mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
main
1860
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d63def425b |
[1/4] Apply checked Megatron checkpoint layouts (#3734)
### What does this PR do? **Problem:** A native checkpoint restore can validate a layout derived from saved tensor metadata but later apply the earlier, deferred layout instead. **Fix:** Carry the checked layout through rank agreement and apply it afterward. Modules without a checked layout retain the deferred callback path. This treats layout values as opaque and works before the GGML changes in the next slice. ### Testing - Source-isolated red/green proof: upstream fails the checked-layout case; the fix passes both checked/deferred cases. Ruff, format and syntax pass. - Native Megatron CI: both checked/deferred regression cases passed ([job log](https://github.com/NVIDIA/Model-Optimizer/actions/runs/47456979207/job/145477291200)); no GPU run was performed locally. ### Before your PR is ready for review Backward compatible; no new dependencies or third-party code; scoped regressions included. Internal restoration fix; no new feature changelog. Claude approval not requested. ### Additional information Part **[1/4]** of the generic exporter stack. Merge **#3734 → #3735 → #3736 → #3727 → #3730**, retargeting each successor after its predecessor merges. Each slice depends only on earlier PRs. Announcement #3726 remains gated on two human approvals after the exporter stack lands. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Improved restoration of sharded extra state so checked checkpoint layouts are applied consistently. Other deferred layouts continue to use their existing handling. * Restoration now checks saved tensor metadata and layout agreement before applying layouts, and clears the restore flag when complete. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Signed-off-by: Hung-Yueh Chiang <hungyuehc@nvidia.com> |
||
|
|
58f6a438e2 |
[OMNIML-6666] [4/4] Document the move of hf_ptq's helpers into the library (#3659)
### What does this PR do? Type of change: documentation **Stack** (merge in order): [1/4] #3656 (merged) → [2/4] #3657 (merged) → [3/4] #3658 (merged) → **[4/4] #3659**. **Problem:** #3656, #3657 and #3658 moved most of `examples/hf_ptq`'s helper modules into the library, and left the stack's CHANGELOG entry for this last PR. Until it lands, scripts that imported those helpers from the example directory have no note of where they went. The Kimi-K3 NVFP4 converter's docstring also still names the MXFP4 cast's old path, `examples/hf_ptq/cast_mxfp4_to_nvfp4.py`. **Fix:** a CHANGELOG entry says what moved where, and the Kimi-K3 docstring names `modelopt.torch.quantization.utils.cast_mxfp4_to_nvfp4`. Recipe-driven AutoQuantize (`examples/hf_ptq/autoquant_utils.py`) stays in the example. It consumes recipes, and `modelopt.recipe` imports `modelopt.torch.quantization`, so it belongs above both packages: in the example now, and in the CLI later. Earlier versions of this PR moved it into `modelopt.recipe`, then into `modelopt.torch.quantization`; this version leaves it as it is on main. ### Testing Documentation only: one CHANGELOG line and one docstring line. Pre-commit passes, mypy included. On CPU, the example's AutoQuantize and `hf_ptq.py` tests (`test_autoquant_utils.py`, `test_hf_ptq_args.py` and `test_hf_ptq_vision_quantization.py`) pass, 124 tests, as on main. ### 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?: ✅ Documentation only. - 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?: N/A Documentation only. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ One entry for the stack. - Did you get Claude approval on this PR?: Not for this version. Claude gave LGTM on the earlier versions, which moved AutoQuantize; this version keeps only their CHANGELOG entry, now without AutoQuantize, and the Kimi-K3 note. ### Additional Information Tracked by OMNIML-6666 (epic OMNIML-3619, nv-modelopt unified entry point), for ModelOpt 0.50.0. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Documentation** * Updated the release notes to clarify where to find model and tokenizer loading, calibration, generation preview, layerwise configuration, and MXFP4 conversion helpers. Scripts that use these helpers should import them from their updated library locations. * Clarified that run checks and the MLflow tool remain available in the examples, and that recipe-driven AutoQuantize remains in its existing location. * Updated the Kimi K3 quantization guide to point to the current MXFP4 conversion reference. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <shengliangx@nvidia.com> |
||
|
|
6af89b6a61 |
Follow up on evaluation guide review feedback (#3721)
### Summary Apply cjluo-nv’s post-merge suggestions from [PR #3270](https://github.com/NVIDIA/Model-Optimizer/pull/3270). The guide now covers representative sampling for question-level analysis, comparisons across sessions, and the minimum number of runs for release evaluations. This PR also adds the guide to the changelog. ### Validation Sphinx built the evaluation guide and its reproducibility notes with zero warnings or errors. The changelog link and `git diff --check` passed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Documentation** * Expanded guidance on comparing checkpoints, detecting regressions, and planning evaluation budgets. * Recommended seeded, category-stratified question sampling and freezing the question IDs used for both models. * Clarified that complete runs can help estimate uncertainty when differences between sessions may exceed within-session noise; paired analysis remains appropriate when question IDs match. * Added release-evaluation guidance referencing ModelOpt comparison requirements, including at least eight valid SciCode runs per checkpoint. <!-- end of auto-generated comment: release notes by coderabbit.ai --> ### 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?: N/A - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ - Did you get Claude approval on this PR?: N/A --------- Signed-off-by: Daniel Korzekwa <dkorzekwa@nvidia.com> |
||
|
|
9c49ed1c6f |
Export INT8 weight-only checkpoints through Megatron-Bridge (#3689)
### What does this PR do? Type of change: New feature **Problem:** Megatron-Bridge's quantized export (`AutoBridge.save_hf_pretrained_modelopt`) packs each weight through ModelOpt's functional quantized-weight export, which refused INT8 weight-only (`INT8_WEIGHT_ONLY_CFG`). So `examples/megatron_bridge/export_quantized_megatron_to_hf.py` sent these checkpoints to `export_mcore_gpt_to_hf`, which needs TP=1 and writes no quantization config for them. This blocks removing `export_mcore_gpt_to_hf`. **Fix:** The functional export now captures INT8 weight-only's per-output-channel `weight_scale` the way it captures FP8 per-channel's, so the TP merge, QKV and gate/up selection already handle it. It packs with the same `to_quantized_weight` and builds the config with the same `process_layer_quant_config` / `convert_hf_quant_config_format` as HF PTQ export: identical int8 weights, `weight_scale` and `W8A16` config. Per-tensor, blockwise, unsigned or non-2-D INT8 weight-only layers are still refused, as are SmoothQuant / AWQ `pre_quant_scale`. The example asks this API what Megatron-Bridge can pack, so INT8 weight-only now routes to Megatron-Bridge with no example change. Megatron-Bridge needs no change at ModelOpt's CI pin or at Megatron-LM main's `megatron/bridge/`: its ModelOpt export is format-agnostic, and it merges and selects scales through this API's axis metadata. Q8_0 is left out. It isn't handled apart from the GGML / IQ formats: it is a `GGML_FORMAT_REGISTRY` entry with `backend="ggml"`, exported by the same GGML branch in every exporter, and packed by the registry's `pack()`, which reuses GPTQ / local-Hessian pinned payloads. Exporting it functionally needs the shared GGML work (moving and TP-merging pinned payloads, plus the example's GGML routing), which is the separate GGML / IQ task. ### Modules touched - `modelopt/torch/export` (`quantized_weight_export.py`, plus the `export_mcore_gpt_to_hf` docstring in `unified_export_megatron.py`): the format support itself, and #3662's list of what Megatron-Bridge can't export. - `examples/megatron_bridge`: one docstring named INT8 weight-only as unpackable. ### Usage ```python import modelopt.torch.quantization as mtq mtq.quantize(megatron_model, mtq.INT8_WEIGHT_ONLY_CFG, forward_loop) bridge.save_hf_pretrained_modelopt(model, export_dir) # any TP / EP / PP ``` ### Testing All in `nvcr.io/nvidia/nemo:26.10` with Megatron-Bridge overlaid at the CI pin (`24b6adc8`), on 2 local GPUs: - `tests/gpu/torch/export/test_export_weight_gpu.py::test_functional_export_matches_existing_helpers_without_mutation`: new `INT8_WEIGHT_ONLY_CFG` case (packed weight and `weight_scale` match HF PTQ's `_export_quantized_weight` bit for bit). Every format's config is now also compared with HF PTQ's `get_quant_config` + `convert_hf_quant_config_format`; all match. - `tests/gpu_megatron/torch/export/test_quantized_mbridge_export.py`: new `qwen3-int8_wo` case: Megatron-Bridge at TP=2 matches HF PTQ export of the same model, bit for bit and config for config. It is compared with HF PTQ because `export_mcore_gpt_to_hf` writes no config for INT8 weight-only. - `tests/unit/torch/export/test_quantized_weight_state.py`: INT8 weight-only added to the canonical-config cases; per-tensor INT8 is still refused. - `tests/examples/megatron_bridge/test_export_routing.py`: the "format Bridge can't pack" case now uses INT8 W8A8. - Reverting the source change fails the new GPU, Megatron-Bridge and unit cases. ### 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 Part of OMNIML-5980, which removes `export_mcore_gpt_to_hf` in 0.51.0: covers INT8 weight-only from "weight formats Megatron-Bridge can't pack (INT8 weight-only, Q8_0)". This updates #3662's deprecation list: the `export_mcore_gpt_to_hf` docstring no longer lists uniform INT8 weight-only checkpoints as exported by neither path (its warning and CHANGELOG entry never named them). Q8_0 stays under "GGML / IQ formats". 🤖 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 * **New Features** * INT8 weight-only (W8A16) checkpoints can now be exported through the Megatron-Bridge workflow, with weights, scales, and quantization settings aligned with Hugging Face PTQ exports. Support is limited to compatible per-channel quantization configurations. * **Documentation** * Clarified that Megatron-Bridge cannot export INT8 W8A8 formats or Medusa heads. Medusa exports with extra modules enabled are documented as unsupported. <!-- 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> |
||
|
|
91fb8a9a27 |
[1/4] [6466805] Support canonical Dynamo weight packing and finalization (#3145)
### What does this PR do? Type of change: new feature Dynamo-captured ONNX graphs name and lay out quantized weights differently from TorchScript graphs. The existing FP8, INT4, MXFP8 and NVFP4 packers can't find or pack those weights, and nothing checks the final graph's domains, opset or metadata. This PR makes the packers handle canonical Dynamo weight paths and adds the finalization step. Nothing calls the Dynamo paths until [2/4]. - **FP8:** keeps calibrated clipping and dtype-changing casts, saturates weights (shared with legacy export), and gives weights that share a scale distinct names. - **INT4 AWQ and MXFP8:** packers select only their own Dynamo Q/DQ nodes and skip the TorchScript-only cast and Gelu rewrites. MXFP8 keeps BF16 and FP16 dequantize types. - **Odd widths:** INT4 and NVFP4 weights with an odd output width now pack, in legacy export too. - **Finalization** validates domains, opset and metadata, and rejects quantized nested subgraphs before mutating the graph. - `fold_dq_fp32_to_fp16_casts` can leave chosen DQ nodes in FP32. ### Usage Internal; the supported entry point arrives in [2/4]. ### Testing - `tests/unit/onnx/test_dynamo_adapter.py`, `test_fold_casts.py`, `quantization/test_qdq_utils.py` and `quantization/test_fp8_mha_exporter.py`: 132 passed at this commit. - `tests/unit/torch/deploy` and `test_tensor_quant_cpu.py` still pass here: 164 passed. - The NVFP4 odd-row and FP32-DQ regressions go through the export helper, so they are in [2/4]. - Ruff, mypy (no new errors) and `git diff --check` passed. ### Before your PR is "*Ready for review*" Follow [Contributor guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md) and [Security Best Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors). Commits are signed and signed off. - Is this change backward compatible?: ✅ — legacy export output is unchanged apart from the odd-width packing fixes. - If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md?: N/A — neither added. - Did you write any new necessary tests?: ✅ - Did you update Changelog?: N/A — one entry for the whole feature, in [2/4]. ### Stack Split from [#2685](https://github.com/NVIDIA/Model-Optimizer/pull/2685), which stays open as a draft reference and is not for merge. Merge in order; each PR targets the one before it. 1. [[1/4] Dynamo weight packing and finalization](https://github.com/NVIDIA/Model-Optimizer/pull/3145) 2. [[2/4] Helper-owned Dynamo ONNX export](https://github.com/NVIDIA/Model-Optimizer/pull/3146) 3. [[3/4] ONNX example wrapper options](https://github.com/NVIDIA/Model-Optimizer/pull/3147) 4. [[4/4] Torch ONNX example CLI options](https://github.com/NVIDIA/Model-Optimizer/pull/3148) 🤖 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** * Improved ONNX export handling for quantized models, including FP8, INT8, INT4, MXFP8, and NVFP4 weights. * Corrected weight packing and shape handling, including for odd-sized rows, and prevented FP8 weight values from exceeding the supported range. * Improved type and metadata consistency in exported graphs, while preserving FP32 values where converting to FP16 could lose precision. * **New Features** * Added validation and normalization of exported graphs, with clearer checks for unsupported operators and inconsistent opset versions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Ajinkya Rasane <131806219+ajrasane@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
1127ee6923 |
[OMNIML-6340] Restore forwards and free GPTQ Hessians when calibration or an update fails (#3704)
### What does this PR do? Type of change: Bug fix **Problem:** When GPTQ calibration fails, it leaves state behind. - If anything raises after the forwards are patched, whether in `forward_loop`, while allocating the fused-expert Hessians, or on Ctrl-C, each quantized linear keeps GPTQ's Hessian-accumulating `forward`. The model then holds the helper and its Hessian after the exception is gone, and every later forward keeps adding to it. - If an update raises, the failed helper and every helper not yet updated keep their Hessians alive for as long as the traceback lives. **Fix:** - In `gptq()`, one `try/finally` spans helper creation through the last update. It restores the forwards and frees every helper, including expert helpers already taken for an update. `GPTQHelper.cleanup()` and `free()` are idempotent, so the success path is unchanged. - `GPTQHelper.update_weights()` frees its own helper when it returns or raises, so callers no longer pair it with `free()`. `GGMLGPTQHelper` overrides `_update_weights()` instead. ### Usage No API change. ### Testing - New `test_a_failed_gptq_run_restores_forwards_and_frees_every_hessian`: INT4 GPTQ on two 128×128 linears, with the second linear's `setup()`, the calibration pass or the first update raising. It checks that both Hessians are freed, both forwards are restored, and a later forward runs. Each case fails without the fix. - `test_gptq.py`, `test_ggml_gptq.py`, `test_layerwise_calibrate.py`, both Nemotron-H tests and the GPTQ tests in `test_fused_experts.py` pass on CPU (145 passed). GPU tests were not run, including `test_an_update_that_may_move_fits_its_room`, which now sizes its room before the update frees the helper. Pre-commit was run only on the changed files. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ Only failure paths change. - 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)?: N/A, not a user-facing feature or a critical bug. - Did you get Claude approval on this PR?: ❌ ### Additional Information Split out of #3288 at a maintainer's request; #3288 (IQ GSQ) stacks on this PR. It also needs the 0.49.0 cherry-pick, since #3288 does. 🤖 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** * Improved GPTQ recovery when setup, calibration, or weight updates fail. Cleanup helps prevent failed operations from affecting subsequent model forwards. * Improved handling of fused-expert weights during GPTQ calibration and updates. * Ensured temporary GPTQ resources are released after updates, including when errors occur. * **Tests** * Added regression coverage for GPTQ failure scenarios, cleanup, and subsequent model forwards. * Added coverage to verify temporary resources are cleared when GGML GPTQ quantization fails. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Ajinkya Rasane <131806219+ajrasane@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
09137c28a9 |
[OMNIML-6666] [3/4] Move hf_ptq's layerwise-config helpers and MXFP4 cast into modelopt.torch.quantization (#3658)
### What does this PR do? Type of change: New feature (library home for example helpers) **Stack** (merge in order): [1/4] #3656 (merged) → [2/4] #3657 (merged) → **[3/4] #3658** → [4/4] #3659. **Problem:** two pieces of `examples/hf_ptq` stay outside the library. The first is the helpers that read and retarget a quantize config's `layerwise` blocks: which entry exports per layer, where a run resumes, where its shards go. The second is the MXFP4 → NVFP4 cast behind `--cast_mxfp4_to_nvfp4`. The cast's numerics are already library code (`quantization/utils/numeric_utils.py`), but its application to a model is not, and the DeepSeek-V4 and Kimi-K3 converters point their readers at the example's copy. **Fix:** both move into `modelopt.torch.quantization.utils`, and `hf_ptq.py` imports them from there. `_layerwise_blocks`, which `hf_ptq.py` imports, becomes public as `layerwise_blocks`. The DeepSeek docs that cited the example's cast now cite the library module; the Kimi-K3 converter's note follows in #3659, the next PR in this stack. Beyond the move, the cast prints its summary, unmatched layers included, once per run on rank 0, and `layerwise_calib` declares its public names in `__all__`. | From | To | |---|---| | `example_utils.layerwise_export_block`, `recipe_layerwise_blocks`, `layerwise_export_requested`, `default_layerwise_resume_dir`, `needs_checkpoint_path_update`, `resolve_checkpoint_dir`, `set_layerwise_export_dir`, `_layerwise_checkpoint_dir` | `modelopt.torch.quantization.utils.layerwise_calib` | | `example_utils._layerwise_blocks` | `layerwise_calib.layerwise_blocks` | | `examples/hf_ptq/cast_mxfp4_to_nvfp4.py` (`apply_to_model`, `build_amax_map`, `force_weight_quantizers_static`, `quantizer_name_from_blocks_key` and their private helpers) | `modelopt.torch.quantization.utils.cast_mxfp4_to_nvfp4` | The layerwise helpers stay functions over the `quant_cfg` dict that `mtq.quantize` takes, since what they set belongs to a run, not to a config. `set_layerwise_export_dir` points the recipe's placeholder `export_dir` at the run's export path, `default_layerwise_resume_dir` puts an unset `checkpoint_dir` beside it, and `resolve_checkpoint_dir` then appends `<model>_<config hash>`, so one recipe serves several models and export paths. `LayerwiseConfig` holds the values `mtq.quantize` uses as given, and the config types validate one algorithm entry at a time, while the export rule these helpers check spans the list: at most one entry exports, and it must be the last. `load_recipe`'s dotlist overrides apply fixed strings at load, but the resolved directory hashes the loaded config, the key path needs the exporting entry's index, and directory recipes take no overrides. The cast and `export/shard_cast_utils.py` share their math (`numeric_utils.py`) but not their job. `apply_to_model` runs on the calibrated model in `hf_ptq.py`: it reads a GPT-OSS checkpoint's MXFP4 `*_scales` and `*_blocks` and pins each NVFP4 weight quantizer's `_global_amax` and per-block `_amax`, so the usual export writes the weights. `shard_cast_utils.py` holds the primitives of the offline DeepSeek-V4 and Kimi-K3 converters, which rewrite the release's shards without loading the model. The cast's private shard lookup moves unchanged. It reads the index's `weight_map`, as `indexed_weight_map` does, and differs only without an index: it takes a lone `*.safetensors` file of any name and raises otherwise, where `indexed_weight_map` takes only `model.safetensors` and returns `{}` otherwise. Switching would change those two cases, so the move leaves it; being private, it can switch later without an API change. ### Modules touched - `modelopt.torch.quantization`: the layerwise helpers beside the layerwise calibration that consumes the blocks, and the cast beside its numerics. - `examples/hf_ptq`: drops them and imports them. ### Usage ```python import modelopt.torch.quantization as mtq from modelopt.torch.quantization.utils.cast_mxfp4_to_nvfp4 import ( apply_to_model, force_weight_quantizers_static, ) force_weight_quantizers_static(quant_cfg["quant_cfg"]) # NVFP4 weights as static blocks model = mtq.quantize(model, quant_cfg, forward_loop) apply_to_model(model, "/path/to/mxfp4_checkpoint") # pin the scales to the MXFP4 source ``` ### Testing - The layerwise helpers' tests move to `tests/unit/torch/quantization/test_layerwise_calibrate.py`. The cast's tests move to `tests/unit/torch/quantization/test_cast_mxfp4_to_nvfp4.py`, without the `sys.path` shim they needed. The GPU cast test imports the library. - `test_resolve_checkpoint_dir_keeps_each_entrys_base` now compares the checkpoint bases by directory: the windows job, which runs `tests/unit`, joins them with a backslash. - CPU only (Python 3.13, torch 2.10, transformers 5.4): the moved tests, the rest of `test_example_utils.py`, and the `hf_ptq` tests that drive the layerwise export and the AutoQuantize finalize (`test_hf_ptq_args.py`, `test_export_quantized_context.py`), 190 passed. - Pre-commit, mypy included, passes against main. GPU tests are not run locally (the GPU cast test collects); CI runs them now that this PR targets main. ### 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?: ✅ `hf_ptq.py`'s command line is unchanged. Scripts that imported the cast or these helpers from the example directory import them from the library. - 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?: N/A The helpers' tests move with them. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: N/A One entry for the stack, in [4/4]. - Did you get Claude approval on this PR?: ✅ LGTM. Claude can't approve a PR that moves tests, so its review asks a human reviewer to confirm the move. ### Additional Information Tracked by OMNIML-6666 (epic OMNIML-3619, nv-modelopt unified entry point), for ModelOpt 0.50.0. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Refactor** * Quantization examples now use shared MXFP4-to-NVFP4 conversion and layerwise calibration and export workflows. * Layerwise exports validate configuration and handle checkpoint and resume paths consistently. * Conversion progress and unmatched-layer messages are reported through rank-aware logging. * **Documentation** * Updated DeepSeek and Kimi guidance to reference the shared conversion implementation. * **Tests** * Added coverage for layerwise export configuration and checkpoint handling, and updated conversion tests to use the shared implementation. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <shengliangx@nvidia.com> |
||
|
|
f23dfdf4a6 |
[6323490] Give autotune benchmark candidates realistic activation scales (#3410)
### What does this PR do? Type of change: Bug fix **Problem:** ONNX Autotune benchmarks every candidate with the same dummy scale (`default_q_scale=0.1`) on every Q/DQ. With all scales equal, TensorRT drops every requantization, so candidates run faster than any calibrated model can, and the search ranks placements on a proxy the shipped model never matches. On a VovNet-based model (Orin, DriveOS 6.5.6.0 QNX Safety, TRT 10.15.4.1), the candidate measured 30.69 ms while the model the same run emitted measured 34.52 ms. **Fix:** Give activation Q/DQ deterministic, name-hashed scales that differ across requantization boundaries and are shared where quantization unifies them: Concat inputs and output (as `concat_elimination` does, when the final quantization applies it, over the nodes it quantizes after `nodes_to_quantize` and `nodes_to_exclude`) and the ends of Flatten/Reshape/Squeeze/Transpose/Unsqueeze chains. With these scale groups the candidate measured 34.51 ms against 34.52 ms shipped. **Why synthetic scales rather than calibration ranges:** - Latency depends only on which neighboring scales are equal, not on their values: replacing the shipped model's 86 activation scale values with synthetic ones left its latency unchanged (34.52 ms on the model above). - The AutoTune-only CLI (`python -m modelopt.onnx.quantization.autotune`) takes no calibration data. - Calibrated scales depend on the Q/DQ placement (concat elimination merges the ranges of each Concat group), so they would have to be recomputed for every candidate by re-running calibration. Synthetic scales cannot reproduce equalities that come from the data, e.g. with `passes=[]` the Concat input with the largest value range gets the same scale as the output. ### Modules touched - `modelopt/onnx/quantization/autotune`: the fix itself; candidate export assigns the scales, and resuming a state file written before this change keeps the uniform scale its latencies were measured with. - `modelopt/onnx/quantization/qdq_graph.py`: candidates share the Concat grouping of the `concat_elimination` pass instead of a copy that could drift from it. - `modelopt/onnx/quantization/fp8.py`: FP8 candidates reuse the scale rescale `int8_to_fp8` applies, so their scales stay distinct after the same conversion. - `modelopt/onnx/quantization/quantize.py`: tells Autotune whether the final quantization applies `concat_elimination` (not when `passes` omits it or `calibrate_per_node=True`) and which nodes it quantizes, so candidates share Concat scales the same way. ### Usage The new behavior is the default for `quantize(autotune=...)` and both CLIs (`python -m modelopt.onnx.quantization --autotune=...` and `python -m modelopt.onnx.quantization.autotune`); they expose no switch for it. `quantize()` sets the new `Config.concat_elimination`, `final_nodes_to_quantize` and `final_nodes_to_exclude` from its arguments. Code that drives the autotuner with its own `Config` can restore the previous uniform scales: ```python config = Config(use_varied_activation_scales=False) ``` ### Testing - `pytest -q tests/unit/onnx` (1033 passed), including 212 in `tests/unit/onnx/quantization/autotune`. Against an earlier revision of this change (plain hashed scales, rearrange ops grouped only between quantized tensors), the new rearrange-chain and collision tests fail; without the FP8 handling, 85 of 3000 groups share a scale after `int8_to_fp8`. - Candidate vs calibrated model, through the quantizer call `quantize(autotune=...)` makes, on CPU (max and entropy): two Concats joined by an input without Q/DQ share one scale in both, Concats without a shared input get different scales in both, and a Concat read only without Q/DQ forms no group in either (`test_candidate_scale_sharing_matches_the_calibrated_model`, `test_concat_read_only_without_qdq_forms_no_group`). They also match when `nodes_to_quantize`/`nodes_to_exclude` leave both Concats unquantized (`test_candidate_scale_sharing_follows_the_final_node_selection`) and with `calibrate_per_node=True` (`test_per_node_calibration_shares_no_concat_scale`). With `passes=[]`, every pair matches except the data-dependent case above. - Resuming from a state file written before this change keeps the uniform scale (`test_resume_keeps_the_activation_scales_the_state_was_measured_with`, which fails without the fix), and only runs that keep it, as the AutoTune-only CLI does, warn about it. Resuming without re-profiling with a different `concat_elimination` or final node selection raises `ValueError` (`test_resume_rejects_scale_sharing_the_state_was_not_measured_with`). - `pre-commit run --files <changed files>` - On device (setup above, `trtexec_safe --useCudaGraph`, median of 3 engine loads per build): candidate 34.51 ms (median of 5 builds, range 34.49-34.55 ms) vs shipped 34.52 ms. These builds predate the final rounding of the scale values; the final code gives that model the same Q/DQ placement and scale groups. - Rearrange chains, on device (same setup) with a small transformer model whose query/key/value are Unsqueezes of one tensor, Q/DQ on every MatMul input: candidate 0.12316 ms before vs 0.10395 ms after sharing scales along the chains (median of 3 builds x 3 loads, build range under 0.00004 ms). The FP16 model runs 0.08829 ms. - `tests/gpu/onnx/quantization/autotune` not run: TensorRT 10.15 does not support this workstation's GPU (SM 12.0). - This PR refactors `get_concat_eliminated_tensors` in `qdq_graph.py` and the node selection in `get_ort_quantization_config`, which every INT8/FP8 `quantize()` run uses. On 287 local real models, both give the same result as before (the node selection, for models whose node names are unique); `get_concat_eliminated_tensors` was also compared on 60,000 random graphs. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ API-compatible. Autotune results change by design, and `default_q_scale` applies only to weight Q/DQ unless `use_varied_activation_scales=False`. A run of `python -m modelopt.onnx.quantization.autotune` resumed from a state file written before this change keeps the uniform scale its latencies were measured with and logs a warning; `quantize(autotune=...)` re-profiles as before. Resuming through `region_pattern_autotuning_workflow` without `model_transform` with a different `concat_elimination`, `final_nodes_to_quantize` or `final_nodes_to_exclude` than the state was measured with raises `ValueError`. - 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` to run after opening) ### Additional Information NVBug 6323490. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Arata Miyamoto <amiyamoto@nvidia.com> Signed-off-by: Gwena Cunha <4861122+gcunhase@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Gwena Cunha <4861122+gcunhase@users.noreply.github.com> |
||
|
|
b018e68b33 |
Export GGML / IQ formats through Megatron-Bridge (#3719)
### What does this PR do?
Type of change: New feature
**Problem:** Megatron-Bridge's quantized export
(`AutoBridge.save_hf_pretrained_modelopt`) packs each weight through
ModelOpt's functional quantized-weight export, which refused the GGML /
IQ formats (`iq1_s`, `iq1_m`, `iq2_xxs`, `iq2_xs`, `iq2_s`, `q8_0`). So
`examples/megatron_bridge/export_quantized_megatron_to_hf.py` sent every
GGML checkpoint to `export_mcore_gpt_to_hf`, which writes them only at
TP=1 and PP=1 and is deprecated in 0.50.0 (removed in 0.51.0). The
GLM-5.3-Flash IQ2_S recipes are the main users.
**Fix:** GGML payloads depend on quantizer state, not just the weight:
GPTQ / imatrix / local-Hessian pin their codes and scales to the
TP-local weight quantizer, and fake quant caches the payload it decoded.
So `capture_quantized_weight_export_state` packs the module's own
(local) weight with its quantizer, exactly as the HF exporter does
(`GGML_FORMAT_REGISTRY[fmt].pack(weight, quantizer)`), and carries the
`[rows, blocks, block_bytes]` payload as its state tensor. Its axis
metadata lets the existing merge / select concatenate TP shards (rows,
or whole blocks for row-parallel) and pick fused gate/up, QKV, ... rows;
`export_quantized_weight_tensors` returns it. GGML blocks are encoded
independently, so a shard's payload is the matching slice of the TP=1
payload. A weight whose (TP-local) input width isn't a multiple of the
block size (256, or 32 for `q8_0`) is refused, since its row-parallel
shards would split blocks; so is a transposed or per-expert quantized
view, and a selection that reorders values within a block. The spec
stays metadata-only. The config comes from the same
`process_layer_quant_config` / `convert_hf_quant_config_format` as both
other exporters.
The example now routes GGML checkpoints to Megatron-Bridge at any TP /
EP / PP; it still falls back to `export_mcore_gpt_to_hf` (TP=1, PP=1)
where Megatron-Bridge can't take one, e.g. a TP size that splits blocks
or `--modelopt_megatron_exporter`.
`examples/hf_ptq/convert_ggml_to_int8.py`, the documented way to serve a
GGML export (e.g. GLM-5.3-Flash IQ2_S) on vLLM, now also reads
Megatron-Bridge exports: they keep the quantization config inline in
`config.json` (no `hf_quant_config.json`) and describe MoE experts by
`<experts>.<projection>` rather than per expert.
Megatron-Bridge needs no change at ModelOpt's CI pin (`24b6adc`):
`check_exportable_quantizers` only checks quantizer names, and the
export gathers and broadcasts state tensors of any shape and dtype.
Megatron-LM's `megatron/bridge` uses the same format-agnostic path.
### Modules touched
- `modelopt/torch/export`: the format support
(`quantized_weight_export.py`), and `export_mcore_gpt_to_hf`'s docstring
/ warning, which listed GGML as something Megatron-Bridge doesn't
export.
- `examples/megatron_bridge`: the routing that sent every GGML
checkpoint to ModelOpt's exporter.
- `examples/hf_ptq`: `convert_ggml_to_int8.py` must read the
Megatron-Bridge exports this routing now produces, or the GLM-5.3-Flash
IQ2_S serving path breaks.
### Usage
```python
mtq.quantize(megatron_model, load_recipe("general/ptq/iq2_s").quantize.model_dump(), forward_loop)
bridge.save_hf_pretrained_modelopt(model, export_dir) # any TP / EP / PP with whole blocks per TP shard
```
### Testing
In `nvcr.io/nvidia/nemo:26.10` with Megatron-Bridge overlaid at the CI
pin (`24b6adc`), on 2 local GPUs (sm_89):
- `tests/gpu_megatron/torch/export/test_quantized_mbridge_export.py`:
new `llama-iq2_s_mlp-q8_0_attn` case (IQ2_S MLP, Q8_0 attention):
Megatron-Bridge at TP=2 matches `export_mcore_gpt_to_hf` at TP=1 bit for
bit, with the same `quantization_config`.
- `tests/unit/torch/export/test_quantized_weight_state.py`: for all six
formats, plain and with a GPTQ-pinned payload, capture + export matches
the HF exporter's packed weight bit for bit, and the spec builds the HF
exporter's config; column- and row-parallel shards merge, and fused rows
select, to the full weight's payload; a weight whose input width splits
blocks is refused.
- `tests/unit/torch/quantization/test_repair.py`: functional export of a
fused-expert GGML weight seen through a per-expert calibration view now
hits the per-expert-view refusal instead of the old GGML-backend
refusal.
- `tests/examples/megatron_bridge/test_export_routing.py`: a GGML
checkpoint goes to Megatron-Bridge at TP=2 / PP=2, and falls back
(asking for TP=1 / PP=1) when its shards split blocks.
- Reverting the source changes fails each new case.
-
`tests/gpu_megatron/torch/export/test_quantized_mbridge_export.py::test_glm5_next_ggml_export_matches_and_converts_to_int8`:
tiny GLM-5.3-Flash with the
`iq2_s_experts-nvfp4_down-q8_0_shared_dense-gptq` recipe (GPTQ;
layerwise off since the test's forward loop can't drive it):
Megatron-Bridge's IQ2_S (GPTQ-pinned), Q8_0 and NVFP4 MLP tensors match
`export_mcore_gpt_to_hf`'s bit for bit, and `convert_ggml_to_int8.py`
turns both into the same INT8 tensors. Without the converter change it
fails on the Megatron-Bridge export.
- `tests/examples/hf_ptq/test_convert_ggml_to_int8.py`: the KV-cache
conversion test now also runs on inline-only (Megatron-Bridge-style)
exports, GGML-only and mixed, and checks the FP8 KV-cache scheme
survives; unknown inline KV-cache schemes are refused; the
`hf_quant_config.json` cases still pass.
### 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
Part of OMNIML-5980 (remove `export_mcore_gpt_to_hf` in 0.51.0): its
"GGML / IQ formats" prerequisite. #3689 covers INT8 weight-only in the
same file; the two changes are independent.
The GLM-5.3-Flash IQ2_S recipes
(`models/zai-org/GLM-5.3-Flash-BF16/ptq/iq2_s_experts-*-gptq`) now
export through Megatron-Bridge, including at EP > 1 with TP / PP > 1.
What they still need, outside this PR:
- Megatron-Bridge's per-layer config names MoE experts
`<experts>.<projection>` and `export_mcore_gpt_to_hf`'s
`<experts>.<index>.<projection>`; both describe the same tensors (the
converter now reads either).
- Megatron-Bridge writes some unquantized GLM-5.3-Flash tensors (mHC
`hc_*_fn`, indexer `index_kpool_compress_ape`) in FP32 where
`export_mcore_gpt_to_hf` writes BF16; unrelated to GGML.
🤖 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
* **New Features**
* GGML and IQ quantized weights can now be exported through
Megatron-Bridge in supported configurations. Tensor-parallel shards must
preserve complete quantization blocks; unsupported layouts remain
subject to existing export constraints.
* The GGML-to-INT8 converter now reads quantization settings from either
`hf_quant_config.json` or inline `config.json` metadata, and supports
exports combining GGML with other quantization formats.
* **Documentation**
* Updated export guidance to clarify supported formats, parallelism
requirements, exporter selection, and Megatron-Bridge’s limitation for
EAGLE modules.
<!-- 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>
|
||
|
|
012480e147 |
Fix INT4 AWQ DequantizeLinear axis for Gemm with transB=1 (#3531)
### What does this PR do? Type of change: Bug fix **Update:** #3551 has since landed on main and fixes the 4-bit blocked axis by inferring it from the stored shapes, so I merged main and dropped that part here. What's left is below. **Problem:** - **Silent wrong outputs at 8 bit.** `awq_clip` and `awq_lite` quantize the weight of a `Gemm` with `transB=1` (what `torch.onnx.export` writes for `nn.Linear` on a 2-D input) transposed and store it back as `[N, K]`. If mixed precision (`enable_mixed_quant` + `layers_8bit`) leaves that layer at 8 bit, its DQ gets per-channel `axis=1`. For a square weight (N == K) that loads and runs, but the per-output-channel scales are applied along the input dim. Max rel. error is 0.84 vs fp32, compared to 0.004 with the right axis. #3551 leaves per-channel DQs unchanged, so this still happens on main. - **Column-major export (`use_column_major=True`):** - 8-bit per-channel weights of `MatMul` and `Gemm(transB=0)` are stored as `[N, K]` after the transpose but keep `axis=1`, so square ones run with the scales on the input dim (all of awq_clip, awq_lite and rtn_dq). - Asymmetric `awq_lite` (`use_zero_point=True`) passes a zero point in a different layout than its scale, so ORT refuses to run the model. - A weight shared by several `MatMul`/`Gemm` nodes only gets its first consumer rewritten, so the model fails to run. This hits direct `int4.quantize` callers, since only the public wrapper duplicates shared constants. **Fix:** - awq_clip and awq_lite record which weights they stored transposed, and `insert_dq_nodes` sets the per-channel axis from the stored layout for transposed and non-transposed weights, in both row- and column-major mode. - `apply_column_major_transformation` transposes zero points with the scales, and per-channel zero points get flattened like the scales. - `insert_transpose_nodes_for_column_major` takes the names of the weights the export transposed and rewrites only their DQ outputs, for every consumer, with one `Transpose` per output tensor, named so it can't collide with existing tensors or nodes, including those in If/Loop/Scan subgraphs. Other DQ nodes already in the graph, named or not, are left alone. - awq_lite inserts its pre-quant scale Muls before the column-major rewrite. They're matched on the DQ -> MatMul/Gemm edge, so a graph-input `MatMul`/`Gemm` used to lose its inverse scale in column-major mode and give wrong outputs (also on main, with or without zero points). Out of scope: shared weights with `awq_lite` fail earlier on main ("Encountered a node not in the graph") in row-major mode too. That's a separate issue. ### Usage ```python from modelopt.onnx.quantization.int4 import quantize # Gemm(transB=1) with a square weight, kept at 8 bit by mixed precision model = quantize("gemm.onnx", "awq_clip", calib_data, enable_mixed_quant=True, layers_8bit="gemm") # before: runs, but per-channel scales hit the input dim (rel. err ~0.84); after: ~0.004 ``` ### Testing All in `tests/unit/onnx/quantization/test_quantize_zint4.py`, run against today's main (with #3551): - `test_awq_gemm_trans_b` (awq_clip/awq_lite × 4-bit/mixed 8-bit × row/column-major, 8 cases). The 2 row-major 8-bit cases fail on main; the others now pass on main too and stay as regression coverage. - `test_awq_lite_gemm_trans_b_zero_point` (asymmetric awq_lite × 4-bit/mixed 8-bit × row/column-major, 4 cases). 3 fail on main. - `test_column_major_shared_weight` (two `Gemm`s or two `MatMul`s sharing one weight × awq_clip/rtn_dq, 4 cases). All 4 fail on main. - `test_column_major_gemm_no_trans_b` (square `Gemm(transB=0)` behind a `Relu`, column-major × asymmetric awq_lite/awq_lite/awq_clip/rtn_dq × 4-bit/mixed 8-bit, 8 cases). 5 fail on main: the 4 mixed 8-bit cases (per-channel scales on the wrong axis) and 4-bit asymmetric awq_lite. - `test_column_major_transpose_skips_other_dq_nodes`: two unrelated unnamed DQs plus one transposed weight; only the latter gets a `Transpose`, checked numerically in ORT. One existing output already uses the name the new `Transpose` output would default to. - `test_column_major_awq_lite_graph_input_pre_quant_scale` (graph-input `MatMul`/`Gemm(transB=0)` × with/without zero points, 4 cases): column-major matches row-major with a nontrivial pre-quant scale. All 4 fail before this fix. - `test_column_major_transpose_name_avoids_subgraph_names`: both `If` branches define the default `Transpose` output name; the export passes `onnx.checker` with `full_check=True`. All pass with the fix. `tests/unit/onnx/quantization` passes (557 passed, 2 skipped, 12 xfailed), and ruff check/format are clean. CPU only, I didn't test TensorRT. ### 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?: N/A ### Additional Information Modules touched: `modelopt/onnx/quantization/int4.py` (track transposed weights in awq_clip/awq_lite; zero points follow the scales) and `modelopt/onnx/quantization/qdq_utils.py` (`insert_dq_nodes` per-channel axis; `apply_column_major_transformation` zero points; `insert_transpose_nodes_for_column_major` takes the transposed weight names). Open PR #2867 touches AWQ-Lite scale math in the same file, but it's a separate bug. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Fixed ONNX Runtime failures when quantizing `Gemm` models with `transB=1` using AWQ Clip or AWQ Lite, including mixed-precision models with 8-bit weights. * Corrected column-major quantization for shared weights used by multiple operations, including per-channel scaling for 8-bit `MatMul` and `Gemm` weights with `transB=0`. * Fixed column-major handling of AWQ Lite zero points for `Gemm` models with `transB=1`. * **New Features** * Added column-major support for asymmetric AWQ Lite quantization of `Gemm` models with `transB=1`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Bndrwe <208378793+Bndrwe@users.noreply.github.com> Signed-off-by: Gwena Cunha <4861122+gcunhase@users.noreply.github.com> Co-authored-by: Gwena Cunha <4861122+gcunhase@users.noreply.github.com> |
||
|
|
430e0bfeb4 |
[2/4] Quantization: price static NVFP4 at 4.5 effective bits in AutoQuantize (#3631)
### What does this PR do? Type of change: Bug fix Part of a 4-PR stack (merge in order): [1/4] fused-expert cost (#3630) → **[2/4] this PR (#3631)** → [3/4] local Hessian across ranks (#3632) → [4/4] calibrator memory (#3633). **Problem:** `configs/numerics/nvfp4.yaml` (dynamic block scales) declares `effective_bits: 4.5` for AutoQuantize's cost (4-bit values + one FP8 scale per 16). `nvfp4_static.yaml`, used by the MSE and local-Hessian presets, stores exactly the same but declares nothing and falls back to the `num_bits` heuristic (4.0). A search over the static presets sees NVFP4 0.5 bit cheaper than one over the dynamic preset and overshoots the budget. **Fix:** Declare `effective_bits: 4.5` in `nvfp4_static.yaml`. This changes saved candidate costs: a resumed search recomputes them from the model (#3630). It also changes the static presets' config signature, so a saved AutoQuantize search checkpoint over static NVFP4 will not resume across this change. A checkpoint saved with #3630 but before this PR would keep the 4.0-bit static NVFP4 price without a warning; the stack lands in one release, so no released checkpoint is in that state. ### Testing Ran on a GB300 node (4 GPUs) with the four stacked PRs applied to `main`: `tests/unit/torch/quantization/test_local_hessian.py`, `test_autoquant.py`, `tests/unit/torch/utils/test_distributed_calibration.py` and `tests/gpu/torch/quantization/test_local_hessian_gpu.py`: 180 passed, 1 skipped. With the library changes reverted, each new test fails. Not run: other GPU suites, multi-node. New parametrized test: dynamic and static NVFP4 numerics both price at 4.5/16. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ❌ — an AutoQuantize search checkpoint saved with a static-NVFP4 format under the old 4-bit price does not resume; rerun the search with a fresh checkpoint path. - 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?: ❌ 🤖 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** * Corrected AutoQuantize’s size estimates for static NVFP4 weights to account for scale data, bringing them in line with dynamic NVFP4 estimates. Searches using static presets should now stay within the selected size budget. * Checkpoints created with the previous estimate are not compatible with resumed searches. Start a new search using a fresh checkpoint path. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Signed-off-by: weimingc <17592131+meenchen@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
11224e371a |
Move deployment tests to per-checkpoint YAML with shared backend templates (#3674)
### What does this PR do?
Type of change: New tests
**Problem:** All Hugging Face deployment cases lived in a single large
Python file (`tests/examples/hf_ptq/test_deploy.py`), repeating
vLLM/SGLang/TensorRT-LLM engine kwargs across ~80 checkpoints, lacking
per-run backend/TP/YAML override controls, and lacking deployment
coverage for six newly published checkpoints (including static NVFP4
image generation).
**Fix:**
- Move the 80 Hugging Face deployment cases into per-checkpoint YAML
files under `tests/examples/hf_ptq/deploy_cases/` with explicit opt-in
backend templates in `deploy_cases/templates.yaml`, and add deployment
coverage for six published checkpoints (Nemotron 3.5 Super VL BF16,
NVFP4, and NVFP4-LiLiCorr, Muse Spark DFlash2, Step-5 Preview NVFP4, and
Qwen-Image NVFP4) across vLLM, SGLang, and TensorRT-LLM.
- Add pure-Python catalog loading/override resolution
(`--deploy-backend`, `--deploy-tp`, `--deploy-config`) with strict
collection-time validation (duplicate keys, nested template overrides,
`IMAGE_PIPELINE_CLASSES`, reserved model/TP engine fields).
- Verify static NVFP4 active shards/block scales on image checkpoints
(`tests/_test_utils/image_deploy_utils.py`), keep default Hub downloads
in an owned temporary cache directory, and clean up newly downloaded
snapshots/blobs/refs after their last selected consumer even when
`HF_HUB_CACHE`/`HF_HOME` is set (while preserving pre-existing staged
snapshots and refs).
**Why a dedicated `deploy_config.py` loader instead of
`modelopt/torch/opt/config_loader.py` (`$import`) +
Pydantic/OmegaConf:**
- `modelopt/torch/opt/config_loader.py` imports
`modelopt.torch.opt.config` (pulling in `torch` and quantization
packages) and hardwires `BUILTIN_CONFIG_ROOT =
files("modelopt_recipes")`. `deploy_config.py` intentionally depends
only on stdlib + PyYAML so CPU-only QA planning/selection agents can
load and validate the deployment catalog without installing `torch` or
`modelopt`.
- `yaml.safe_load` / `config_loader.py` silently overwrite duplicate
YAML keys, whereas `deploy_config.py` rejects duplicate keys via a
strict `SafeLoader` constructor.
### Usage
```bash
# Run a specific checkpoint on one backend using its checked-in YAML recipe
pytest --run-release tests/examples/hf_ptq/test_deploy.py \
-k "Llama-3.1-8B-Instruct-NVFP4" \
--deploy-backend trtllm
# Override backend/TP or native engine options via a run YAML
pytest --run-release tests/examples/hf_ptq/test_deploy.py \
-k "Qwen3-32B-NVFP4" \
--deploy-backend vllm \
--deploy-tp 4 \
--deploy-config path/to/override.yaml
```
### Testing
- **Unit tests (CPU):**
- `PYTHONPATH=tests pytest --noconftest -o addopts="" -q
tests/unit/examples/test_image_deploy_utils.py
tests/unit/examples/test_deploy_config.py
tests/unit/examples/test_deploy_fixtures.py` — **57 passed** (slowest
test 0.04s).
- **Static checks:** `ruff check` (including `ISC`) and `ruff format
--check` passed on all modified files.
- **Final-head GPU text deployment validation on B300 (one case per
backend):**
- `test_llama[nvidia/Llama-3.1-8B-Instruct-NVFP4_trtllm]`
(`nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc4`, TP1, source rev
`3e3a410b7a`) — **PASSED** (272s).
- `test_llama[nvidia/Llama-3.1-8B-Instruct-NVFP4_vllm]`
(`vllm/vllm-openai:v0.34.0`, TP1, source rev `3e3a410b7a`) — **PASSED**
(119s).
- `test_llama[nvidia/Llama-3.1-8B-Instruct-NVFP4_sglang]`
(`lmsysorg/sglang:v0.5.23`, TP1, source rev `ec0898fe21` — identical
`tests/` tree prior to rebase onto `7024de11ad`) — **PASSED** (332s).
- **Earlier B300 validation for new checkpoints (VLM, DFlash, and image
generation):**
| Case | Backend | Tested Image | Effective TP | Checkpoint Revision |
Source Rev | Result / Evidence |
| --- | --- | --- | --- | --- | --- | --- |
| `nvidia/Qwen-Image-NVFP4` | TRT-LLM VisualGen |
`nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc3` | 1 | `4928c00477`
(pinned in YAML) | `2e868af7e3` | PASSED (108s, static NVFP4 + RGB
image) |
| `nvidia/Qwen-Image-NVFP4` | SGLang Diffusion |
`lmsysorg/sglang:v0.5.23` | 1 | `4928c00477` (pinned in YAML) |
`09d27bb772` | PASSED (185s, static NVFP4 + RGB image) |
| `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4` | TRT-LLM |
`nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc3` | 1 | `ae1368329b` |
`09d27bb772` | PASSED (VLM image description) |
| `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16` | TRT-LLM |
`nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc3` | 2 | `fb0ee0bc6b` |
`09d27bb772` | PASSED (VLM image description) |
| `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4-LiLiCorr` |
TRT-LLM | `nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc3` | 1 | target
`ae1368329b`, draft `292bf1efc0` | `09d27bb772` | PASSED
(`drafted_tokens=98`) |
| `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-{BF16,NVFP4,LiLiCorr}`
| vLLM | `vllm/vllm-openai:v0.34.0` | 2 / 1 / 1 | `fb0ee0bc6b` /
`ae1368329b` / `292bf1efc0` | `09d27bb772` | 3/3 PASSED |
| `nvidia/Muse-Spark-Open-816B-A42B-DFlash2` | TRT-LLM |
`nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc3` | 4 (EP4) | target
`75271573ed`, draft `22e2669e4c` | `09d27bb772` | PASSED
(`drafted_tokens=973`) |
| `nvidia/Muse-Spark-Open-816B-A42B-DFlash2` | SGLang |
`lmsysorg/sglang:v0.5.23` | 4 (EP4) | target `75271573ed`, draft
`22e2669e4c` | `09d27bb772` | PASSED (`spec_verify_ct=123,
spec_num_proposed_drafts=861`) |
| `stepfun-ai/Step-5-Preview-NVFP4` | SGLang |
`lmsysorg/sglang:step-5-preview` | 4 | `bc246cc284` | `09d27bb772` |
PASSED (VLM image description) |
| `stepfun-ai/Step-5-Preview-NVFP4` | vLLM | `vllm/vllm-openai:v0.34.0`
| 4 | `bc246cc284` | `09d27bb772` | PASSED (VLM image description) |
- **Not run on final head (`3e3a410b7a`):** Full 80-checkpoint matrix
and re-execution of the 120B-816B/image cases (handled by downstream
release QA).
### 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?: ✅ (Existing `test_deploy.py`
entry points and node IDs are preserved except for consolidating the
previously duplicated `nvidia/Kimi-K2.6-Eagle3` entry under `test_kimi`;
catalog validation is intentionally stricter at collection time for
duplicate/malformed YAML definitions and reserved engine options.)
- 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?: ✅
(`tests/unit/examples/test_deploy_config.py`,
`tests/unit/examples/test_deploy_fixtures.py`,
`tests/unit/examples/test_image_deploy_utils.py`)
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A (Tests, examples, and documentation only; no `modelopt/` library
changes.)
- Did you get Claude approval on this PR?: N/A
### Additional Information
Generated with [Devin](https://devin.ai)
---------
Signed-off-by: yingguo-trt <244492186+yingguo-trt@users.noreply.github.com>
|
||
|
|
cbda458060 |
Make the grouped experts' restore recalibration NaN-safe (#3720)
### What does this PR do? Type of change: Bug fix **Problem:** restoring a Megatron checkpoint of grouped MoE experts (`TEGroupedLinear`) with a block-scaled weight quantizer (e.g. FP8 in 2D blocks) at another expert tensor-parallel size fails with `AssertionError: detected nan values in amax` when the ModelOpt state is restored before the weights load, as Megatron-Bridge's loader does. `_QuantTEGroupedLinear.modelopt_post_restore` dry-runs each expert's quantizer; a block amax saved at another TP size no longer fits the weight, so it recalibrates the amax from the weight, which is still uninitialized memory. #3398 fixed the same recalibration in `_ParallelLinear` but left the grouped one, as no test reached it then. Per-channel amax doesn't get here since #3663 (resized from the weight's shape instead), so a block amax is what still does. **Fix:** the grouped recalibration reads `torch.nan_to_num(weight)`, as `_ParallelLinear`'s does. The checkpoint's amax replaces the value when the weights load. ### Testing In `nvcr.io/nvidia/nemo:26.10` on 2 GPUs (sm_89): - `test_te_grouped_sharded_state_dict_reshard` gets `fp8-2d-block-tp-upsize` / `-tp-downsize`: the experts' `linear_fc1` quantized to FP8 in 16x16 blocks, saved at TP 1 and restored at TP 2, and back. The target's expert weights are NaN until the weight load (as the test already does), and the test checks that every expert's restored amax holds its saved value. Both pass; with the fix reverted both fail with `detected nan values in amax`. The amax check now skips disabled quantizers (`linear_fc2` here). - The other `test_te_grouped_sharded_state_dict_reshard` cases and `test_te_grouped_gated_per_channel_reshard_rejected` pass. - Before writing the test, I instrumented the recalibration on `main` and ran all 12 existing reshard cases plus INT8 TP 1→2, FP8 per-channel TP 2→1 and NVFP4-MSE TP changes with NaN expert weights: none reached it. Block-scaled amax at a TP change does. Not covered here (found while probing, both fail loudly rather than load wrong values): a row-parallel `linear_fc2`'s 2D-block amax doesn't load at another TP size (`Global shape mismatch` at the weight load), and an INT4 block amax at another TP size trips a CUDA device-side assert (`amax >= 0`) in the dry run, as per-channel amax did before #3663. ### 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?: ❌ (review bot loop follows) ### Additional Information OMNIML-6311 (follow-up from #3398). 🤖 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 restoration of Megatron grouped-MoE checkpoints with block-scaled weight quantization when using a different expert tensor-parallel size. This prevents NaN-detection errors during checkpoint loading and supports tensor-parallel size increases and decreases. <!-- 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> |
||
|
|
7f1f1e099d |
[7125727] fix(onnx): reject conflicting AutoTune resumes (#3552)
### What does this PR do? Type of change: Bug fix **Problem:** Reusing an INT8 AutoTune output directory with `--quant_type fp8` can return success and export INT8: loading the checkpoint silently replaces the requested quantization type. The Handoff reproduces this with a static Conv model and ResNet50. **Fix:** Reject standalone AutoTune checkpoint resumes whose saved quantization type conflicts with an explicit or auto-discovered `--quant_type` after normalizing relative `output_dir`/`state_file` paths. Explicit `--state_file` resumes with `--quant_type` omitted inherit the checkpoint's saved type, and calibrated PTQ AutoTune (`model_transform`) continues to re-profile checkpoints for the requested type. ### Usage Matching checkpoint resumes and explicit `--state_file` resumes without `--quant_type` require no changes. To switch quantization types from scratch, use a fresh `output_dir` and omit or change `--state_file`. ### Testing Supplied Handoff evidence from an isolated proposal overlay on ModelOpt **0.49.0rc0**, Linux x86_64, Python 3.12, **TensorRT 11.4.0.106 / Blackwell SM100**: - **29 passed, no failures or skips:** 5 real CLI/API contract cases, 22 existing AutoTune/quantization integration cases, and 2 native GPU API regressions. - **Baseline:** 2 of 5 CLI/API contract cases fail because mismatched resumes incorrectly succeed; both new GPU regressions fail with `DID NOT RAISE`. The three matching/re-profiling controls pass. - The proposal rejects both INT8-to-FP8 and FP8-to-INT8 conflicts, preserves checkpoint bytes, and writes no final ONNX model. Matching types and explicit transformed workflows succeed with real native TensorRT builds/timings. - The original wrong-type export is reproduced on static Conv and ResNet50, with fresh/matching FP8 positive controls. In addition to the Handoff results above, head `2d02f916ed` passed 185 unit tests (`100%` diff coverage across `workflows.py` and `__main__.py`), 52 single-process GPU AutoTune tests, and native TensorRT 11.4 `trtexec` CLI/API verification (explicit `--state_file` FP8 resume with omitted `--quant_type`, parent-relative `output_dir` conflict rejection, and `quantize(..., autotune=True)` cross-type re-profiling) across SM89, SM90, and SM100. Windows and TensorRT 10 native reruns remain pending. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ Matching resumes and explicit transformed workflows are preserved; conflicting resumes now fail explicitly. - 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?: ✅ Unit regression cases for conflicting checkpoint resumes and temporary output-directory cleanup in `tests/unit/onnx/quantization/autotune/test_workflows.py`. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ - Did you get Claude approval on this PR?: ❌ Pending. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * ONNX AutoTune now rejects resume checkpoints when the saved quantization type conflicts with an explicitly requested or auto-discovered type. * When an explicit state file is provided without a quantization type, AutoTune inherits the type saved in the checkpoint. * Calibrated PTQ AutoTune continues to re-profile when resuming, retaining the saved quantization type if none is requested. * **Documentation** * Resume with the checkpoint’s quantization type, or start fresh in a new output directory without the state file. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: joe-nv <222375587+joe-nv@users.noreply.github.com> |
||
|
|
4d07511c72 |
Fix export_hf_checkpoint after save_pretrained and on non-zero ranks (#3717)
### What does this PR do?
Type of change: Bug fix
**Problem:** `export_hf_checkpoint` fails in two ways when every rank of
a `torch.distributed` run exports its own replica of an HF model (found
in NVIDIA/Megatron-LM#10084's KV-cache export test):
- On a model that was saved with `save_pretrained` first, packing fails
with `RuntimeError: Invalid device string: 'bfloat16'`. transformers'
`save_pretrained` rewrites `config.dtype` in place as the string
`"bfloat16"`, and `_resolve_export_dtype` returned it as the export
dtype, so `weight.to("bfloat16")` read it as a device. This is not
specific to multiple ranks: a single process that calls
`save_pretrained` before the export fails the same way. In that test it
showed only on rank 0, the one rank that had saved the source
checkpoint.
- On every rank other than 0, the export fails with `FileNotFoundError:
.../config.json`. Under `torch.distributed`, transformers'
`save_pretrained` writes on rank 0 only, but ModelOpt's non-sharded
export then edits `config.json` on every rank (and ModelOpt's
`save_pretrained` hook writes `modelopt_state.pth` on every rank).
**Fix:** `_resolve_export_dtype` converts a string config dtype to a
`torch.dtype`. In the non-sharded export, only rank 0 calls
`save_pretrained`, edits `config.json` and copies the source's files;
the other ranks write nothing, as `save_pretrained` does.
### Testing
In `nvcr.io/nvidia/nemo:26.10` on 2 GPUs (sm_89):
- Reproduced both failures first with a 2-rank `torchrun` (Megatron-Core
model parallel initialized at TP=1; it plays no part): a tiny Llama
quantized with FP8 weights and an FP8 KV cache, exported from every
rank. A single-process export after `save_pretrained` fails with the
same dtype error.
- New
`tests/gpu/torch/export/test_distributed_hf_export.py::test_replicated_export_after_save_pretrained`:
every rank saves, quantizes (FP8 + FP8 KV cache) and exports its own
replica with `save_modelopt_state=True`; checks rank 0's checkpoint and
that rank 1 writes nothing. It passes. With the dtype fix reverted it
fails with `Invalid device string: 'bfloat16'`; with the config edits on
every rank, rank 1 fails with `FileNotFoundError` on `config.json`; with
`save_pretrained` on every rank, rank 1 writes `modelopt_state.pth`.
- `tests/unit/torch/export/test_unified_export_hf.py -k
resolve_export_dtype` gains two string-dtype cases; they fail without
the fix.
### 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?: ❌ (review bot loop follows)
### Additional Information
OMNIML-6311. NVIDIA/Megatron-LM#10084 works around this by exporting the
HF-side baseline in a subprocess on rank 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**
* Hugging Face checkpoint exports now work with models saved using
`save_pretrained`.
* String-valued model data types, including `torch.`-prefixed values,
are recognized during export; unrecognized values are treated as unset.
* For replicated distributed exports, rank 0 writes the checkpoint while
other ranks return without waiting.
* **Tests**
* Added coverage for distributed FP8 checkpoint exports and
string-valued model data types, including cases where the requested
export type differs.
<!-- 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>
|
||
|
|
3197c87316 |
Refuse EAGLE-1 draft export from the Megatron exporter and test EAGLE-3 (#3718)
### What does this PR do? Type of change: Bug fix **Problem:** the deprecated Megatron exporter's EAGLE draft export fails with the default EAGLE config. `export_mcore_gpt_to_hf(..., export_extra_modules=True)` on an EAGLE-1 draft (`use_aux_hidden_state=False`, as in `default_eagle_config`) raises `AttributeError: 'EagleModule' object has no attribute 'fc'`: the Megatron `EagleModule` builds `fc` only for EAGLE-3, and `_get_eagle_module_state_dict` writes it unconditionally. The eagle cases in `test_unified_export_megatron.py` export only the base model, so the draft export was untested. Testing it found that an EAGLE-3 draft with a vocabulary smaller than the target's is exported without its `d2t` mapping (draft to target token offsets): `_get_eagle_module_state_dict` checks for an attribute `dt2`, but the buffer is `d2t`. **Fix:** `GPTModelExporter` refuses an EAGLE-1 draft export with a clear `NotImplementedError` (EAGLE-1 is deprecated, #946), and the EAGLE-3 draft export checks for `d2t`. EAGLE-3 draft export is now tested. Nothing else in the EAGLE export path changes. ### Testing In `nvcr.io/nvidia/nemo:26.10` on 1 GPU (sm_89): - `tests/gpu_megatron/torch/export/test_unified_export_megatron.py -k "test_unified_export_megatron and eagle"`: the existing `llama-eagle` case now also checks that the EAGLE-1 draft export is refused; a new `llama-eagle3` case exports an EAGLE-3 draft (`export_extra_modules=True`) whose vocabulary is half the target's, and checks its config (`LlamaForCausalLMEagle3`) and tensors (`fc`, the `midlayer` attention, MLP and norms, with `fc` and `q_proj` input sizes; the draft `lm_head`; and the `d2t` values set before export). With the refusal reverted, the `llama-eagle` case fails with the `AttributeError` above; with the `d2t` check reverted to `dt2`, `llama-eagle3` fails with `d2t` missing from the draft. - `test_export_rejects_weight_only_awq`, which builds an EAGLE draft exporter, now uses an EAGLE-3 draft and passes. - Note: the EAGLE draft export reads `nvidia/Llama-3.1-8B-Instruct-FP8`'s config from the Hugging Face Hub (unchanged behavior), so the new case needs Hub access, as other `gpu_megatron` tests do. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ (EAGLE-1 draft export failed before) - 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?: ❌ (review bot loop follows) ### Additional Information OMNIML-6311 (the wider EAGLE export decision is OMNIML-5980). Found while working on #3681. 🤖 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 * **New Features** * Extra-module exports support EAGLE-3 draft models, including deep EAGLE-3 configurations and drafts with smaller vocabularies mapped to the target model. * **Bug Fixes** * Exporting EAGLE-1 drafts without auxiliary hidden states now reports that the configuration is unsupported and recommends EAGLE-3. * **Documentation** * Export guidance now identifies EAGLE-3 as the supported option for extra-module exports. <!-- 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> |
||
|
|
4ece634070 |
Load gated grouped experts' per-channel state at another expert TP size (#3724)
### What does this PR do? Type of change: Bug fix **Problem:** a Megatron checkpoint of gated (SwiGLU) grouped MoE experts with per-channel weight quantizers (e.g. `INT8_DEFAULT_CFG`, `FP8_PER_CHANNEL_PER_TOKEN_CFG`) can't be loaded at another expert tensor-parallel (ETP) size. Megatron shards the experts' `linear_fc1` weight by gate and up rows, but their per-channel amax by plain rows, so at another ETP size the two land on different rows. #3663 refused this when the extra state is restored (`ValueError: ... can't be loaded at another expert tensor-parallel size`), deferring the fix (OMNIML-6311). **Fix:** grouped experts now get what #3505 gave dense `linear_fc1`: - Saves are unchanged: plain rows. A model loaded from another ETP size re-saves in that checkpoint's layout and records its sizes (`modelopt_swiglu_legacy_numels`) in its extra state, as dense layers do; a restore at another EP size takes them by expert, as it does each expert's quantizer state. - ModelOpt's restores read the checkpoint's layout: a fresh restore (`restore_sharded_modelopt_state` into an unquantized model, through `set_extra_state`) and a restore into a converted target (through `modelopt_read_checkpoint_layout`). Both work out the saved ETP size from the saved amax shapes (on the expert TP group; an expert the state doesn't hold, e.g. at a smaller EP size, is sized as expert 0). The grouped `sharded_state_dict` then plans each gated expert's per-row amax with `_legacy_swiglu_factory`, after the per-expert key rewrite, on the expert-TP axis. - #3663's refusal is dropped. - A load that plans these rows without reading the checkpoint's layout (Megatron-Bridge's or Megatron-LM's own loader, into a model already quantized) is refused at another ETP size, as on `main`, instead of loading the rows misplaced: `ValueError: This checkpoint saved gated grouped experts' per-channel weight quantizer state at another expert tensor-parallel size, and this load planned its rows without reading the checkpoint's layout. Restore with restore_sharded_modelopt_state first, or load at the expert tensor-parallel size it was saved at.` The same check runs on every later load into a restored model (without rebuilding its quantizers), so a native load of another checkpoint after a restore at another ETP size is refused too rather than planned with the earlier checkpoint's layout. These loaders still don't read the layout themselves, so they remain limited to the saved ETP size for this state. Dense layers' per-row state through those loaders at another TP size is still unchecked, as today (OMNIML-6311). ### Testing In `nvcr.io/nvidia/nemo:26.10` on 2 GPUs (sm_89): - `test_te_grouped_gated_per_channel_reshard` replaces `test_te_grouped_gated_per_channel_reshard_rejected`: INT8 and FP8 per-channel gated experts saved at ETP 2 and loaded at 1, and 1 to 2, into a fresh target, into a converted (quantized) target, and through a plain Megatron load into a quantized target (`native`). Every per-channel value is distinct by its global gate or up row, and the expert weights are NaN until the weight load. All 12 pass. - With `megatron.py` from `main`, all 8 fresh/converted cases fail with #3663's refusal. - With the refusal dropped but the legacy factory disabled, the fresh and converted cases fail with misplaced rows. - Without the new check, the 4 `native` cases fail (`DID NOT RAISE ValueError`). - New `test_te_grouped_gated_per_channel_resave_at_another_ep`: saved at TP2/EP1, restored at TP1/EP2, re-saved (in the ETP2 layout, with its sizes recorded), then restored at TP1/EP1; every expert's rows load in the ETP2 order. Without remapping the recorded sizes by expert across the EP change it fails with `imply different tensor parallelism sizes [1, 2]`. - New `test_te_grouped_gated_per_channel_reshard_then_native_load`: restore an ETP2 checkpoint into ETP1, load it, then natively load an independently quantized, row-distinct ETP1 checkpoint into the same target: refused. Without the check on later loads it fails with `DID NOT RAISE ValueError`. - The other `test_te_grouped_sharded_state_dict_reshard` cases, the dense SwiGLU layout tests and `test_transformer_engine.py`'s grouped tests pass: `test_megatron.py` and `test_transformer_engine.py` with `-k "grouped or swiglu or sharded_state_dict"`, 130 passed and 24 skipped (4-GPU cases and unsupported configs). This touches the grouped restore next to #3720 (NaN-safe recalibration); the two merge without conflicts. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ Checkpoints are saved as before. Loads that #3663 refused now succeed through ModelOpt's restores. - 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)?: ✅ (the unreleased #3663 entry) - Did you get Claude approval on this PR?: ❌ (review bot loop follows) ### Additional Information OMNIML-6311 (deferred from #3663). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d666be6a2c |
[4/19] [OMNIML-5967] Add streaming IQ Bypass with Lion defaults (#3456)
### What does this PR do?
Type of change: New feature.
Existing IQ-quantized models need scale-only repair against a frozen
teacher without retaining targets for the full calibration set. Add
`modelopt.torch.distill.bypass`: stream one boundary's targets at a
time, train native IQ fields with Lion, and finalize through the repair
policy's public `IQRepairPolicy.recover()` path.
Boundary selection refuses shared storage, frozen routers and
overlapping owners before training. Masked MSE normalizes over each
complete global update; clipping checks every field group before any
step. Decay starts at the first post-warmup update, so the final update
keeps a nonzero learning rate and `num_steps=1` trains. Caller
Torch/CUDA RNG, model modes and teacher gradient flags are restored on
exit. Finalization commits boundaries in order: a later publication
failure can leave earlier boundaries committed, so reload a saved
checkpoint before retrying. Optional held-out validation only reports
MSE after every boundary is finalized. Unrecoverable owner restoration
requires discarding the affected model.
### Modules touched
- `distill._bypass_runner`: coordinates native-field policies, masked
gradient accumulation, finite-update validation and failure cleanup (one
`IQRepairPolicy.recover()` per policy) across streamed units.
- `distill._bypass_optimizer`: updates each FP32 policy field as one
tensor with Lion and the configured cosine or constant learning-rate
schedule.
- `distill.bypass` and package exports: expose the runner with
validation and caller-state restoration.
### Usage
```python
import modelopt.torch.distill as mtd
mtd.bypass(student, teacher, calibration_batches, {
"num_steps": 20,
"global_batch_size": 8,
"sequence_length": 2048,
"modules": ["decoder.mlp"],
})
```
### Testing
At signed/DCO head `37da0d7b41d210a485314fce45576eb59a0d6c27`, the exact
head passed all 50 public runner cases in
`tests/gpu/torch/distill/test_bypass.py` and 10 of 11
`tests/gpu/torch/quantization/test_repair.py` cases on four GPUs (Slurm
2546657); the remaining FSDP2 rollback case timed out waiting on a
worker queue, and a rerun of the whole `test_repair.py` file passed
11/11 (Slurm 2546879). Earlier results qualify their stated revisions
only.
Fresh hosted checks are pending. Stacked required GPU/example/regression
markers defer until targeting main; actual on-demand workflows are
tracked separately. Human approval remains separate.
### Before your PR is "*Ready for review*"
- Backward compatible: Additive entry point; existing distillation is
unchanged.
- Copied code or dependency: None; source headers match the canonical
repository header.
- Necessary tests: Mathematical update/schedule/VJP checks and public
failure/recovery/offload flows.
- Changelog: Added the public Bypass feature entry.
- Claude approval: Fresh review requested; prior feedback considers code
issues fixed but requests a human size exception.
### Additional Information
Design choice: `LayerwiseDistillationModel.modify()` unfreezes selected
student layers and replaces LM heads. Bypass instead freezes physical
weights and trains only `IQRepairPolicy` fields through that policy's
prepare/project/finalize/recover lifecycle. Existing forward hooks still
capture boundaries; the runner owns masked accumulation, finite-gradient
validation before any unit update, scheduling and failure cleanup.
Extending the KD conversion/export lifecycle would mix those two
ownership contracts. The adapter isolates boundary capture/replay while
quantization state stays in the existing repair policy.
Merge order: #3678 → #3599 → #3591 → #3592 → #3593 → #3676 → **#3456** →
#3457 → #3458 → #3679 (physical fields) → #3680 (TP field/geometry
helpers) → #3459 → #3460 → #3461 → #3462 → #3463 → #3464 → #3465 → #3466
→ #3467 → #3468 → #3469. The Bypass feature series has 19 slices. Keep
stacked until predecessors merge into main.
Capture and configuration now live in #3676. This runner/optimizer slice
adds approximately 212 source lines excluding comments, docstrings and
blanks. No size exception is claimed or needed.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added Bypass support for adjusting IQ scales in existing student
models using teacher guidance.
* Added configurable warmup and learning-rate scheduling, including Lion
optimization with a default peak learning rate of 0.001.
* Added full-global-batch updates and optional validation reporting.
* **Documentation**
* Documented Bypass configuration, batching and masking requirements,
validation options, and run behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Native continuation: #3457 → #3458 → #3679 (physical fields) → #3680
(TP/geometry) → #3459 → #3460 → #3461. Both exact module and
logical-layer selectors intersect where supported.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Sepehr Sameni <ssameni@nvidia.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
f385f55352 |
[3/19] Add Bypass capture boundaries and validated configuration (#3676)
### What does this PR do? Type of change: new feature **Problem:** Bypass repair needs disjoint teacher/student boundaries and faithful replay of inputs, masks and boundary outputs before its runner can update native IQ fields. **Fix:** Provide the capture/replay adapter and validated training configuration as a standalone prerequisite to the streamed runner in #3456. `sequence_length` is a maximum (only longer batches are refused), the teacher forward receives `use_cache=False` by keyword only, and tied teacher weights are accepted because the teacher is read-only; one teacher module shared by two boundaries is still refused. This slice adds approximately 385 lines of source excluding comments, docstrings and blanks. ### Modules touched - `distill._bypass_capture`: owns boundary validation, bounded masked loss and teacher-input replay required by the runner. - `distill.config`: validates the shared batch, scheduling and boundary-selection contract; the public export is deferred to #3456. - `quantization.repair`: extends the existing physical ownership walk to whole capture boundaries, replacing a duplicate walk. ### Usage This internal prerequisite keeps `BypassConfig` out of the package exports. The validated configuration becomes public with its runner consumer in #3456. ### Testing Fresh local and hosted validation at signed/DCO head `606001b54b1df405cd5ce65ae0963279e0719c52` is pending. Since the previous head `8f6109cc0b4d332598c05447042b537e8b435d60`, this slice dropped positional `use_cache` handling, `output_selector`, the optimizer field and the linear scheduler; `layer_indices` moved to its first reader in #3457. At the previous head, standalone capture passed 25 cases (0.76 s), the rebased integration at |
||
|
|
8667e5dff0 |
Support Minitron pruning of Qwen3.5-VL's hybrid language model (Megatron-Bridge 0.8) (#3698)
### What does this PR do? Type of change: Bug fix **Problem:** Megatron-Bridge 0.8 (nemo:26.12) builds Qwen3.5-VL's language model as a Megatron-Core `HybridModel` (NVIDIA-NeMo/Megatron-Bridge#6733): each HF decoder layer becomes two pattern positions, a GatedDeltaNet (`G`) or attention (`*`) mixer followed by its MoE/MLP (`E`/`-`), e.g. `GEGEGE*E`. Minitron pruning of it (`tests/examples/megatron_bridge/test_prune_minitron.py::test_prune_minitron_vlm[qwen3_5_moe_vl]`) fails three ways, each hidden behind the previous one: 1. The new `Qwen35VLHybridLanguageModel` class is not registered for NAS: "no configurable hyperparameters". 2. The model-stats helpers reject `G` in hybrid patterns. 3. Depth pruning drops single positions, which splits a mixer from its MLP, and the example writes the position count as HF `num_hidden_layers` without rebuilding `layer_types`. **Fix:** - Register `Qwen35VLHybridLanguageModel` in the Megatron-Bridge NAS plugin. - Count `G` layers in `mcore_param_count` (the existing GatedDeltaNet formula, now checked against a live model) and their conv + delta-rule state in `mcore_memory_footprint_mb`. `*` in a hybrid pattern no longer reads the per-layer `linear_attention_freq`, which indexes positions there. Also accept Megatron-Core 0.21's `"gdn"` name for the GPT path. - New searcher option `layer_group_size` (default 1): depth pruning ranks groups of that many consecutive layers by their summed scores and drops them whole; `num_layers` and each PP stage's layer count must be multiples of it. The depth-pattern slicer also keeps the `|` pipeline boundaries that Bridge puts in this pattern under PP. - `prune_minitron.py` sets `layer_group_size` to the source checkpoint's pattern positions per HF layer (2 for hybrid Qwen3.5, 1 otherwise). For grouped models it takes `num_hidden_layers` and `layer_types` from the pruned pattern, using Bridge's `qwen35_hf_layer_config`. **Design: where the grouping lives.** A pattern describes positions, not how they group into HF layers: `*E` is one Qwen3.5 layer but two Nemotron-H layers. So the core searcher does not infer it. The Bridge path, which knows the source checkpoint, passes it in, and search and HF export use that one value. The value comes from the source config (positions ÷ `num_hidden_layers`), not from `G` in the pattern, so it also holds for a Qwen3.5 checkpoint with no GatedDeltaNet layers left, e.g. when re-pruning. I did not use a class-based rule in the Bridge NAS registration: Bridge 0.8 builds text-only Qwen3.5 as a plain Megatron-Core `HybridModel`, so there is no class to register. Nemotron-H and every other model keep `layer_group_size=1`, so their behaviour is unchanged. Bridge's `qwen35_hf_layer_config` landed in the same Bridge commit as the hybrid model; the local fallback only covers it being moved or renamed later. ### Modules touched - `modelopt/torch/nas`: registration of the new class and `G` in the model stats used by the pruning search. - `modelopt/torch/prune`: pair-wise depth pruning; without it the pruned model cannot be exported to HF. - `examples/megatron_bridge`: the HF config of the pruned model. ### Usage `examples/megatron_bridge/prune_minitron.py` sets the new option itself. A direct caller pruning Bridge's hybrid Qwen3.5 passes it as follows: ```python mtp.prune( language_model, mode=[("mcore_minitron", mtp.mcore_minitron.get_mcore_minitron_config(num_layers_divisor=2))], constraints={"params": target_params}, dummy_input=None, config={"forward_loop": forward_loop, "score_func": score_func, "layer_group_size": 2}, ) ``` ### Testing New tests: - `test_megatron_model_stats.py`: `G` cases for the formula, the recurrent-state memory, and a live `HybridModel` with a `G` layer. - `test_mcore_hybrid_minitron_pruning.py`: a deterministic grouped depth-pruning test and a pattern-slicing test. - The depth test uses fixed scores that would split pairs if layers were ranked one position at a time, and that drop every GatedDeltaNet pair. - The slicing test covers a pattern with `|` and an MTP suffix. - `test_prune_minitron.py::test_grouped_hybrid_hf_layers`: checks the example's group-size choice and the HF `num_hidden_layers` / `layer_types` it writes. All local runs used 2 GPUs (sm_89). The example ran at PP=2. **nemo:26.12** (Megatron-Core 0.21, TE 2.22, Megatron-Bridge 0.8), at the head of this PR: - `test_prune_minitron_vlm[qwen3_5_moe_vl]` passes. Depth pruning drops the `[11, 12]` pair, and the pruned HF checkpoint loads strictly in transformers. - `test_grouped_hybrid_hf_layers`, `test_megatron_model_stats.py`, the grouped depth test and the slicing test pass (39 tests). - In `test_mcore_hybrid_minitron_pruning.py`, the other Mamba tests fail on 26.12 with or without this PR. That is the Megatron-Core Mamba cache change, which is fixed separately under OMNIML-6686. **nemo:26.10** with the CI Megatron-Bridge pin (Qwen3.5-VL is not hybrid there): - `test_megatron_model_stats.py` and `test_mcore_hybrid_minitron_pruning.py` pass (43 tests, Nemotron-H style hybrids included). - `test_prune_minitron_vlm[gemma3vl]`, `test_prune_minitron_vlm[qwen3_5_moe_vl]` and `test_prune_minitron[nemotron_h]` pass. **Revert checks.** Each fix was reverted alone, and the test named for it fails: | Fix reverted | 26.12 | 26.10 | |---|---|---| | Class registration | example: "does not contain any configurable hyperparameters" | not hybrid there | | `G` in model stats | example: "Unsupported hybrid layer chars {'G'}"; 5 model-stats tests fail | same 5 model-stats tests fail | | Grouped depth pruning | example: drops `[1, 3, 5, 11]`, then Bridge export reports "No mapping found"; grouped depth test fails | grouped depth test fails | | HF layer fields | example: `IndexError` in `layer_types`; `test_grouped_hybrid_hf_layers` fails | n/a | | `\|`-aware slicing | slicing test fails | slicing test fails | The `|` revert does not fail the example on its own. The pruned pattern string is then wrong, but nothing downstream reads it in that run. CI runs nemo:26.10, so on CI the example exercises the old GPT path for Qwen3.5-VL. The hybrid path was checked only locally, on 26.12. ### 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?: N/A ### Additional Information OMNIML-6686. Export parity of hybrid Qwen3.5 in the ModelOpt Megatron exporter is a separate item. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
53d36b54c1 |
[7/7] [OMNIML-5967] Manage native IQ repair lifecycle and publication (#3593)
### What does this PR do? Type of change: New feature. Native IQ Bypass repair needs trainable scale fields while frozen weights, quantizer layouts and offloaded/sharded owners remain recoverable. Add the repair lifecycle on #3592's ownership plan, with caller-owned CPU backups, coordinated publication recovery, bounded native replay and explicit cleanup. Planning also captures the caller's calibration/GEMM flags and refuses a quantizer that already has an active repair. Full quantizer/model state export now refuses while a repair policy is open; properties-only Bypass checkpoints remain supported. This folds #3590 into its first producer as requested by the human reviewer, replacing property overlays and shared allowlists with a runtime-only open marker. Recovery uses the policy's existing backups; no owner undo callback remains. Failed recovery retains its backups for a matched retry through `IQRepairPolicy.recover()` and refuses premature close. ### Modules touched - `quantization/repair.py`: owns preparation, field masters, publication recovery and cleanup. - `quantization/nn/modules/tensor_quantizer.py`: refuses unsupported full-state export during active repair and excludes runtime markers from serialized properties. - `quantization/utils/weight_cache.py`: avoids detached weight-cache reuse during active repair. - `quantization/plugins/huggingface.py`: preserves gradients through active transposed expert paths. ### Usage Internal standalone-boundary example; the Bypass runner follows in #3456: ```python from modelopt.torch.quantization.repair import IQRepairPolicy, plan_iq_repair policy = IQRepairPolicy() try: fields = policy.prepare_plan(plan_iq_repair([iq_quantized_layer]), 0) # Optimize fields, calling policy.project_() after each step. policy.finalize_() finally: policy.close() ``` Distributed/offloaded callers supply the runner's weight-access and error-agreement callbacks. If a failed finalization's rollback also fails, call `policy.recover(weight_access, synchronize_error)` on every rank before reusing the units; `close()` refuses until then. Keep logical ownership fixed from planning through close. Backend/collective failures may require restarting the job; recovery cannot guarantee safe reuse after an unrecoverable communication failure. ### Testing Signed/DCO head `05d80ea0d3a22c7678c94203a817aefe7ad04825`. Since the previous head `9cb4f852ccb03b41bbcaf480105706d5c44a57af`, this slice removed `prepare()`, per-plan refcounting, pin-key peer cleanup and its Accelerate backing-namespace hook, and added `recover()`; fresh per-head validation is pending. At the previous head, the rebased integration at |
||
|
|
3ef84ecd95 |
[6/7] [OMNIML-5967] Plan native IQ repair ownership (#3592)
### What does this PR do? Type of change: New feature, bug fix. **Problem:** Native IQ Bypass repair needs a complete ownership plan before changing selected weights or freezing shared controls. Shared quantizers, parameters, buffers, physical storage or offload publication slots can otherwise let a selected boundary change an unselected owner. **Fix:** Build lazy native-IQ bindings against the full logical root and capture original parameter flags. Validate all selected and frozen owners without slicing expert weights or gathering DTensors. Inspect both resident execution values and retained backings on every non-meta device, including hooks suspended by an outer materialization window. Compare absolute byte intervals per device so overlapping NumPy-backed wrappers cannot hide behind different storage-base pointers; sparse and other storage-less layouts are refused. Canonical mapping/key slots are checked even when a cached value is missing; representations of the same logical owner are merged before cross-owner comparison. ### Modules touched - `repair.py`: lazy plans, eligibility and full-root ownership validation. - `plugins/accelerate.py`: safe resident backing/publication-slot inspection, including every nested hook and suspended native offload hooks. - `utils/core_utils.py`: quantizer-to-parameter bindings, persistent FSDP registration lookup and the shared absolute storage-span helper. - `algorithms.py`: AutoQuantize's restorability check reuses that span helper, so it also catches overlap between two `from_numpy` slices of one array. - `plugins/huggingface.py`: expose the same legacy fused-expert container to existing conversion and save consumers. - `model_calib.py`: reuse that existing resolver so AWQ-family calibration sees the container planning selected. The shared lookup intentionally also fixes legacy export detection: restored non-gated fused-expert wrappers storing first-projection quantizers under `gate_up_proj_weight_quantizers` now report the actual format/block size instead of none/zero. A regression checks representative lookup, export format, block size and IQ detection; the compatibility correction is recorded in the changelog. The policy lifecycle and publication remain in #3593. Fields used only by that lifecycle, including calibration/GEMM flags and the active-repair guard, are introduced with their first consumers there. Quantizer container lookup is shared with the existing representative helper, and storage inspection refuses unsupported layouts with a consistent diagnostic. ### Testing Fresh local and hosted validation at signed/DCO head `57416370bdd89cfed97d8d399d14b6180b4cdf78` is pending. The results below qualify the previous head `7b18726d3df752ab5059d401ece7763fb00ef7d0`, before the shared storage-span helper, the sparse/negative-stride removal and the move of calibration/GEMM flags to #3593. There, the rebased integration at |
||
|
|
b05e6096ae |
Add --kld_eval to hf_ptq: KL divergence of the quantized model before export (#3639)
> Builds on #3694 (merged), which added `kld_eval_vllm.py` and the shared `kld_eval.py` helpers (the `--kld_*` options, prompt loading and KL) that this PR reuses. ### What does this PR do? Type of change: new feature **Problem:** `hf_ptq.py` has no quick way to tell how far a quantized checkpoint drifts from the original model before exporting it. Accuracy benchmarks run after export, take much longer, and need a separate harness. **Fix:** `--kld_eval` collects the original model's greedy continuations of chat prompts before calibration, along with its top-k log-probabilities at evenly spaced positions, and holds them in host memory. After quantization and before export, it prints the conditional top-k KL(original ‖ quantized): both distributions are renormalized over those tokens, so probability the quantized model moves outside the top-k set does not count. The output is one number. The evaluation writes no artifact of its own (Hugging Face may cache the dataset), and the exported checkpoint is unchanged: the RNG is forked, so calibration draws the same samples as before. If scoring fails, the run exports without a score and then warns, so a warnings-as-errors policy cannot cost the checkpoint. Defaults: `nvidia/balanced-benchmark-prompts-short-1000`, 300 prompts, 1024 new tokens, generation batch 64, top-k 2048, 512 scored positions, seed 0. The flag refuses setups it cannot score correctly, before calibration starts: - multi-process or FSDP2 launches - layerwise calibration, from `--recipe` or a `--qformat` preset such as `iq2_s`, plus `--low_memory_mode` and `--offload_folder` - sparsity and offline speculative decoding - multimodal and encoder-decoder models, and models that cannot generate - AutoQuantize runs that leave no quantized model to score ### Usage ```bash python hf_ptq.py --pyt_ckpt_path <model> --recipe general/ptq/nvfp4_default-kv_fp8_cast --kld_eval # ... Conditional top-k KL: <score> nats ``` ### Testing - **CPU tests, on a Mac.** `tests/examples/hf_ptq/test_kld_eval.py` and `test_hf_ptq_args.py`: 86 passed. They cover: - KLD is 0 before quantization and positive after it, the RNG state is unchanged, and no files are written - flag validation, including a regression test for Slurm single-process jobs, which set `RANK` and were wrongly refused - the score is printed before export, and the run still exports when scoring fails, also with warnings as errors - the reference stays one greedy continuation per prompt when the model's config asks for beam search - refusal before calibration for `--qformat iq2_s` and encoder-decoder models - **GPU tests, on one GB300 node (4 GPUs, oci-jhb).** `test_llm_ptq.py` with the two files above: 101 passed. The GPU tests and the end-to-end run below predate the review fixes, which were tested on CPU only. - **End to end, on one GB300.** Qwen3-0.6B with NVFP4, 256 calibration samples, default `--kld_*` settings and the container's own `datasets` 3.1.0: - The run printed a score of 0.196782 nats, before the output was renamed to `Conditional top-k KL`. - `model.safetensors` is byte-identical with and without `--kld_eval`. - The flag added 356 s of wall time, 8.4 GiB of peak host RSS and 33 GiB of peak GPU memory. - The host memory is the 2.3 GiB reference plus heap memory that `model.generate` leaves behind, measured stage by stage. Pinned memory and `malloc_trim` don't account for it. - The GPU memory is from generation and scales with `--kld_generation_batch_size`: about 19.5 GiB allocated at 64 against about 5 GiB at 16. - The score changes slightly with that batch size (0.1968 at 64, 0.1997 at 16). - **Dataset loading.** The default dataset's parquet metadata used a feature type that only `datasets` 4 reads. I fixed the dataset on the Hub, and it now loads by name on `datasets` 3.0.0, 3.1.0 and 4.8.5. - **Not run:** - models other than Qwen3-0.6B - a model spread across several GPUs with `device_map=auto` - the full flow loading the dataset by name with an HF token; the cluster has no token, so it read a local copy ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ (opt-in flag; runs without it are unchanged) - 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 Supersedes #2661 with a smaller scope. The default dataset is private to the NVIDIA Hugging Face organization; the README says so and explains how to pass another dataset with `--kld_dataset`. 🤖 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 * **New Features** * Added optional conditional top-k KL evaluation comparing the original model with its quantized version before export, using generated chat continuations. The score is printed in nats; evaluation creates no files and does not change the exported checkpoint. If scoring fails, a warning is shown and export continues. * **Documentation** * Documented how to enable the evaluation, its settings and limits, and configurations it does not support. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Ajinkya Rasane <131806219+ajrasane@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8923e32b22 |
[5/7] [OMNIML-5967] Refresh GPT-OSS expert quantizers and clean caches (#3591)
### What does this PR do? Type of change: Bug fix. **Problem:** GPT-OSS expert weight access can keep using a quantizer captured before configuration replaces it with a sequential container. A failed forward can also leave quantization flags and cached weights active for the next call. **Fix:** Resolve each weight quantizer from its current module registration when accessed, and clear both flags plus every cached quantized weight (single or sequential quantizer) in `finally`. ### Testing Signed/DCO head `91cca538017d62d81b0968eea74848a3bc31ed60`. Since the previous head `712e199098c6b8606d47aa427b1e6e0e4ca0aecd`, cleanup deletes `_cached_quant_val` from any module that has it rather than type-checking quantizers; the existing regression still covers both the plain and sequential cases. Fresh per-head validation is pending. At the previous head, the rebased integration at |
||
|
|
5db72b5245 |
[4/7] Recover composite native Accelerate weight access (#3599)
### What does this PR do? Type of change: Bug fix and new internal support. A failed Accelerate weight-access window can leave partially onloaded owners, changed registrations or a partially published backing map. Restore the pre-window registrations, placement, ties and map entries on failure, and publish successful composite updates before native hooks reload shared tensors. The dispatcher supports offloaded descendants of hookless composites and suspended native hooks. Publication refuses two different source tensors for one backing-map slot before the first write; tied parameters and parent/child publication into separate maps still work. Non-tensor extra-state entries are skipped, and carried calibrator state rebound through `.data` is copied back. Ordinary hooks keep their normal route. A nested window must not onload or publish an owner that an open outer window already holds; every supported caller opens one window per owner, so no whole-model overlap scan runs per window. ### Modules touched - `quantization/plugins/accelerate.py`: owns native onload, shared publication and failure cleanup; these operations must share one requested-subtree journal to recover partial native-hook entry and shared slots. **Why one shared journal instead of owner-scoped windows composed with `ExitStack`/`multi_context`:** independent owner windows each onload, publish and re-offload on their own, so they cannot capture one pre-onload baseline for the whole requested subtree, and they cannot publish every shared backing entry before native offload resumes; `multi_context` is an `ExitStack` wrapper whose scopes still close one at a time. The journal records each owner's pre-onload registration and backing binding once, publishes all entries, and only then restores native offload, so a failure at any point can roll every owner back to the same baseline. Native Accelerate hooks still own placement; FSDP2 staging coordinates shards, not Accelerate registrations, so it is a different lifecycle. - `quantization/utils/core_utils.py`: dispatches composites and suspended owners to the Accelerate route. All export source and export tests were extracted to #3678, as requested in human review. They are absent from this PR's diff. ### Usage ```python with enable_weight_access_and_writeback(layer, model, rollback=True): # Retain caller-owned value backups before editing weights. ... ``` `rollback=True` selects the FSDP2 staging contract from #3589. Accelerate retains native tensor-value semantics: callers restore in-place or already-published CPU-master edits through a fresh writeback window. Mixed resident/meta placement across a native owner's parameters and managed buffers is refused before yielding; edit those buffers inside a materialized window. Registration/map recovery stores references, not tensor-value snapshots, and supplies no post-exit undo. The consuming production path is #3593's `IQRepairPolicy.finalize_`, which calls its owner factory with `writeback=True, rollback=True`; #3456's runner supplies the dispatcher factory and #3460 extends it to native physical owners. ### Testing Fresh local and hosted validation at signed/DCO head `eec1a9925f695135a678ea5c9ddce8ce0088cc6f` is pending. The results below qualify the previous head `79f98c95f9db69a59b6ab769fa291a4a8c489ca0`, which still had the nested-window overlap scan and its guard-only tests; this head removes them and adds one-source-per-slot, extra-state and rebound-calibrator cases. There, all 380 CPU cases passed with optional Diffusers installed (82.04 s), and all whole-PR hooks passed. Four-GPU Slurm 2523466 passed 134 cases including both development profiles; its eight FSDP workers failed to import a synthetic _cache package because an external profile changed pytest root discovery. With the harness root explicitly pinned to the frozen checkout, those remaining eight cases passed at the same head in Slurm 2523544 (19.86 s): all 142 selected cases are qualified across the two runs, including two development profiles. The existing nested-active matrix also covers successful inner storage rebinding followed by outer failure and validates the next native load. An optional-import probe passes the plain-hook case and skips three offload-only cases without Transformers. Rebased onto `main` at `7024de11ad6ef52b278438a04537accec9b63894` (after #3678 merged). Fresh hosted checks and automated reviews are pending; earlier results qualify their stated revisions only. Stacked-PR required GPU/example/regression markers defer until the base targets main; on-demand workflows exercise the actual lanes meanwhile. Human approval remains separate. ### Before your PR is "*Ready for review*" - Backward compatible: positional arguments retained; unsafe custom writable maps refuse before onload. Failure-recovery behavior is documented in the changelog. - Copied source/new dependencies: none. - Necessary tests: existing ownership/failure matrices extended. New unit cases cover conflicting sources for one backing slot and extra-state modules; the extra-state case fails against the preceding implementation. Existing-test changes still require human signoff. - Changelog: current-release failure-recovery note. - Claude review: requested for this revision; pending. ### Additional Information Merge order: #3678 → **#3599** → #3591 → #3592 → #3593 → #3676 → #3456, then the remaining Bypass series. #3590 is closed and folded into #3593. Removing the per-window overlap scan (and the `root_model`/`names` index it needed in the Accelerate route) removes a whole-model walk on window entry and before publication. With one window per offloaded `nn.Linear` on CPU: 2,000 modules 4.67 s → 0.61 s; 8,000 modules 52.3 s → 2.04 s. These isolated measurements do not measure full-model calibration throughput. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Weight access and writeback now handle nested and suspended offload hooks, including prefixed and disk-backed weight mappings. * FSDP2 weight access offers an optional rollback setting for coordinated staging. * **Bug Fixes** * Failed access and writeback operations restore offload registrations and backing state. Callers remain responsible for restoring values they changed. * **Documentation** * Clarified that writable access requires supported resident backing maps, while read-only access accepts custom mappings. Also clarified caller-managed value restoration and route-specific behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Sepehr Sameni <ssameni@nvidia.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
cb8730cd9e |
[OMNIML-5897] Add kld_eval_vllm.py: conditional top-k KL of an exported checkpoint against its base, in vLLM (#3694)
### What does this PR do? Type of change: new feature **Problem:** There is no quick way to tell how far a checkpoint exported by `hf_ptq.py` drifts from the checkpoint it was quantized from, as vLLM serves it, with its real low-precision kernels and KV-cache quantization. Accuracy benchmarks take much longer and need a separate harness. **Fix:** `examples/hf_ptq/kld_eval_vllm.py` takes the base checkpoint and the exported unified checkpoint, runs both in vLLM 0.32 or later, and prints one number: the conditional top-k KL(base ‖ quantized). It works in two passes: - The base checkpoint writes greedy continuations of chat prompts. It then reads each prompt and continuation back without generating and keeps its top-k log-probabilities at evenly spaced positions. - The quantized checkpoint reads the same tokens and returns its log-probabilities of those token ids, through `prompt_logprob_token_ids`. Both distributions are renormalized over the top-k set, so probability moved outside it does not count. Each checkpoint runs in its own process. The script reports the KV-cache quantization the checkpoint declares and the dtype vLLM uses, reports the range of K/V scales vLLM loaded, and warns when vLLM drops the KV-cache quantization. The `--kld_*` options, prompt loading and KL live in `kld_eval.py`, so that #3639 (`hf_ptq.py --kld_eval`, now stacked on this PR) computes the same score before export. Defaults: `nvidia/balanced-benchmark-prompts-short-1000`, 300 prompts, 1024 new tokens, at most 64 sequences at once, top-k 2048, 512 scored positions. The script refuses a quantized checkpoint whose tokenizer reads the prompts differently, and vLLM older than 0.32. ### Usage ```bash python kld_eval_vllm.py --base_ckpt_path <model> --quantized_ckpt_path <export> # KV cache: the quantized checkpoint declares no quantization; vLLM uses bfloat16. # Conditional top-k KL: <score> nats ``` ### Testing - **CPU, on a Mac:** `test_kld_eval_vllm.py` passes, 8 passed with the GPU test skipped. It covers: - the tokenizer refusal - the conditional KL ignoring mass moved outside the top-k - reading vLLM's top-k layout - where the KV-cache declaration is read from - **GPU, one GB300 on oci-jhb, vLLM 0.33.0 image:** the end-to-end test passes. A tiny Qwen3 scores 0 against itself and more against a copy with a changed `lm_head`. - **End to end, Qwen3-0.6B,** against an NVFP4 export from `hf_ptq.py` (no KV-cache quantization). Default options, one GB300 per run: | vLLM | base vs NVFP4 | base vs base | batch 16 | repeat | wall | |---|---|---|---|---|---| | 0.33.0 | 0.193426 | 0.000000 | 0.192817 | 0.193426 | ~5 min | | 0.34.0rc1 nightly | 0.193441 | 0.000000 | 0.192797 | 0.193441 | ~2.5 min | - Repeats are bit-identical, and the batch size moves the score by 0.3%. - `hf_ptq.py --kld_eval` (#3639) gives 0.196782 for the same export with simulated quantization. vLLM's real NVFP4 kernels score 1.7% lower. - On 0.33 the time goes mostly to the base checkpoint's top-2048 pass, about 80 s, because vLLM converts prompt log-probabilities in Python. - These runs and the GPU test used this code before it was split off #3639; the split changed only comments and docstrings. - **After the review fixes ( |
||
|
|
2dea685d69 |
[OMNIML-6666] [2/4] Move hf_ptq's VLM calibration, preview and loader helpers into the library (#3657)
### What does this PR do? Type of change: New feature (library home for example helpers) **Stack** (merge in order): [1/4] #3656 (merged) → **[2/4] #3657** → [3/4] #3658 → [4/4] #3659. **Problem:** `examples/hf_ptq` keeps its VLM calibration loop and its generation previews in `example_utils.py` and `vlm_utils.py`, and defines its offline-data loader, FSDP2 call context and VL language-model preparation inside `hf_ptq.py` itself. Nothing outside the example can import them, including the ModelOpt CLI they are moving toward. **Fix:** they move into the library modules that hold their neighbours. `hf_ptq.py` imports them from there. One change goes beyond the move. The VL preview read its sample images from an `images/` folder beside `vlm_utils.py`, and library code cannot look beside its own file. So `run_vlm_preview` and `run_vl_preview_generation` take `images_dir`, and without one they skip the image preview. `hf_ptq.py` passes its own `images/` folder, where `vlm_utils.py` looked. Pillow stays optional: it is imported where an image is opened. | From | To | |---|---| | `example_utils.create_vlm_calibration_forward`, `create_vlm_calibration_loop` | `modelopt.torch.utils.vlm_dataset_utils`, beside `get_vlm_dataset_dataloader` | | `example_utils.preview_generate_kwargs`, `keep_the_experts_implementation`, `run_vlm_preview`, `generate_excludes_prompt`; all of `vlm_utils.py` (`run_vl_preview_generation`, `run_text_only_generation`, `_load_sample_image`) | new `modelopt.torch.utils.plugins.hf_generate` | | `hf_ptq.extract_and_prepare_language_model_from_vl` | `modelopt.torch.export.model_utils`, beside `get_language_model_from_vl`, which it calls | | `hf_ptq.fsdp2_call_context` | `modelopt.torch.utils.fsdp2_utils`, beside `fsdp2_root_unsharded` | | `hf_ptq._DeviceDataLoader`, `_shard_calib_dataloader`, `_move_batch_to_device` | `modelopt.torch.utils.dataset_utils`, as `DeviceDataLoader`, `shard_calib_dataloader` (public) and `_move_batch_to_device` | `create_vlm_calibration_loop` stays a loop of its own, as in the example. It runs the whole VLM, whatever module `mtq.quantize` targets. It passes each batch only the parameters the forward takes, renames an encoder-decoder's inputs, lets a model's plugin run the batch, and keeps an FSDP2 root unsharded for that plugin path. `create_forward_loop` runs the module `mtq.quantize` hands it, on tensor batches, and `distributed_forward_loop` does not unshard an FSDP2 root. An expert-parallel model already calibrates through `distributed_forward_loop`, with `create_vlm_calibration_forward` as its per-batch callback, as the loop's docstring now says. The previews' docstrings say that they serve the VLM wrappers `hf_ptq.py` previews, the models whose `PTQSpec` sets `vlm_wrapper`. ### Modules touched - `modelopt.torch.utils`: the calibration loop, the loader helpers, the FSDP2 context, and the previews in `plugins.hf_generate`. - `modelopt.torch.export`: the VL language-model preparation, beside the extraction it calls. - `examples/hf_ptq`: drops the helpers and imports them. ### Usage ```python from modelopt.torch.utils.distributed import distributed_forward_loop from modelopt.torch.utils.moe import expert_parallel_mesh from modelopt.torch.utils.plugins.hf_generate import run_vlm_preview from modelopt.torch.utils.vlm_dataset_utils import ( create_vlm_calibration_forward, create_vlm_calibration_loop, ) mtq.quantize(model, config, forward_loop=create_vlm_calibration_loop(model, calib_dataloader)) # An expert-parallel model calibrates through the distributed loop instead. ep_loop = distributed_forward_loop( model, calib_dataloader, device=device, ep_mesh=expert_parallel_mesh(model), forward=create_vlm_calibration_forward(model), ) mtq.quantize(model, config, forward_loop=ep_loop) run_vlm_preview(model, tokenizer, input_ids, ckpt_path, "after quantization", images_dir="images") ``` ### Testing - The tests move with the code: - the previews' tests to the new `tests/unit/torch/utils/test_hf_generate.py`; the image-preview tests pass `images_dir` instead of patching `vlm_utils.__file__`, and the sharded skip test gains a case without one, which needs no Pillow; - the calibration loop's to the new `tests/unit/torch/utils/test_vlm_dataset_utils.py`; - the loader sharding test to `test_dataset_utils.py`, and the VL preparation's to `tests/unit/torch/export/test_unified_export_hf.py`. - CPU only (Python 3.13, torch 2.10, transformers 5.4), `tests/unit/torch/utils`, `tests/unit/torch/models`, `test_unified_export_hf.py` and `tests/examples/hf_ptq`, on main and on this PR: | | main | this PR | |---|---|---| | failed | 47 | 47, the same tests (CUDA extensions, `hf_ptq.py` runs that need a GPU) | | passed | 1,668 | 1,669: the new case of the sharded skip test | | skipped | 178 | 178 | - The moved tests also run without transformers, as CI's partial-install lane does; the Nemotron-H Omni calibration case skips there, since its hooks include Nemotron-H's MTP plugin. - Pre-commit, mypy included, passes against main. GPU tests are not run locally; CI runs them now that this PR targets main. ### 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?: ✅ `hf_ptq.py`'s command line and previews are unchanged. Scripts that imported these helpers from the example directory import them from the library. - 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?: N/A The helpers' tests move with them. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: N/A One entry for the stack, in [4/4]. - Did you get Claude approval on this PR?: ✅ LGTM. Claude can't approve a PR that moves tests, so its review asks a human reviewer to confirm the move. ### Additional Information Tracked by OMNIML-6666 (epic OMNIML-3619, nv-modelopt unified entry point), for ModelOpt 0.50.0. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * VLM previews can use a specified image directory and coordinate image availability across distributed workers. * Multimodal calibration supports encoder-decoder inputs and filters unsupported arguments. * **Improvements** * Calibration data can be sharded while preserving device-aware loading. * Preview generation uses synchronized settings in supported distributed configurations. * Ambiguous vision-language model structures are detected and reported as errors. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <shengliangx@nvidia.com> |
||
|
|
073eceb541 |
launcher: clean up the Qwen3-8B DFlash2 streaming example (#2932)
### What does this PR do?
Type of change: New example
Problem: The Day-0 speculative-decoding workflow copies
`hf_streaming_dflash2.yaml` as its streaming template, but the example
floats on `vllm/vllm-openai:latest` (training) and `:nightly` (smoke
test) and writes its export to a fixed `/scratchspace/export`. A run
can't be reproduced, and its smoke test can't be re-run against an
earlier export. It also trains on 16-token blocks, while vLLM ignores
the checkpoint's `block_size` and serves DFlash2 with a block of 1 +
`NUM_SPEC_TOKENS`: 8, with the `NUM_SPEC_TOKENS=7` that task_2 sets.
Fix: Pin `vllm/vllm-openai:v0.31.0` by its multi-arch index digest
(linux/amd64 and linux/arm64; contains vllm#52816 for DFlash2) for
training and the smoke test, route the training checkpoints and the
drafter export through `global_vars.output_dir`, and train on block 8.
- `dflash.dflash_block_size=8` (was the recipe's 16), the block task_2
serves with `NUM_SPEC_TOKENS=7`. Block 8 also matches the library
default and the published DFlash2 drafters, and an ablation found no
acceptance-length cost (see Testing).
- Training output, `EXPORT_PATH`, and the smoke test's `DRAFT_MODEL` all
go through `global_vars.output_dir`, so one override moves producer and
consumer together. The smoke test writes `SMOKE_JSON` to its own
`/scratchspace`, so a rerun against an earlier export never replaces
that experiment's verdict.
- `TRITON_CACHE_DIR` keeps the launcher's default, the shared
`/cicd/triton-cache`, as on main. A node-local cache is opt-in: launch
with `TRITON_CACHE_DIR=/tmp/triton-cache`, as the header's third Usage
line shows.
- `dflash2.md` follows the new export path and notes that
`dflash_block_size` and `NUM_SPEC_TOKENS` change together.
### Usage
```bash
uv run launch.py --yaml examples/Qwen/Qwen3-8B/hf_streaming_dflash2.yaml --yes
# rerun only the smoke test against an earlier experiment's export; its verdict lands in this experiment
uv run launch.py --yaml examples/Qwen/Qwen3-8B/hf_streaming_dflash2.yaml \
pipeline.global_vars.output_dir=/cicd/<experiment_id>/dflash2 \
pipeline.task_0.skip=true pipeline.task_1.skip=true --yes
# Slurm with enroot < 4.0: run both vLLM tasks from a .sqsh built from the pinned digest
uv run launch.py --yaml examples/Qwen/Qwen3-8B/hf_streaming_dflash2.yaml \
pipeline.task_1.slurm_config.container=/path/to/vllm.sqsh \
pipeline.task_2.slurm_config.container=/path/to/vllm.sqsh --yes
# opt-in node-local Triton cache instead of the launcher's shared /cicd/triton-cache
TRITON_CACHE_DIR=/tmp/triton-cache uv run launch.py \
--yaml examples/Qwen/Qwen3-8B/hf_streaming_dflash2.yaml --yes
```
### Testing
- On main (
|
||
|
|
6bb8f69614 |
Keep Megatron test harness green on Megatron-Core 0.21 (#3697)
### What does this PR do? Type of change: Bug fix (tests only) **Problem:** On nemo:26.12 (Megatron-Core 0.21, TE 2.22) about 34 `tests/gpu_megatron` tests fail because of the test harness, not the library: - Megatron-Core #9071 made `alltoall` the default MoE token dispatcher. It sizes its buffers from the build-time `moe_router_topk`, so tests that set `router.topk = num_experts` after building the model fail in `split_with_sizes` (20 tests). - `distributed_setup_size_1` never destroys Megatron's model-parallel state. When an in-process test fails before its own cleanup, every later one fails with "data parallel group is already initialized" (13 tests, all passing in isolation). - Megatron-Core records a model's attention backend in `NVTE_FLASH_ATTN` / `NVTE_FUSED_ATTN` / `NVTE_UNFUSED_ATTN` and asserts later models agree. A flash-backend hybrid model leaves `NVTE_FUSED_ATTN=0` in a reused worker, which fails `test_sequential_experts_export_at_ep` in a later module. **Fix:** - Tests that calibrate every expert build with `moe_router_topk=num_experts` (`_gpt_model_provider(route_all_experts=True)`) instead of raising `router.topk` afterwards, so they keep Megatron-Core's default dispatcher, alltoall on 0.21. - `distributed_setup_size_1` runs inside the new `distributed_size_1()`, which also calls `destroy_model_parallel()` on the way out. - `reset_worker_state` (run at each test-module boundary) restores the `NVTE_*ATTN*` variables to what the worker spawned with. ### Testing - `test_reset_worker_state_restores_the_settings_a_worker_starts_with` now also checks the `NVTE_*_ATTN` variables. - New `tests/gpu_megatron/torch/utils/test_distributed_setup.py`: a failure inside `distributed_size_1()` after initializing Megatron must not stop the next setup from initializing it again. Results are being collected and will be added here. ### 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)?: N/A (tests only) - Did you get Claude approval on this PR?: N/A ### Additional Information OMNIML-6686 (ModelOpt on nemo:26.12). Lands together with #3696 (TE 2.21+ grouped-linear quantization): on nemo:26.12 this PR alone moves 7 MoE quantization tests past the dispatcher error and onto the bug #3696 fixes. 🤖 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 * **Tests** * Improved coverage for restoring attention-related environment settings when workers are reset. * Added checks that distributed and model-parallel state is cleaned up after test failures, allowing subsequent tests to initialize independently. * Updated mixture-of-experts test setup to configure expert routing during model construction. <!-- 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> |
||
|
|
1f5223a305 |
Refuse hybrid Qwen3.5 models in the deprecated Megatron exporter (#3700)
### What does this PR do? Type of change: Bug fix **Problem:** Megatron-Bridge 0.8 (in nemo:26.12) builds the Qwen3.5 / Qwen3.5-VL language model as a Megatron-Core hybrid model, whose pattern mixes GatedDeltaNet (`G`), MoE (`E`) and attention (`*`) layers. The deprecated `export_mcore_gpt_to_hf` has no rules for that layout. It fails with `KeyError: 'final_norm'`, and even with a `final_norm` rule added it silently drops every MoE layer's MLP and `post_attention_layernorm`. Megatron-Bridge's `AutoBridge.save_hf_pretrained_modelopt` already exports these models, and this exporter is removed in 0.51.0, so it isn't worth finishing. **Fix:** The exporter now refuses, at construction and before anything is written, any Megatron-Core hybrid model whose architecture has no rules for the hybrid stack. It points to `AutoBridge.save_hf_pretrained_modelopt`. The check uses only the model type and the HF architecture, so every rank raises together. Nemotron-H, its Omni variant and GLM-5 Next have hybrid rules and still export. `examples/megatron_bridge/export_quantized_megatron_to_hf.py` falls back to this exporter only for GGML / IQ formats, `--export_extra_modules`, weights Megatron-Bridge can't pack, and `--modelopt_megatron_exporter`. For a hybrid Qwen3.5 model, it now refuses as soon as it picks that fallback, before the `--tp_size` / `--pp_size` errors: a rerun at TP=1 would only get past those to hit this refusal. With `--modelopt_megatron_exporter` alone, the error says to drop the flag. Otherwise it says neither exporter can write the checkpoint. **Those fallback cases aren't supported for Megatron-Bridge 0.8's hybrid Qwen3.5 models.** ### Modules touched - `modelopt/torch/export`: the refusal in `GPTModelExporter`. - `examples/megatron_bridge`: the example checks the same rules (`has_hybrid_export_rules`) when it picks ModelOpt's exporter, so it refuses before its parallelism errors. ### Testing - `tests/gpu_megatron/torch/export/test_quantized_mbridge_export.py::test_matches_megatron_exporter[qwen3_5_moe_vl-nvfp4]`: when the language model's hybrid pattern has `G` layers, ModelOpt's exporter is expected to refuse, and the Megatron-Bridge export still runs. Otherwise the parity check is unchanged. - New `tests/examples/megatron_bridge/test_export_routing.py::test_a_hybrid_model_without_hybrid_rules_is_refused` uses a tiny hybrid model with a tiny Qwen3.5 HF config. `export_mcore_gpt_to_hf` refuses it without creating the export directory. In the example, `--modelopt_megatron_exporter` and `--export_extra_modules` at `--tp_size 2` both get the hybrid refusal rather than the `--tp_size 1` error. This test runs in today's CI. Ran locally on 2 GPUs: - nemo:26.10 with the Megatron-Bridge commit CI overlays: all 4 parity cases and all 8 routing tests pass. With the source changes reverted, the new routing test fails with the `--tp_size 1` `ValueError`. - nemo:26.12 (Megatron-Core 0.21, TE 2.22): results pending, will update. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ (the refused models already failed or exported a broken checkpoint) - 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 OMNIML-6686. #3683 also edits `unified_export_megatron.py`; this PR touches only `GPTModelExporter.__init__` and its docstring there. 🤖 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** * Hybrid Qwen3.5 models unsupported by the ModelOpt Megatron exporter now receive a clear error. Where applicable, users are directed to Megatron-Bridge, which has limitations for GGML/IQ formats and EAGLE modules. * **Documentation** * Updated the release notes and Megatron-Bridge guide to clarify export limitations and alternatives for hybrid Qwen3.5 models. * Documented the updated resume requirements for distributed `auto_quantize` workflows. <!-- 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> |
||
|
|
4bfb2a595c |
Fix TE GroupedLinear quantization on Transformer Engine 2.21+ (#3696)
### What does this PR do?
Type of change: Bug fix
**Problem:** On Transformer Engine 2.21+ (nemo:26.12 ships TE 2.22 with
Megatron-Core 0.21), quantizing a Megatron-Core MoE model with
grouped-GEMM experts breaks. TE now calls `_GroupedLinear` as `(inp,
fwd_args, *weights_and_biases)` and passes no bias tensors when the
layer has no bias, which is the case for Megatron-Core's experts.
`te_grouped_quantized_linear_fn` assumed `2 * num_gemms` trailing
tensors, so it located the expert weights wrongly and quantized `inp` /
`fwd_args` in their place. Every Megatron-Core MoE quantization test
fails on TE 2.22.
**Fix:** When TE's signature has `fwd_args`, the weights start right
after it, with or without biases. TE 2.20 and older keep the existing
path. `GroupedLinear(single_grouped_weight=True)` (one `weight` for all
GEMMs, Megatron-Core's `moe_single_grouped_weight`) now gets a clear
`NotImplementedError` at `mtq.quantize` instead of an internal
assertion, since the plugin quantizes per-GEMM `weight{i}`.
### Testing
`test_transformer_engine.py::test_quantize` gains a bias-free
`TEGroupedLinear` case, the layout Megatron-Core's experts use. For the
grouped cases it also checks that every expert's weight quantizer gets
that expert's weight, in both the inference and the autograd forward.
`tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py`,
on one sm_89 GPU:
- nemo:26.12 (Megatron-Core 0.21, TE 2.22): 37 passed, 8 skipped. With
the fix reverted, the 6 bias-free cases fail (`'NoneType' object has no
attribute 'numel'`: the wrapper quantized the forward's `ctx`
placeholder as a weight).
- nemo:26.10 with CI's Megatron-Bridge pin (TE 2.20): 37 passed, 8
skipped. TE 2.20 still passes biases, so the old path is unchanged and
the revert can't fail there. CI's nemo:26.10 can't show this bug.
- `GroupedLinear(single_grouped_weight=True)`: TE 2.22 now raises the
new `NotImplementedError` at `mtq.quantize` (before: `AssertionError:
self.weight should not exist`). On TE 2.20 the flag leaves per-GEMM
`weight{i}`, and quantization is unchanged.
- The Megatron MoE quantization tests in `test_megatron.py` on
nemo:26.12 also need #3697; that combined run is reported there.
### 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?: N/A
### Additional Information
OMNIML-6686 (ModelOpt on nemo:26.12). Lands together with #3697 (test
harness): on nemo:26.12 that PR alone moves the MoE tests past the
dispatcher error and onto this bug.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
ac76342ff7 |
[OMNIML-6461] [5/7] Run the AutoQuantize weight search on expert-parallel models (#3250)
### What does this PR do?
Type of change: New feature
**Stack**, split from this PR at review (merge in order): [1/7] #3612
(merged) → [2/7] #3634 (merged) → [3/7] #3636 (merged) → [4/7] #3617
(merged) → **[5/7] #3250** → [6/7] #3613 → [7/7] #3614. The review
threads before the first split cover every slice; this one keeps the
expert-parallel weight search, and [2/7] to [4/7] the checks every
distributed search runs.
**Problem:** `mtq.auto_quantize` refused a model whose routed experts
are sharded expert-parallel, so a model that `load_pretrained` loads
expert-parallel could not get a mixed-format search. The searcher
already sums each module's scores and costs over its TP/DP/EP groups and
broadcasts the chosen formats, so ranks that each score their own data
can agree. What kept it from running, and from picking the right
formats:
- **The experts' all-to-all forwards.** Quantizer insertion rebinds
`forward` and drops transformers' wrapper that hands the torch_a2a
experts their process group (transformers >= 5.16).
`distributed_forward_loop` re-plants it for `mtq.quantize`;
`auto_quantize` never did, so its first forward failed.
- **The experts' cost.** From transformers 5.16 the expert-parallel load
leaves the experts' weights as DTensors, whose size is already the whole
tensor's. `get_cost` summed that size over the EP group, so the experts
counted `ep_size` times in the effective-bits budget and the search
picked other formats.
- **`aumann_shapley` over the experts alone.** Its loss and token count
were reduced over the first module carrying a parallel state. A search
whose only configurable groups are routed experts took an expert's
groups, which span only the ranks holding the same experts, while its
expert-parallel ranks score data of their own too.
**Fix:** `auto_quantize` re-plants the experts' forwards after its
conversion, over the model's expert-parallel mesh, which every rank
checks against its experts' group in a setup collective before the model
is converted. That collective also runs, for every candidate, main's
check of the groups each rank's routed experts name, and compares the
ranks' recorded plans, every rank walks the model's modules in one
order, in which calibration syncs every module's scales, dense and
routed experts alike, within and across the expert-parallel rows, every
member of each process group the modules sync their scales over agrees
on its modules, and the ranks of each mesh compare each expert weight's
communicator, which calibration's check reduces over: ranks that would
take different routes or reduce over different communicators are refused
together. `get_cost` sums each weight over the TP/EP groups its DTensor
mesh leaves out. [4/7] records each DTensor weight's mesh and placements
in a checkpoint's layout; a file written on plain shards, as a search
before transformers 5.16 writes it, records none for such a weight and
is refused. The message names that cause and points at a new path or
`get_auto_quantize_config`. Under the recorded expert-parallel plan,
`aumann_shapley` sums its loss and token totals over every rank, each of
which scores a batch of its own; other layouts keep main's reduction. An
expert-parallel search steps its batches together, as FSDP2's does. A
SmoothQuant format the search selects is folded into an FSDP2-sharded
weight in its weight-access window. In the search, whose calibrations
every rank runs in step, calibration's share of the experts' input amax
over each expert-parallel group runs on a recorded expert-parallel plan
in a failure-aware collective every rank joins, so a group refusing a
per-channel scale some of its ranks lack after routing raises on every
rank, not only on its own; a standalone or subgroup calibration keeps
main's group-local refusal. The setup also checks that each routed
experts module's projections hold, on every rank, as many experts as the
module counts, which its quantizers index by, and that every rank counts
the same: a rank counting otherwise would index its experts by global
expert, or route its tokens by another count, alone. On a recorded
expert-parallel plan, a GPTQ candidate that would rewrite the routed
experts is refused before any calibrates, whether the load holds them as
DTensors or, before transformers 5.16, as each rank's plain share;
Megatron's experts, which no plan records, are rewritten as before. On
an expert-parallel plan, routed experts' input quantizers whose state
the tokens routing sends them shapes are refused the same way, before
any calibrates: a static scale kept per token, by an axis or by block
sizes of `None` along the hidden dim, and static blocks, whose reshape
fixes the input's shape in every forward, calibrating or not. Received
token counts change with each batch and rank, so such a quantizer would
raise on one rank inside the experts' forward while its peers wait in
the all-to-all. Every expert-parallel search saves the unconverted
modules for these refusals. Per-tensor, per-channel and fixed-size
dynamic-block scales are searched. A format whose resolved activation
quantizers use a static bias is refused on a model `load_pretrained`
distributes over several ranks. Calibration loads that bias on each rank
from its own data, or, with the quantizer pinned to a constant amax, not
at all. Quantization still reads it, so a rank whose experts get no
tokens would skip a read on which its peers fail. A weight quantizer's
static bias, which comes from the weight, and a static-bias entry that
is disabled, or whose match a later entry disables, are admitted. A
search over several processes refuses a layerwise `checkpoint_dir`
before converting the model, which layerwise calibration refused only
after. The KV-cache search keeps refusing an expert-parallel model,
before converting it, until [6/7].
Why the experts' forwards are re-planted in the search rather than in
quantizer insertion: insertion is layout-agnostic and has no mesh, and
runs for callers that run no forward, such as a restore. So each path
that converts the model and then runs forwards re-plants them after its
conversion over the mesh the model carries, as
`distributed_forward_loop` does for `mtq.quantize`.
Still run in one process, as on main: `hf_ptq.py`'s
`auto_quantize.finalize_algorithm` and format-shard options. Rank-local
calibrations (AWQ and the others) stay refused per candidate, as before.
### Usage
```python
import modelopt.torch.quantization as mtq
from modelopt.torch.utils.distributed import distributed_run
from modelopt.torch.utils.plugins.model_load_utils import load_pretrained
# Launched with torchrun: distributed_run() sets up the process group, so load and search inside it.
with distributed_run():
model = load_pretrained(ckpt) # records the plan (EP or replicated), and for EP the experts' mesh
model, search_state = mtq.auto_quantize(
model,
constraints={"effective_bits": 5.4},
quantization_formats=[mtq.NVFP4_DEFAULT_CFG, mtq.FP8_DEFAULT_CFG],
data_loader=this_ranks_shard, # every rank runs the same number of batches
forward_step=lambda m, batch: m(**batch),
loss_func=lambda output, batch: output.loss,
)
```
### Testing
- New
`tests/unit/torch/quantization/test_autoquant.py::test_expert_parallel_auto_quantize_picks_one_processes_formats[gradient|kl_div|aumann_shapley]`,
on two CPU ranks (gloo). A tiny Qwen3-MoE is sharded as transformers'
expert-parallel load leaves it (`apply_tensor_parallelism` with the
load's torch_a2a plan: DTensor experts behind forward wrappers, on
transformers 5.18 and 5.23 alike), with each module's groups seeded as
the load seeds them. Each rank searches on its own batch; one process
searches on every rank's batch, one per step. Formats and costs are
equal, and scores agree within 1e-2 relative (gradient: ~1e-7; a
KL-divergence score also within a thousandth of the largest, as an INT8
weight's KL of ~1e-6 is at float32 noise). `aumann_shapley` searches the
experts alone. Each fix fails it when reverted:
| Reverted | Result |
|---|---|
| re-planting the a2a forwards | `gradient`, `aumann_shapley`:
`torch_a2a experts forward requires the EP process_group` |
| DTensor weights summed over EP | `gradient`, `aumann_shapley`:
experts' costs 2x (ep_size) |
| shapley's totals over every rank | `aumann_shapley`: scores up to 59%
off |
- New expert-parallel and FSDP2 tests; each refusal among them comes on
every rank, where one rank alone would otherwise leave the others in a
collective:
-
`test_expert_parallel_weight_search_resumes_from_its_checkpoint[own|swapped|legacy_swapped|other_plan|no_weight_layouts|in_one_process]`:
a valid expert-parallel resume passes; swapped files, swapped files that
record no writer or layout, another plan's files, files that record no
weight layouts for the experts' DTensor shards (as a search on plain
shards before transformers 5.16 writes them), and one process taking a
rank's file are refused; the four multi-rank refusals hand back the
unconverted model, as the search saves it whenever it resumes from a
file.
`test_tensor_parallel_resume_of_a_file_recording_no_weight_layouts_is_refused[as_plain_shards|by_0_49]`:
the test rewrites a tensor-parallel DTensor weight's rank files to the
layout a load that leaves the weight a plain tensor records, or to
0.49's fields, which record no layout. Every rank refuses them and hands
back the unconverted model, and `get_auto_quantize_config` still
re-solves their scores to the formats the search picked.
`test_fsdp2_folds_a_selected_smoothquant_format`: a SmoothQuant format
an FSDP2 search selects is folded into each sharded weight in its
weight-access window, and the fold reaches the shards.
-
`test_expert_parallel_search_refused_on_one_rank_raises_on_every_rank[gradient-no_mesh|reordered_mesh|mesh_over_another_communicator|expert_over_another_communicator|experts_over_swapped_communicators|experts_in_another_order|dense_and_experts_in_another_order|dense_over_another_communicator|no_plan|own_ep_group|expert_on_another_dim|global_expert_count|global_expert_count_on_plain_shards|global_expert_count_on_every_rank|count_unlike_peers]`:
a rank missing the experts' mesh or holding it with its ranks reordered
or over another communicator, holding an expert's weight on another
communicator of the same ranks, recording no plan, naming other experts'
groups, or holding an expert sharded on another dim, and ranks holding
two layers' expert weights over two communicators the other way round,
or alike but registered in another order, and a rank registering a
layer's experts before its attention or syncing an attention over
another communicator; a rank whose experts count every rank's experts,
with DTensor or plain shards, and a rank holding and counting more
experts than its peers.
-
`test_expert_parallel_batches_unequal_on_one_rank_raise_on_every_rank`:
the experts' all-to-alls step the batches together.
- `test_aumann_shapley_totals_over_an_expert_parallel_world`: under a
recorded expert-parallel plan, `aumann_shapley`'s loss and token totals
sum over every rank, also where no module carries a parallel state.
- `test_a_row_of_ranks_recording_no_plan_is_refused`: four ranks at EP=2
whose first row records no plan, while each row's meshes agree, are
refused by the plans' comparison alone; with the plan on every rank,
rows on communicators of their own pass.
- `test_a_row_of_ranks_walking_its_experts_otherwise_is_refused`: four
ranks at EP=2 whose second row walks the experts in reverse, while each
row agrees with itself, are refused by the order's comparison across
every rank.
-
`test_kv_cache_auto_quantize_refuses_an_expert_parallel_model_before_changing_it`:
main's refusal test, now for the KV-cache search, which this slice still
refuses before converting the model. [6/7] lifts the refusal.
- New
`tests/gpu/torch/quantization/test_amax_sync_distributed.py::test_expert_input_amax_one_row_lacks_fails_every_row`
(four GPUs): rows of two ranks over gloo groups that time out, one
rank's experts given no tokens, calibrating in step as the search does,
refuse the per-channel share on every rank, rather than one row raising
while the other waits; and, with no plan, a pair of ranks sharing its
experts' amax over its own group calibrates beside a pair without
experts, with no collective across the pairs
(`test_expert_input_amax_shared_within_one_pair_calibrates`).
-
`test_expert_parallel_search_refuses_expert_input_scales_tokens_shape[per_token|per_token_blocks|static_blocks|static_blocks_quantized_dynamically]`:
on two ranks, with batches of one size whose tokens routing sends each
rank in other numbers, each layout is refused on every rank before any
calibrates, and the same model then searches per-channel scales. Each
layout fails in the experts' forward without the refusal.
-
`test_expert_parallel_search_refuses_gptq_on_routed_experts[dtensors|plain_shards]`:
a GGML q8_0 GPTQ candidate is refused on every rank, with the experts as
DTensors or as each rank's plain share, handing back the unconverted
model;
`test_ggml_gptq.py::test_gptq_rewrites_experts_no_expert_parallel_load_sharded`:
experts each whole on their rank, under an expert-parallel group but no
plan, as Megatron's, are searched and rewritten as before, meeting a
3-bit target.
-
`test_expert_parallel_search_refuses_a_static_bias_on_every_rank[candidate|fixed_baseline|constant_amax_on_an_empty_shard|constant_amax_weight_on_an_empty_shard]`:
four static biases are each refused on every rank before any calibrates,
handing back the unconverted model. Three are on input quantizers: one
in a candidate, one in the fixed baseline, and one pinned to a constant
amax on the routed experts alone, with a router hook that leaves one
rank's experts no tokens. Without the refusal, that case fails in the
experts' forward on the rank that got tokens, while the other waits in
the all-to-all. The fourth is on the routed experts' weight quantizers,
pinned to a constant amax: calibration loads it no bias, and without the
refusal every rank fails in scoring.
`test_data_parallel_search_admits_a_static_bias_off_the_data[entry_disabled|disabled_later|weight_bias]`:
on two replicated-DP ranks with different batches, a static bias its
entry disables, or a later entry does, is admitted, as is a weight
quantizer's, and the selected weight biases agree across the ranks.
`test_search_over_several_processes_refuses_a_layerwise_checkpoint_dir`:
on two ranks, a tiny Llama search whose candidate sets a layerwise
`checkpoint_dir` is refused on every rank, leaving the model
unconverted. `test_auto_quantize_fails_fast_on_nonfinite_gradients` also
checks that every forward of the search runs inside
`_every_rank_calibrating()`, and that the promise ends with the search
when it fails.
- `test_fsdp2_folds_a_selected_smoothquant_format[gradient|kl_div]`: on
two FSDP2 ranks, the INT8 SmoothQuant format the search selects is
folded into each shard, and an explicit `reshard()` after the search
leaves the output unchanged. Without resharding before the fold, the
`kl_div` case fails that check: its forwards leave the root's weights
whole, and the fold went into those temporaries.
- New
`tests/unit/torch/quantization/test_dist.py::test_a_rank_calibrating_alone_under_a_recorded_plan_joins_no_collective`:
under a recorded expert-parallel plan, a rank calibrating alone joins no
collective of every rank.
- New cost tests:
`test_a_dtensor_is_whole_over_a_group_its_mesh_holds_or_this_ranks_part`,
`test_expert_parallel_cost_counts_each_projection_by_its_own_layout[plain_shard|own_rank_dtensor]`
and `test_tensor_parallel_cost_counts_a_dtensor_weight_once`. They drive
the cost on each layout directly; the expert-parallel test above checks
the search's costs through `auto_quantize` against one process.
Each fails with its change reverted; about 2 s per id once the shared
worker pool is up.
- CPU, torch 2.14: the stack's CPU set at this head, 1051 passed with
transformers 5.23, CI's, and 1051 with 5.18. Pre-commit, mypy included,
passes against main.
- GPU (CI's GPU job runs on this PR, on one GPU, now that it targets
main; these are cluster runs):
`tests/gpu/torch/utils/test_moe_a2a.py::test_expert_parallel_auto_quantize_and_export_match_the_whole_model`
runs the production expert-parallel load in float32 over three layouts:
experts over every rank, over half of them, and with the dense part
FSDP2-sharded. It compares the search's costs, scores and formats, and
then the no-gather writer's mixed-format checkpoint, with the whole
model's single-process run. With the experts over half the ranks (EP=2
on 4 GPUs) it also saves the search and resumes it with no forward,
checking that the picks, scores and each quantizer's scales are the ones
saved. It then loads the model twice more, once with no plan recorded on
the first row of ranks and once with the second row's experts registered
in reverse, and checks that every rank refuses each search before any
runs a forward or converts its model. These passed on 2026-12-02 at
|
||
|
|
030f1ecf2d |
[OMNIML-6666] [1/4] Move hf_ptq's model and tokenizer loading into model_load_utils (#3656)
### What does this PR do? Type of change: New feature (library home for example helpers) **Stack** (merge in order): **[1/4] #3656** → [2/4] #3657 → [3/4] #3658 → [4/4] #3659. **Problem:** `examples/hf_ptq/hf_ptq.py` loads its model and tokenizer with `get_model` and `get_tokenizer` from `examples/hf_ptq/example_utils.py`. Other scripts and the library's own tests reach into the example directory through `sys.path` to reuse them, and the ModelOpt CLI (the nv-modelopt unified entry point) cannot import them at all. This stack moves every helper module of `examples/hf_ptq` into the library; this PR moves the loading. **Fix:** both move into `modelopt.torch.utils.plugins.model_load_utils`, beside `load_pretrained`, which `get_model` wraps, together with `get_model`'s private helpers. `hf_ptq.py` and `run_tensorrt_llm.py` import them from there. Some changes go beyond the move, now that `get_model` is library code: - Its MXFP4 check calls the loader's existing `_ckpt_quant_method` instead of a copy of its own. Its pack-quantized check reads the same config levels, a VLM's `llm_config` included, and counts any level that names the format, as before. - Its packed load path keeps a CPU request on the CPU, as the MXFP4 path does, and a model spec's request for no device map, after which the model moves to its device before its weights are unpacked. The example handed that path an "auto" map either way, which could place the weights on a visible GPU or under a map the spec refuses. - Its progress lines print once per run, on rank 0, and the parameters whose meaning the signature does not show are documented. - The unused `get_dtype` is dropped. accelerate stays an import inside the functions that use it, so the module still imports without it. | From `examples/hf_ptq/example_utils.py` | To `modelopt.torch.utils.plugins.model_load_utils` | |---|---| | `get_model`, `get_tokenizer` | same, public (`__all__`) | | `_resolve_init_config`, `_get_config_dtype`, `_apply_dtype_to_config`, `_fmt_max_memory`, `_unpack_compressed_linear_weights` | same | | `is_model_on_gpu` | `_is_model_on_gpu` | | `get_original_hf_quant_method` | dropped: `get_model` calls `_ckpt_quant_method` | | `has_pack_quantized_config`, nested in `get_model` | `_ckpt_is_pack_quantized`, which also reads `llm_config` | | `get_dtype` | dropped: unused | ### Modules touched - `modelopt.torch.utils.plugins.model_load_utils`: the loaders' new home. - `examples/hf_ptq`: drops the loaders and imports them. ### Usage ```python from modelopt.torch.utils.plugins.model_load_utils import get_model, get_tokenizer model = get_model("Qwen/Qwen3-8B", device="cuda") tokenizer = get_tokenizer("Qwen/Qwen3-8B") ``` ### Testing - The loaders' tests move to `tests/unit/torch/utils/test_model_load_utils.py`, and the bundled-code rules' tests to `tests/unit/torch/models/test_nemotron_h_mtp.py` and `test_hf_hooks.py`. The 4 tests of the dropped `get_original_hf_quant_method` go; `_ckpt_quant_method` has its own. `_ckpt_is_pack_quantized` gets 4 cases. The rank-pin test also checks that the MXFP4 load dequantizes and that only the pack-quantized checkpoint is unpacked. The two moved tests that load a real checkpoint take 0.74 s at most. A new test checks that a CPU load of a packed checkpoint stays on the CPU, with the metadata at the top level or only in `llm_config`. Another checks that a spec's request for no device map holds there, and that the model moves before the unpacking. - CPU only (Python 3.13, torch 2.10, transformers 5.4), `test_model_load_utils.py`, `tests/unit/torch/models` and `tests/examples/hf_ptq`, on main and on this PR: | | main | this PR | |---|---|---| | failed | 47 | 47, the same tests (CUDA extensions, `hf_ptq.py` runs that need a GPU) | | passed | 987 | 990: the 4 dropped tests go, and 7 new cases come | - Pre-commit, mypy included, passes against main. GPU tests are left to CI. ### 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?: ✅ `hf_ptq.py`'s command line is unchanged. Scripts that imported these helpers from the example directory import them from the library. - 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?: N/A The helpers' tests move with them. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: N/A One entry for the stack, in [4/4]. - Did you get Claude approval on this PR?: ✅ LGTM at the latest head: Claude finds every concern resolved and leaves only the test move for a human reviewer to confirm. It approved earlier heads. ### Additional Information Tracked by OMNIML-6666 (epic OMNIML-3619, nv-modelopt unified entry point), for ModelOpt 0.50.0. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Model loading for calibration supports device placement and memory-aware options, including sequential placement and disk offload. * Tokenizer loading uses the end-of-sequence token as a fallback when no padding token is set. * Checkpoint loading supports additional model-specific formats and configuration options, with improved placement across distributed GPU runs. * Model loading can select compatible bundled or built-in model implementations based on checkpoint configuration. * **Documentation** * Updated the documented location of the device-map guidance for FP8 calibration. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <shengliangx@nvidia.com> |
||
|
|
4648837aee |
Refuse Megatron export of quantized formats it writes no quantization config for (#3683)
### What does this PR do? Type of change: Bug fix **Problem:** `export_mcore_gpt_to_hf` writes a quantization config only for FP8, FP8 block-wise, NVFP4, W4A16 NVFP4 / MXFP4 and the GGML formats. Weights in any other format are still packed and written with their scales, but with no `quantization_config` and no `hf_quant_config.json`, and nothing warns that the checkpoint can't be loaded correctly. On a tiny Llama this happens with: - INT4 weight-only and INT4 AWQ, also after `disable_pre_quant_scale_and_resmooth(..., delete_pre_quant_scale=True)`, as reported in #3681; - MXFP8, MXFP4, W4A8 MXFP4-FP8 and W4A8 NVFP4-FP8; - a mixed model whose first quantized layer uses one of those formats. Related problems affect mixed models whose leading format is mapped: - INT4 layers get a per-layer config that claims a `pre_quant_scale`, which is never written. - Per-channel (INT8, FP8 per-channel) QKV layers, and 2-D blockwise FP8 on QKV, gate/up or GatedDeltaNet / KDA `in_proj` layers, crash during row slicing on their stage only, and the other stages hang. - Grouped experts whose quantizers differ are packed under a single recorded format. Under pipeline parallelism only the last stage's format was checked, because that stage writes the config. So a last stage holding no quantized layer, or an unmapped one, dropped the config for every stage. `examples/megatron_bridge/export_quantized_megatron_to_hf.py` reaches this exporter through `--modelopt_megatron_exporter` and through its fallback. **Fix:** - Before packing or writing anything, `save_pretrained` gathers from every rank the formats of the weights it exports. The scan covers only the children the export writes (`embedding`, `decoder`, `output_layer`, `mtp`), so drafts and a distillation teacher are left out. Within them it follows `_get_state_dict`'s selection: a tied output layer, the MTP stage's embedding, an MTP `eh_proj` the rules don't export, and KDA's raw `conv1d` and mHC's `mapping_proj` are skipped, and each grouped-expert quantizer is resolved as packing resolves it. - An export whose config-writing rank (the last pipeline stage's first rank) holds no quantized layer while other ranks do is refused on every rank: its config couldn't describe the other ranks' weights. A single-stage export keeps the writer's own format. - Every rank raises `NotImplementedError` in these cases: - no config is mapped for that format; - any exported layer uses a format whose per-layer config would promise a `pre_quant_scale` (INT4 / W4A8 AWQ, NVFP4 AWQ / SVDQuant), or has no usable schema (real blockwise FP8, `fp8_pb_real`, which was previously passed through as a top-level format); - a QKV layer has per-channel scales (by label, or by a multi-element weight amax); - a row-split layer (QKV, gated `linear_fc1`, GatedDeltaNet / KDA `in_proj`) uses blocks spanning several rows (2-D block scales, e.g. FP8 2-D blockwise); - an INT8-labelled weight carries block scales (MXINT8), which packs as neither INT8 layout; - a grouped module's experts, or the local experts that packed rules (Llama 4, GPT-OSS) stack into one tensor, differ in format or block size, or mix enabled and disabled. - The error names the format and points to HF PTQ export, or to Megatron-Bridge for the formats it supports. - If format detection fails on one rank, every rank raises instead of hanging. - #3681's base-model `pre_quant_scale` refusal, merged from main, shares the same single cross-rank exchange and takes precedence over format-detection errors. The exchange uses `modelopt.torch.utils.distributed.allgather` (tensor bytes loaded with `weights_only`), now backend-aware so CPU / Gloo groups work too. - No new formats are mapped. Mixed models such as FP8 + MXFP8 still export the same `MIXED_PRECISION` config. **Why a separate scan.** The preflight mirrors `_get_state_dict`'s module selection rather than reusing the export rules or `get_quantized_weight_export_spec`: - The refusal has to happen on every rank before any rank packs. The rule dispatch packs as it walks and runs expert-parallel collectives inside it, so a rank failing mid-walk would strand its peers, and a dry run would pack everything twice. - `get_quantized_weight_export_spec` (the functional spec Bridge and HF export use) has its own allowlist, which differs from what this exporter packs. Reusing it would refuse formats this exporter writes today and accept some it can't. - Each skip in the scan names the rule it follows (tied output, MTP embedding and `eh_proj`, KDA `conv1d`, mHC `mapping_proj`, drafts), and the tests cover them. ### Modules touched - `modelopt/torch/export`: the fix itself, in `unified_export_megatron.py`. - `modelopt/torch/utils/distributed.py`: `allgather` always put its tensors on CUDA and padded with an uninitialized buffer. The export preflight's cross-rank exchange needs it to pick the device from the group's backend configuration, so CPU / Gloo groups work too, and it now pads with zeros. ### Testing All runs used `nvcr.io/nvidia/nemo:26.10` with 2 local GPUs. - `tests/gpu_megatron/torch/export/test_unified_export_megatron.py`: - New `llama` + `MXFP8_DEFAULT_CFG` case in `test_unified_export_megatron`: export refuses and writes nothing. - New `nemotron_h` + `NVFP4_EXPERTS_ONLY_CFG` row: the real TEGroupedLinear experts alone produce both configs and are the only packed weights. - The Medusa rows now quantize only the draft heads and expect a BF16 export with no `hf_quant_config.json`. - The Llama PP=2 MTP test now quantizes only the MTP `eh_proj`, which Llama's rules don't export, and expects a BF16 export. - New PP=2 test `test_unified_export_megatron_pp2_quant_config_spans_stages`: - W4A16 NVFP4 on the first stage and an unquantized last stage: refused on both ranks, nothing written. - MXFP8 on the first stage behind a mapped W4A16 NVFP4 writer: exported with a `MIXED_PRECISION` config (inline and sidecar, including their per-layer entries) and both layers' packed weights and scales. - INT4 on the first stage with a mapped writer stage: refused on both ranks. - INT8 on the first stage (per-channel QKV) with a mapped writer stage: refused on both ranks. - Per-channel FP8 QKV with `axis=(0,)`, which resolves to plain `fp8`, with a mapped writer stage: refused on both ranks. - FP8 2-D blockwise on the first stage with a mapped writer stage: refused on both ranks. - A Qwen3.5 GatedDeltaNet model with FP8 2-D blockwise only on stage 0's `in_proj`: refused on both ranks. - Real blockwise FP8 on stage 0's `linear_fc2` behind a mapped writer: refused on both ranks. - MXINT8 only on stage 0's `linear_fc2`: refused on both ranks. - MXFP6 on one stage: detection fails there, and both ranks raise. - Every case runs under `bounded_collectives`, which now also bounds `dist.all_gather` (used by the preflight's `allgather`), so a rank left waiting fails in seconds. - New fast test `test_export_format_scan_follows_packing`. It uses TEGroupedLinear's numbered-weight layout with uniform experts, mixed experts, and a disabled first expert. The test checks that the scan resolves each expert as packing does, flags mixed groups, and ignores a quantized tied output layer, KDA's raw `conv1d`, and 2-D scales on Mamba's `in_proj`. - New fast test `test_qkv_per_channel_scales_are_found_by_the_scale_layout`: calibrated per-channel FP8 on QKV is refused; `axis=()`, a constant scalar amax, and static NVFP4 with one-row blocks (`{-2: 1}` or `{-2: None}`) are accepted and pack through the real `_qkv_slicing`. - New `test_retained_pre_quant_scale_refused_behind_a_supported_layer`: #3681's refusal still wins when the format scan raises on a GGML layer that kept its scale. - `test_mcore_vllm_export_packed` (vLLM fake-quant) now also exports a stack with one weight-only NVFP4 expert among BF16 ones. - Every new or changed case fails with the fix reverted. - Whole file plus `test_vllm_fakequant_megatron_export.py`, at |
||
|
|
369b8712a9 |
docs(review): scope findings to the PR and make re-reviews converge (#3695)
### What does this PR do?
Type of change: Bug fix (review guidance)
**Problem:** Since the review bots moved to gpt-6.2 on 2026-11-20,
reviews have run for many rounds. They focus on nits, hypothetical
callers and code the PR doesn't touch, and new issues arrive one round
at a time. Examples: #3499 and #3582 (11 bot rounds each), #3629 (13),
#3519 (14), #3502 (61).
Across Model-Optimizer PRs since 2026-10-25, gpt-6.2 averaged 7.2 review
rounds per PR, against 2.5 for gpt-6.1 under the same guidance. It
approved or LGTM'd 1% of PRs on the first round. 47% of its PRs got at
least one issue raised late, on code it had already reviewed, against
10% for gpt-6.1.
The baseline sets no limit on what counts as a finding. Its re-review
rules don't say how a review converges, and they keep a correct rebuttal
open: "a reply that argues the point without changing anything" counts
as unresolved. On #3582, 27 of the author's 53 replies showed the issue
already existed on `main`, and those items stayed open.
**Fix:** Adds "What earns an action item" and rewrites the re-review
rules so each round converges instead of starting over:
- **Three bars for an action item:** this PR caused it, a real path in
the repo reaches it, and it matters.
- Pre-existing problems, untouched sibling call sites and systems
outside the repo get at most a follow-up note.
- Invented callers, and failures that need a second unrelated fault,
don't qualify.
- Silent wrong results, corrupted checkpoints and hangs in the new code
are raised even when rare.
- The split, skill-compress, `CHANGELOG.rst` placement, licensing and
design asks keep their own rules.
- Everything else is a capped `Nit:` that never changes the decision.
- **A first review** raises everything at once and states each concern
at its full extent.
- **A re-review** judges each earlier concern as fixed, not fixed, or
not fixed well. It reviews only what changed since the last round, and
from round 3 raises new items only for severe problems. Another variant
of a concern already raised is not a new item.
- **"What counts as resolved"** keeps its evidence standard. It now
names what settles a concern without a code change: pre-existing, out of
scope, a committed follow-up, no real path, or a reasonable trade-off.
- **No asks for new runs, benchmarks or GPU results.** When the testing
notes disagree with the code, the review asks once for the notes to be
corrected.
- **The `AGENTS.md` pre-push checklist** is guidance on where to look,
not proof every PR must supply.
- **Licensing:** a PR that says it copied or transcribed something
always gets the licensing ask.
The markers (`:speech_balloon:`, `:heavy_check_mark:`, `:scissors:`) are
unchanged.
### Testing
This is a text-only change to review guidance. The same change ships in
the internal gh-review-bot prompt.
I replayed real PRs frozen at the commits the bot reviewed, with the
comment history as it was then, using gpt-6.2. Nothing was posted. Cells
are decision / action items:
| Snapshot | Current guidance | With this change |
| --- | --- | --- |
| #3577 round 4 | comment (×2) | lgtm |
| #3499 round 7 | lgtm, then comment on a `-> None` annotation | lgtm |
| #3519 round 14 | comment (production) | lgtm |
| #3582 round 6 | comment / 5 (×2) | comment / 3, all "not fixed well" |
| #3674 round 3 | comment / 5 | comment / 1–4 (no external-runner proof
or GPU reruns) |
The bugs both models agreed on are still raised: the BF16 overflow
(#3577), the Megatron rank hang (#3582), the AutoCast inference gap and
licensing (#3629), and a bug in #3629's pushed fix.
This PR's file was also replayed on its own, since it differs from the
internal prompt it was ported from. It matched:
- **#3577 round 1:** 2 items, the BF16 overflow and the CUDA sync.
- **#3629 round 1:** 4 items, including licensing and the `quantize()`
test break.
- **#3577 round 4:** lgtm.
- **#3582 round 6:** 3 items, all "not fixed well".
- **#3629 round 12:** 1 item, the bug in the pushed fix.
- **#3674 round 3:** 3 items. The review notes that "external teardown
and final-head reruns are not review requirements".
After the review-feedback commit (
|
||
|
|
606c95e7c3 |
Shard a sparse Megatron layer's weight mask when it is quantized on top (#3688)
### What does this PR do? Type of change: Bug fix **Problem:** a Megatron model that is sparsified and then quantized saves each sparse layer's `_weight_mask` without its tensor-parallel (TP) sharding. At TP > 1 the checkpoint keeps only TP rank 0's masks, so on reload the other ranks get rank 0's masks (same TP) or the load fails (another TP). Sparsity's `sharded_state_dict` took the mask's shard axis from `_get_shard_axis_dict`, but the stacked class's MRO resolves that to quantization's Megatron plugin's override, which only knows quantizer state. This affects every sparse column- and row-parallel linear (gated and non-gated MLPs, attention), and is why #3663's stacked legacy-mask test ran at TP=1. **Fix:** the sparsity plugin gives the mask its own shard axis (`_weight_mask_shard_axis`, 0 for column- and 1 for row-parallel) instead of overriding a method name quantization also uses. Quantizer state and sparsity-only checkpoints are saved exactly as before. ### Testing - `test_swiglu_weight_mask_tp_reshard` (`tests/gpu_megatron/torch/sparsity/weight_sparsity/plugins/test_megatron_sparsity.py`) gets a sparsity-then-FP8-quantization case saved at TP=2 and restored at TP=2 and TP=1. The source's weights are set to their masks, so after the restore every source mask (including each `linear_fc1`'s) must come back and equal its own weight, which Megatron reshards correctly by construction (this now checks all sparse layers, not only `linear_fc1`). The sparsity-only case also restores at both sizes; the legacy case keeps TP=1 only because the old single-key layout loads right only at its saved TP size, and its OMNIML-6311 note is dropped. - With the fix reverted, the new stacked case fails; the other cases pass. The same three cases also pass with a non-gated (squared ReLU) model, and its stacked case also fails without the fix (local check, not committed). - Ran in `nvcr.io/nvidia/nemo:26.10` on 2 GPUs: `test_megatron_sparsity.py`. CI runs the full suites. ### 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?: ⚠️ Sparse-then-quantized checkpoints now save the mask sharded, under the same key, so ones saved before at TP > 1 no longer load, even at their saved TP size (checked: a TP=2 checkpoint saved without the fix fails to load at TP=2 with it). They were already missing the other ranks' masks; re-save them from the original sparse model. Sparsity-only checkpoints and quantizer state are unchanged. - 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)?: ✅ 0.50.0 Bug Fixes. - Did you get Claude approval on this PR?: ❌ ### Additional Information Fixes the OMNIML-6311 item "Sparsity mask isn't TP-sharded when quantization is stacked on sparsity". Follow-up to #3663. 🤖 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 saving and restoring weight masks for sparse Megatron models using tensor parallelism, including quantized sparse models. * Current-format checkpoints can be loaded across supported tensor-parallel sizes. * Checkpoints created by earlier versions with this issue cannot be loaded, even at their original tensor-parallel size. Recreate them from the original sparse model. <!-- 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> |
||
|
|
7544e10ae2 |
[NVBug 6714779] Accept ONNX Runtime's SimplifiedLayerNormalization in ONNX quantization (#3670)
### What does this PR do? Type of change: Bug fix ONNX Runtime fuses RMSNorm into `SimplifiedLayerNormalization` in the default ONNX domain, and onnx-community LLM exports (Llama-3.2, Qwen3, Gemma 3, Granite 4.0, Phi-4-mini) contain it. ONNX doesn't define the op, so `quantize()` fails in `load_onnx_model` with `No Op registered for SimplifiedLayerNormalization`. **Fix:** `load_onnx_model` registers a schema for the op before shape inference. The schema matches ONNX Runtime's, and its inference function gives `Y` the shape of `X` and the type of `scale`. It is registered once per process and removed at exit, because ONNX 1.21 crashes at exit otherwise. AutoCast still treats the op as custom. Rewriting the op instead would change the shipped graph, and ONNX's `RMSNormalization` needs opset 23. ### Usage No API change; affected models now quantize. ### Testing - onnx-community Qwen3-0.6B, INT4 RTN on CPU: 196 INT4 `DequantizeLinear` nodes; all 57 `SimplifiedLayerNormalization` nodes kept. - New unit tests: `quantize()` and `load_onnx_model` on a model with the op (both fail without the fix), the schema against ONNX Runtime's, and AutoCast's classification after registration. - ONNX 1.21 exits cleanly (`partial-install (onnx)` CI job). - Not fixed: with TensorRT Python installed on Linux, `load_onnx_model` first parses the model with TensorRT, which has no importer for this op. ### 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 NVBug 6714779. Supersedes #3629 and #2425. 🤖 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 ONNX model loading and quantization for models containing ONNX Runtime’s default-domain `SimplifiedLayerNormalization` operator. - CPU-based INT4 quantization now works for models containing this operator, including models where it is followed by a matrix multiplication. - **Known Limitations** - TensorRT plugin discovery on Linux may still reject models that use this operator. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Haoxi Zhang <haoxiz@nvidia.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2e909a11fc |
Pass dynamic_cp to Megatron-Core's get_batch_on_this_cp_rank (#3693)
### What does this PR do? Type of change: Bug fix **Problem:** Megatron-Core renamed `get_batch_on_this_cp_rank`'s `is_hybrid_cp` argument to a required `dynamic_cp`. It kept `is_hybrid_cp` as a deprecated keyword for a while, and passing both raises an error. Newer builds drop the alias; this includes the Megatron-Core shipped with Megatron-Bridge #7057 and later. On those builds, ModelOpt's context-parallel split (`cp_split_sequence`, used for calibration with `--cp_size`) fails with `get_batch_on_this_cp_rank() missing 1 required positional argument: 'dynamic_cp'`. **Fix:** pass whichever of `dynamic_cp` / `is_hybrid_cp` the installed Megatron-Core takes, preferring `dynamic_cp`. Builds that take neither get neither, as before. ### Testing I ran `tests/examples/megatron_bridge/test_quantize_export.py::test_quantize_and_export[qwen3_moe]`, which calibrates with context parallelism. Runs used `nvcr.io/nvidia/nemo:26.10` on 2 GPUs. "New pin" means Megatron-Bridge `c9451327`, overlaid the way `.github/actions/megatron-from-source` does it, with the Transformers version it requires. | | CI pin (Megatron-Bridge `24b6adc`) | New pin (Megatron-Bridge `c9451327`) | |---|---|---| | With this fix | passes | passes | | Without this fix | passes | fails: `missing 1 required positional argument: 'dynamic_cp'` | - CI can't run the new pin yet (OMNIML-6686), so the revert check runs only on the new pin, locally. - On the CI pin I also ran `tests/gpu_megatron/torch/utils/plugins/test_utils_megatron.py`: 2 passed, 4 skipped. - An earlier draft passed both arguments whenever both existed. That broke the CI pin with `Cannot pass both is_hybrid_cp and dynamic_cp`, which is why this version prefers `dynamic_cp` alone. - No unit test: no test can fail without this fix on the CI pin. ### 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?: N/A (see Testing) - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ - Did you get Claude approval on this PR?: ❌ (requested) ### Additional Information OMNIML-6686: make ModelOpt's Megatron plugins work with the Megatron-Core shipped by Megatron-Bridge #7057 and later. This PR is split out of #3690, which is on hold until OMNIML-6686. 🤖 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 calibration with context parallelism on newer Megatron-Core versions. Calibration now works with the updated batch-setting requirements and remains compatible with versions using the deprecated setting. <!-- 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> |
||
|
|
4a9180b989 |
feat(speculative): context parallelism for offline DFlash training (#3597)
### What does this PR do? Type of change: new feature **Problem:** DFlash-family training accepts `training.cp_size > 1` but is not adapted to it, so the trainable sequence length is bounded by one GPU's memory. This is a first slice of #3344: context parallelism for the plain DFlash draft trained offline. **Fix:** Each CP rank holds only its slice of the target hidden states. Every draft layer all-gathers the context keys/values inside a checkpoint, so no layer keeps a full-length copy for backward; anchors are broadcast so the ranks draft the same blocks. DFlash uses this instead of torch's ring attention, which covers causal self-attention only. Everything else with `cp_size > 1` (online, streaming, DFlash2/DSpark/Domino/LiLiCorr, `torch.compile`, attention dropout) now raises an error. **Limit:** each rank still runs one layer's attention over the full context, so the saving over gradient checkpointing is modest (table below). Input ids, base final hidden states, draft blocks and the attention mask are also unsharded. ### Modules touched - `modelopt/torch/speculative`: the sharded attention and the model's CP checks live in the draft model. - `examples/speculative_decoding`: `main.py` enables it and the trainer shards the batch instead of entering torch's context-parallel mode. ### Usage ```bash ./launch_train.sh --config ../../modelopt_recipes/general/speculative_decoding/dflash.yaml \ model.model_name_or_path=<base> data.offline_data_path=<dumps> training.cp_size=2 ``` ### Testing torch 2.10.0, transformers 5.12.1, accelerate 1.16.0. GPU runs used the code at |
||
|
|
56e8d564db |
Deprecate export_mcore_gpt_to_hf in favor of Megatron-Bridge (#3662)
### What does this PR do? Type of change: Deprecation `export_mcore_gpt_to_hf` (ModelOpt's Megatron-Core → Hugging Face exporter) now emits a `DeprecationWarning`, and its removal is planned for 0.51.0 (OMNIML-5980). Where it supports the checkpoint, Megatron-Bridge's `AutoBridge.save_hf_pretrained_modelopt` replaces it, as `examples/megatron_bridge/export_quantized_megatron_to_hf.py` already uses it since #3651: it exports quantized checkpoints at any TP / EP / PP, for the bridges and quantization configs its packed export supports. That example also copies the source's non-model files. It checks only what Megatron-Bridge can export, and otherwise falls back to the old exporter, which then exports the checkpoint only within its own limits. It needs a Megatron-Bridge newer than the one in `nemo:26.10`; ModelOpt tests it at the commit `examples/megatron_bridge/README.md` names (ModelOpt's CI pin). This follows #3238, which deprecated the importer (`import_mcore_gpt_from_hf`) in 0.49.0. The docstring lists what Megatron-Bridge doesn't export yet, and the warning and the CHANGELOG entry point at it: - GGML / IQ formats; - EAGLE modules (`export_extra_modules=True`); - models whose Megatron-Bridge bridge post-processes the exported weights (e.g. Nemotron 3.5 Super VL), which Megatron-Bridge's quantized export can't handle yet; - KV-cache quantizers, with a Megatron-Bridge older than NVIDIA-NeMo/Megatron-Bridge#7057, including the commit the README names. The old exporter covers these only for the architectures in its rule tables (`plugins/mcore_*.py`) and at TP=1 (GGML / IQ formats also at PP=1). A quantized base model also needs a weight format it records in the quantization metadata; the separate EAGLE draft export doesn't. For example, it has no rules for Gemma3-VL, and writes no quantization metadata when only KV-cache quantizers are enabled. (A VLM checkpoint holding only the language model no longer needs it: since #3677 the example exports it through Megatron-Bridge.) The docstring also says that neither exporter handles these (the CHANGELOG entry links the README's prerequisites and points at the docstring): - Medusa heads. Megatron-Bridge won't add them, and `export_mcore_gpt_to_hf` fails for a Medusa model with `export_extra_modules=True`: its rule table has no Medusa entry. - Uniform INT8 weight-only checkpoints. Megatron-Bridge can't pack INT8 weight-only layers, and `export_mcore_gpt_to_hf` writes no quantization metadata for such a checkpoint. `examples/megatron_bridge/export_quantized_megatron_to_hf.py` exports through Megatron-Bridge and falls back to the old exporter only where Megatron-Bridge can't export (or with `--modelopt_megatron_exporter`), so it suppresses the warning around that fallback call. Its `--export_extra_modules` help now describes the flag as the EAGLE draft export (no Medusa or MTP). Megatron-Bridge's `examples/quantization/export.py` fallback and Megatron-LM's `examples/post_training/modelopt/export.py` still call `export_mcore_gpt_to_hf`, so they show the warning until they move off it. Part of OMNIML-5979. ### Modules touched - `modelopt/torch/export/unified_export_megatron.py`: `export_mcore_gpt_to_hf` (public API) emits the `DeprecationWarning`, and its docstring holds the migration guidance. - `examples/megatron_bridge/export_quantized_megatron_to_hf.py`: suppresses the warning around its ModelOpt-exporter fallback, and the `--export_extra_modules` help now describes the EAGLE draft export. - `CHANGELOG.rst`: 0.50.0 Deprecations entry. - Tests: `tests/unit/torch/export/test_get_quantization.py` asserts the warning; `tests/gpu_megatron/torch/export/test_quantized_mbridge_export.py` passes `source_path` to `save_hf_pretrained_modelopt`. ### Usage ```python import torch from megatron.bridge import AutoBridge from modelopt.torch.export import copy_non_model_files bridge = AutoBridge.from_hf_pretrained(hf_path) # model: the quantized Megatron-Core model chunks, at any TP / EP / PP. bridge.save_hf_pretrained_modelopt(model, export_dir, source_path=hf_path) # Megatron-Bridge saves only the config, tokenizer and remote code; carry over the source's # other non-model files (chat templates, assets) as export_mcore_gpt_to_hf does. if torch.distributed.get_rank() == 0: copy_non_model_files(hf_path, export_dir) ``` Megatron-Bridge writes the model as it is in memory, so `model` must hold the whole loaded model. For a VLM checkpoint that holds only the language model, load the HF weights first (`bridge.load_hf_weights(model, hf_path)`) and the checkpoint over them, as the example does; Megatron-Bridge doesn't copy the vision tower from `source_path`. ### Testing - `test_export_mcore_gpt_to_hf_passes_kv_cache_clamping_option` (`tests/unit/torch/export/test_get_quantization.py`) now expects the warning. At |
||
|
|
36601d09ca |
Report the unsupported sparsity pattern instead of raising AttributeError (#3687)
### What does this PR do?
Type of change: Bug fix
**Problem:** `mts.sparsify(model, "sparse_magnitude", {"pattern": "4:8
sparsity"})` (any unsupported pattern) raises `AttributeError:
'MagnitudeSearcher' object has no attribute 'config'` instead of the
intended "Unsupported pattern" assertion. On a searcher that already ran
a search, the message shows the previous search's pattern.
**Fix:** `BaseSparseSearcher.sanitize_search_config` built the assertion
message from `self.config`, which `BaseSearcher.search` only assigns
from the value this method returns. The message now uses the sanitized
config.
### Usage
```python
import modelopt.torch.sparsity as mts
mts.sparsify(model, "sparse_magnitude", {"pattern": "4:8 sparsity"})
# before: AttributeError: 'MagnitudeSearcher' object has no attribute 'config'
# after: AssertionError: Unsupported pattern 4:8 sparsity for sparsity
```
### Testing
- New `test_unsupported_pattern` in
`tests/unit/torch/sparsity/weight_sparsity/test_sparsify.py`: fails on
main with the `AttributeError`, passes with the change.
- `pytest tests/unit/torch/sparsity` (CPU, macOS, torch 2.15): 192
passed, 10 skipped (the skips need `transformers`).
- Not run: GPU tests.
### 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)?:
N/A
### Additional Information
Commit is signed off and signed (`-s -S`).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Tests**
* Added coverage confirming unsupported sparsity patterns produce a
clear error message.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Signed-off-by: sohailshk <122166523+sohailshk@users.noreply.github.com>
|
||
|
|
722c0f4ff6 |
Export a VLM's language-model-only checkpoint through Megatron-Bridge (#3677)
### What does this PR do? Type of change: New feature (example) **Problem:** `examples/megatron_bridge/export_quantized_megatron_to_hf.py` exports through Megatron-Bridge's `save_hf_pretrained_modelopt` since #3651, except for a VLM's language-model-only checkpoint (what QAD's `distill.py` saves). Megatron-Bridge writes the whole in-memory model, and that checkpoint holds no vision tower, so the example fell back to ModelOpt's Megatron exporter (`export_mcore_gpt_to_hf`), which copies the tower from the HF source. That exporter is being deprecated (OMNIML-5980), needs `--tp_size 1`, and has no rules for some VLMs (e.g. Gemma3-VL). **Fix:** - Before loading the Megatron checkpoint, the example resolves its iteration once and asks whether it holds only a VLM's language model. If so, it loads the source's HF weights (with the vision tower and projector) first, then that same iteration over the language model, and Megatron-Bridge exports the whole VLM at any TP / EP / PP. A newer iteration published in between can't be loaded instead. - The HF weight load is skipped when ModelOpt's exporter is selected up front (`--modelopt_megatron_exporter`, `--export_extra_modules`): it copies the vision tower from the HF source itself. - New `modelopt.torch.utils.plugins.mbridge.resolve_modelopt_megatron_checkpoint(model, megatron_path)`: the iteration a load takes and whether it holds only the language model (the check `load_modelopt_megatron_checkpoint` makes), agreed on every rank, reading checkpoint metadata only. - The language-model-only fallback reason is removed from the exporter routing. ### Usage Unchanged: ```bash torchrun --nproc_per_node 2 examples/megatron_bridge/export_quantized_megatron_to_hf.py \ --hf_model_name_or_path Qwen/Qwen3.5-35B-A3B \ --megatron_path /tmp/qad_output/checkpoints \ --tp_size 2 \ --export_unified_hf_path /tmp/Qwen3.5-35B-A3B-QAD-hf ``` ### Testing - `test_qad[qwen3_5_moe_vl]` now asserts that Megatron-Bridge wrote the language-model-only export (no `hf_quant_config.json`), next to its existing bit-exact check of the vision tower. Its QAD step needs Transformer Engine kernels the local GPU (sm_89) lacks, so CI runs it. - Local check of the same export path in `nvcr.io/nvidia/nemo:26.10` with Megatron-Bridge at ModelOpt's CI pin, 2 GPUs (`--pp_size 2`): a tiny Qwen3.5-VL MoE quantized to FP8 by `quantize.py`, saved language-model-only as `distill.py` does, then exported. - With this PR: Megatron-Bridge writes it, and the vision tower matches the HF source bit for bit. - On `main`: ModelOpt's exporter writes it (`hf_quant_config.json` present), so the updated assertion fails. - With the HF weight load removed: the vision-tower check fails. - `test_export_routing.py` (7 passed): - `test_the_checkpoint_iteration_is_resolved_once`: the checkpoint root's latest iteration changes from a full-VLM to a language-model-only one between the two steps; the inspected iteration must be the one loaded. Fails when the load takes the root again. - `test_a_language_model_only_checkpoint_loads_over_the_hf_weights_for_bridge_only`: the HF weights load first for Megatron-Bridge's export, and not with `--modelopt_megatron_exporter`. The forced case fails without the skip. ### 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?: ✅ Same checkpoints and CLI; the language-model-only VLM export now comes from Megatron-Bridge (quantization config inline in `config.json`, no `hf_quant_config.json`). - 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?: ✅ (`test_qad`'s VLM assertion) - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ The 0.50.0 entry from #3651. - Did you get Claude approval on this PR?: ❌ ### Additional Information Part of OMNIML-5980 (the language-model-only VLM case that only `export_mcore_gpt_to_hf` covered). Gemma3-VL wasn't run locally: its PTQ needs Transformer Engine fused-attention kernels the local GPU lacks. 🤖 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 * **New Features** * VLM exports using Megatron-Bridge can retain the vision tower when a language-model-only QAD checkpoint is applied over the source Hugging Face weights. * **Bug Fixes** * Corrected exporter selection so eligible VLM checkpoints use Megatron-Bridge, while configurations that require ModelOpt continue to use the existing fallback. * Updated VLM export expectations: `hf_quant_config.json` is no longer expected when no KV cache is quantized. <!-- 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> |
||
|
|
7024de11ad |
[3/7] Prevent unsafe offloaded export dispatch (#3678)
### What does this PR do? Type of change: Bug fix. Export can mutate quantizers or detach Accelerate hooks before rejecting an unsupported offload route. A model combining FSDP2 with rank-local Accelerate offload can also send ranks into different export writers and hang, including after a weight-access window closes. Check offload compatibility before conversion or dispatch, agree on hybrid FSDP2 refusal across ranks (counting hooks suspended by an open window), refuse whole-state export of offloaded models before conversion, and preserve ordinary layer-streaming export. The vLLM exporter opens resmoothing windows only for owners that need them and skips non-quantized containers. ### Modules touched - `torch/export`: owns writer dispatch and the conversions/hook removal that must follow compatibility checks. - `torch/quantization/utils/core_utils.py`: supplies one typed detector for enabled/suspended hooks; its upstream lifecycle assumption is pinned by a fast compatibility test. - `torch/quantization/plugins/accelerate.py`: delegates its hook predicate to that same detector, preventing export/materialization decision drift; writeback keeps its non-empty backing-map assertion, and the writeback/composite implementation is otherwise unchanged. ### Usage For an FSDP2 model with Accelerate CPU/disk hooks, reload without Accelerate offload before export; closing a weight-access window alone leaves those hooks installed. Ordinary non-FSDP offload continues through the public streaming exporter. ### Testing Fresh local and hosted validation at signed/DCO head `8b2a778eabfaef63bed776e4e341b7579bb6e69c` is pending. The results below qualify the previous head `f96a21e68d37deb50737cb43e7b6a584bb19fc24`, which still had the non-FSDP suspended-window refusal and its Diffusers/converter variants; this head removes that refusal and those cases. There, all 231 CPU cases passed with optional Diffusers installed (93.83 s), including converter-before-mutation checks and two native-hook lifecycle compatibility cases (0.06 s maximum call). All 57 export/offload validation cases passed on four GB300 GPUs (Slurm 2522927, 25.15 s), including eight HF/vLLM refusal/retry variants across actual FSDP wrapping and recorded-plan-only dispatch. The preceding guard reproduces mismatched broadcast entry for the recorded-plan-only case (bounded Slurm 2522669, 22.25 s). Export and the native plugin share hook discovery. Full Megatron/example lanes have not been rerun locally for this extracted prerequisite. Rebased onto `main` at `f69ba34748fac6e1f40a992751f63accb3780448`. Fresh hosted checks and automated reviews are pending; earlier results qualify their stated revisions only. Human approval remains separate. ### Before your PR is "*Ready for review*" - Backward compatible: ordinary supported exports retained; unsafe routes refuse before mutation. - Copied source/new dependencies: none. - Necessary tests: existing offload, converter-order and distributed export tests extended; standalone read-window test does not depend on the subsequent writeback fix. - Changelog: N/A, unsupported/unreleased route protections. - Claude review: requested; pending. ### Additional Information Extracted from #3599 at the human reviewer's request. Merge this prerequisite before #3599, then #3591, #3592 and #3593. This PR does not change the Accelerate writeback implementation or composite dispatcher. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Exports now detect active and suspended CPU offload and reject unsupported configurations before creating output files or changing model parameters. * Fake-quant exports handle offloaded weights more reliably, including resmoothing multiple offloaded layers. * **Tests** * Added coverage for export behavior with distributed offload, hook detection, and model parameter preservation. <!-- end of auto-generated comment: release notes by coderabbit.ai --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Sepehr Sameni <ssameni@nvidia.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d5722cd651 |
Fix grouped per-channel amax and sparse SwiGLU masks at another TP size (#3663)
### What does this PR do? Type of change: Bug fix **Problem:** two Megatron checkpoints don't load at another tensor-parallel (TP) size: - **Grouped MoE experts with per-channel weight quantizers** (e.g. `INT8_DEFAULT_CFG`, `FP8_PER_CHANNEL_PER_TOKEN_CFG`). The restore rebuilds each expert's amax at the saved TP size, and `_QuantTEGroupedLinear.modelopt_post_restore` dry-runs the quantizer on the weight to find amax that no longer fit it. The per-channel kernels index amax by output channel without a size check. A smaller amax (TP 2→1) reads past its end, and for INT8 trips a CUDA device-side assert (`amax >= 0`), losing the CUDA context. A larger one (TP 1→2) passes the dry run, and the weight load then fails with a global shape mismatch. - **A sparse gated (SwiGLU) MLP's `linear_fc1` weight mask** loads on the wrong rows, with no error. `_SparseMegatronMLP._modelopt_state_keys = [r"\._weight_mask$"]` was meant to give the mask Megatron's SwiGLU sharding, but `_is_swiglu_state` matches patterns from the start of the full key, so it never applies. This is the bug #3505 fixed for quantizer state. **Fix:** - **Grouped experts:** in Megatron's sharded extra-state restore (ModelOpt's and Megatron-LM's loaders both go through `set_extra_state`), before the dry run, each per-channel amax's channel dims (the buffer's own layout, as the kernels broadcast it) are compared with the weight's in Python. A mismatched amax takes the weight's channel count, from the weight's shape only (the weights may not be loaded yet), and the weight load then fills in the saved values. Saves already shard per-channel amax along the expert-TP rows, so nothing changes there. This runs on any device (CPU or meta targets too); only the existing dry run needs CUDA. An ordinary restore (e.g. `mto.restore()`) loads the buffers as saved, so it keeps their shapes. A gated (SwiGLU) expert `linear_fc1` is refused at another expert TP size by ModelOpt's restore into an unquantized model: Megatron shards its weight by gate and up rows but its amax by plain rows, so they would load on different rows. A load into an already quantized model (e.g. `restore_sharded_modelopt_state` into a converted target, or Megatron-Bridge's own loader) isn't checked and still misorders them, as on `main` (tracked in OMNIML-6311): load gated experts' per-channel state at the expert TP size it was saved at. Non-gated experts (e.g. Nemotron-H's squared ReLU) now load. - **Sparsity:** a gated `linear_fc1`'s mask now goes through Megatron's SwiGLU factory (gate and up rows under their own keys, correct at any TP size). The sparsity mode's metadata records that layout. A checkpoint saved before has no record, so ModelOpt's restore into a model that isn't sparsified yet plans the mask under its old single key: it loads as before, at the TP size it was saved at. Sparse Megatron checkpoints are rarely used, so backward compatibility stops there by design: a native load, or a load into an already sparsified model, of a pre-fix sparse checkpoint fails with a missing key, and one restored at another TP size still loads its masks on the wrong rows, as before (both stated in the CHANGELOG). A later mode's replay (e.g. quantization on top of sparsity) keeps the restored choice. A model restored from a pre-fix checkpoint also saves its masks in the old layout again (the record stays absent), so a re-save isn't migrated: it too loads right only at its saved TP size. A pre-fix checkpoint without ModelOpt state (weights only) has no fresh-restore route: load it with an earlier ModelOpt version. **Why a record in the sparsity mode's metadata, not the checkpoint-layout read/forget hooks or the checkpoint's tensor metadata:** the mode's metadata is what every restore into an unconverted model already replays before any key is planned, so it needs no new per-module state or checkpoint access. The layout hooks read each module's ModelOpt extra state, which sparse layers don't have, and pick a quantizer state's layout and saved sizes; covering masks would add a per-module record and a legacy factory for the old layout (what #3505 needed for quantizer state). Discovering the keys from the checkpoint's tensor metadata would need the checkpoint path wherever a module plans its keys, which a native load doesn't give it. Those buy compatibility for converted targets and native loads only, which isn't kept here. ### Modules touched - `modelopt/torch/quantization/plugins/transformer_engine.py`: the grouped experts' restore (`_QuantTEGroupedLinear.modelopt_post_restore`), where the per-channel amax is checked and resized. - `modelopt/torch/quantization/plugins/megatron.py`: the refusal for gated experts, which needs Megatron's config. - `modelopt/torch/sparsity/weight_sparsity/`: the mask's SwiGLU routing (`plugins/megatron.py`) and its layout record (`mode.py`). ### Testing - `test_te_grouped_sharded_state_dict_reshard` gets an INT8 per-channel TP 2→1 and an FP8 per-channel TP 1→2 case. Per-channel amax now holds a distinct value per output channel (exact in BF16), so the test also checks the rows land in order. The target's expert weights are NaN until the weight load, as in Megatron-Bridge's restore. New `test_te_grouped_gated_per_channel_reshard_rejected` checks the refusal for gated experts, and `test_grouped_post_restore_resizes_per_channel_amax_off_cuda` the resize on a CPU module. - New `test_swiglu_weight_mask_tp_reshard` (`tests/gpu_megatron/torch/sparsity/weight_sparsity/plugins/test_megatron_sparsity.py`): a gated MLP's magnitude-sparsity masks saved at TP=2 load at TP=1 in Megatron's row order, and a checkpoint saved as before (no record), sparsified then quantized, still loads through a fresh restore that replays both modes. That case runs at TP=1: with sparsity and quantization stacked, the mask is saved without its TP sharding at TP > 1, as on `main` (tracked in OMNIML-6311). - Each new case fails with its fix reverted: INT8 with the device-side assert, FP8 with the shape mismatch, both on NaN weights when the resized amax is calibrated instead, the off-CUDA case with the resize after the CUDA check, the gated case without the refusal, the stacked legacy mask case with a missing key when quantization's conversion resets the layout, a same-topology `mto.restore()` of a per-channel quantizer that is disabled, has quantization off or uses `use_constant_amax`, an active FP8 per-channel quantizer whose configured axis no longer describes its amax, or an oversized INT8 amax (`test_grouped_restore_keeps_disabled_quantizer_amax`) with a size mismatch, sparsifying again after a legacy model's final export (`test_resparsify_after_legacy_export`) in the old layout, the SwiGLU mask case on wrong rows, and the legacy mask case with a missing key once the record is dropped. - Ran in `nvcr.io/nvidia/nemo:26.10` on 2 GPUs: `test_te_grouped_sharded_state_dict_reshard` (all 12 cases), the gated refusal, `test_transformer_engine.py` and `test_megatron_sparsity.py`. CI runs the full suites. ### 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?: ⚠️ Quantized checkpoints are saved as before. Sparse checkpoints of gated MLPs now save the mask in Megatron's SwiGLU layout. Ones saved by earlier versions load only through `restore_sharded_modelopt_state` into an unsparsified model (see above). - 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)?: ✅ 0.50.0 Bug Fixes. - Did you get Claude approval on this PR?: ❌ ### Additional Information Part of the OMNIML-6311 cleanup. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
11e2968995 |
Stop recompiling Triton attention for every skip-softmax threshold (#3685)
### What does this PR do? Type of change: Bug fix **Problem:** Calibrated skip-softmax thresholds are `scale_factor / seq_len`, so almost every call passes a new value: every decode step and every new prefill length. The Triton attention kernels took the threshold as `tl.constexpr`, so every new value compiled a new kernel. QA measured vLLM calibration refinement about 10× slower on 0.49.0rc0 and rc1 (31 min instead of 3 min per pass, 64 prompts, 4× RTX 6000 Ada). The same recompiles hit vLLM serving, HF `generate` and the skip-softmax backward kernels. **Fix:** The threshold is now a runtime float argument, as `p_qdq_scale` already is, in the forward kernel, both backward kernels and `_skip_softmax_decision`. Outputs and gradients are bit-identical to before. ### Testing - Repro on an RTX A6000: 63 decode steps, KV length growing by one per step, threshold = 40 / L. | | `main` | This PR | |---|---|---| | Serving launch | 63 new kernels, 470 ms per call | 0 new kernels, 0.7 ms per call | | Sparsity-counter launch (calibration) | 63 new kernels, 1.7 s per call | 0 new kernels, 0.8 ms per call | | Forward + backward, 5 thresholds | +4 forward, +5 per backward kernel | +1 per backward kernel (first call only) | Forward outputs and gradients are bit-equal to `main`. - Kernel time at a fixed threshold, after compilation: decode is unchanged (86 µs at 4K, 320 µs at 16K). Prefill is about 1% slower: 2.01 vs 2.00 ms at 4K and 30.4 vs 30.1 ms at 16K. - New test `TestSkipSoftmax::test_new_threshold_reuses_compiled_kernels` fails on `main` (15 compiled kernels vs 5) and passes here. - `tests/gpu/torch/kernels/sparsity/attention` and `tests/gpu/torch/kernels/common/attention` (NeMo 26.10 container, Triton 3.8): 125 passed, 21 skipped for hardware. `tests/unit/torch/kernels` and `tests/unit/torch/sparsity/attention_sparsity`: 262 passed; 3 RULER dataset tests fail only because the container lacks `wonderwords`. - Not run: vLLM end-to-end calibration (`tests/gpu_vllm`), multi-GPU. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ (`SKIP_THRESHOLD_LOG2` was a private kernel parameter; the public `skip_softmax_threshold` argument is unchanged) - 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?: N/A - Did you get Claude approval on this PR?: ❌ (not run) ### Additional Information NVBug 7186199, targeted for 0.49.0. The patch applies cleanly to `release/0.49.0`. The QA runs also exit with code 1 because of the strict held-out sparsity check after calibration; that is a separate issue and this PR does not change it. 🤖 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 * **Improvements** * Changing the skip-softmax threshold no longer increases the number of compiled kernel variants. The existing threshold comparison and skip-softmax behavior remain unchanged. * **Tests** * Added coverage to verify compiled kernel counts remain stable when the threshold changes across forward, backward, and sparsity-measurement operations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Signed-off-by: Kai Xu <kaix@nvidia.com> |
||
|
|
8552088a4d |
[OMNIML-6461] [4/7] Bind a distributed AutoQuantize search's checkpoints to their run (#3617)
### What does this PR do?
Type of change: Bug fix
**Stack**, split at review (merge in order): [1/7] #3612 (merged) →
[2/7] #3634 (merged) → [3/7] #3636 (merged) → **[4/7] #3617** → [5/7]
#3250 → [6/7] #3613 → [7/7] #3614. This PR's review threads, and #3250's
before its first split, also cover [2/7] and [3/7], and the entry checks
of #3635, closed as unnecessary.
**Problem:** On several ranks, each rank of a distributed
`mtq.auto_quantize` weight search saves and restores a checkpoint file
of its own. A file did not record which rank, run, world size,
distribution plan or parallel groups wrote it. So a rank could resume
another rank's file, a file of another run, or one from another layout,
and calibrate on state that is not its own, unnoticed. A file failing to
load on one rank left the others waiting in the search's first
collective. A save failing on one rank, e.g. on a full disk, left the
ranks' files a save apart.
**Fix:** Each file now records:
- the rank that wrote it, the world size and the distribution plan;
- the parallel groups its searched modules span, and the mesh and
placements of each weight that tensor or expert parallelism shards as a
DTensor;
- an ID that every rank of one search shares.
A resume does three things:
- Each rank checks its own file against itself, in one collective with
the others. A file recording only part of its provenance (writer, world
size, layout, run ID), which no search writes, is refused.
- The ranks compare their progress and restored state. A file of another
rank, run, world size or plan, or at another point, is refused on every
rank before the model changes. One of another search setup or parallel
layout, or an older file the run cannot verify, is refused on every rank
once the search has converted the model, which it then hands back.
- Each rank restores its calibration in a `fail_together` block (#3634).
A refused one also hands the unconverted model back.
Every rank writes its file beside the old one, and all ranks rename
together, so a write failing on one rank leaves every rank's previous
save. Merging format shards keeps each rank's shards apart, and records
every shard's run; it refuses a shard that records only part of its
provenance. A refused file's scores still re-solve in one process with
`mtq.get_auto_quantize_config(search_state, constraints)`.
Why the resume check spans every rank, rather than each Hugging Face
route or each pipeline stage: the search's sums and reductions run over
each module's TP, EP and DP groups. A rank resuming at another point
than a rank it shares a group with would pair unrelated collectives with
it. The search records no pipeline-parallel groups to compare a stage's
ranks by. A check limited to runs with a recorded plan would leave
Megatron and data-parallel runs unchecked, though they hang the same
way. So a pipeline-parallel search starts over from a new path, as the
CHANGELOG's Backward Breaking entry says, and re-solving one stage's
file covers that stage's layers alone.
Why not the alternatives:
- **The KV-cache search's resume check.** It compares one fingerprint of
its state across ranks. A weight-search file holds each rank's own
calibration, e.g. its own experts', which other ranks cannot compare. So
each file records its writer, and the ranks compare a digest of
everything else.
- **`BaseSearcher`'s checkpoint lifecycle.** This extends it rather than
replacing it. `load_search_checkpoint` is `BaseSearcher`'s, run inside
the resume collective. `save_search_checkpoint` stages the write and
renames on several ranks, and keeps `BaseSearcher`'s save in one
process. [6/7] #3613 moves the KV-cache search onto the same staged
save.
- **PyTorch distributed checkpointing.** A file is a small state dict of
scores, costs and quantizer states. `get_auto_quantize_config` and
`merge_auto_quantize_checkpoints` read it in one process, and one
process can resume it. Distributed checkpointing's sharded format would
change those readers, for state that needs no resharding. The staged
write and the rename together publish a save only once every rank has
written, which is the part needed here.
### Usage
No API change. A distributed search's checkpoint is one file per rank,
as before, now bound to the run that wrote it:
```python
# Re-solve a distributed run's saved scores in one process, e.g. for another budget:
config = mtq.get_auto_quantize_config(search_state, {"effective_bits": 4.8})
```
### Testing
- New CPU tests on two ranks (gloo). Each is refused on every rank,
where one rank alone would otherwise leave the others in a collective:
-
`test_resume_from_another_point_on_one_rank_raises_on_every_rank[missing|older|other_setup|other_scoring|other_scores|other_run|other_run_no_ids|of_rank_0|of_rank_0_stripped|of_a_larger_run|under_another_plan|under_no_plan|under_other_groups|bad_payload|missing_tensors|legacy_other_calibration|legacy_other_metadata|truncated]`.
Rank 1's file is one of:
- deleted, rolled back, or truncated;
- rank 0's, also with its writer and world size removed, or from another
setup, scoring, run (also with both files' run IDs removed), larger run
or distribution plan, none included;
- written under other groups;
- readable but missing a quantizer's state or its tensors;
- calibrated by another run on other data, or holding another quantizer
state for the same tensors, with neither file recording its run.
-
`test_checkpoint_save_failing_on_one_rank_raises_on_every_rank[write|rename]`,
`test_checkpoint_save_writes_through_no_link` and
`test_checkpoint_save_keeps_the_checkpoint_mode`: a write or a rename
that fails on rank 1 alone, links planted at the staged name or at the
path, with another save's staged file left alone, also when a save draws
its name, and a re-save of an owner-only checkpoint.
- `test_search_on_ranks_of_their_own_groups`: ranks holding groups of
their own each resume from their own file.
-
`test_resume_files_that_record_no_writer[replicated|tensor_parallel|dtensor_parallel]`:
files written before they recorded their writer. Data-parallel replicas'
resume, with no forward, also under a plan; a tensor-parallel rank's are
refused, also a DTensor's whose groups no parallel state names.
- `test_resume_under_another_weight_placement_is_refused`: a
tensor-parallel DTensor weight sharded by rows resumes with no forward;
resumed sharded by columns over the same group, it is refused on every
rank and the model handed back.
- `test_fsdp2_resumes_with_no_weight_placements`: the weights FSDP2
alone shards record no placements, and the file resumes with no forward.
- `test_resume_with_the_same_nan_diagnostics_on_every_rank`, and a
format-shard merge case for a shard another rank wrote.
- One process:
`test_auto_quantize_refusal_hands_back_the_unconverted_model[after_restored_codes]`
refuses a payload restored after a GPTQ candidate's codes; the search
hands the unconverted model back.
`test_format_shards_merge_into_the_unsharded_search` refuses a shard
with its run ID removed, and merges shards written as 0.49 writes them
to no run ID.
- #3630's tests, on main since this PR's rebase:
`test_auto_quantize_resume_reprices_a_grouped_layer_saved_under_another_member`
resumes on a model that registers `k_proj` before `q_proj`, which the
layout, now recorded sorted by module name, matches.
`test_auto_quantize_resume_with_a_shorter_saved_ladder_on_one_rank` now
expects both ranks to refuse rank files whose saved ladders differ,
rather than resume them.
- CPU, transformers 5.18 and torch 2.14: the stack's CPU set at this
head, 999 passed. Pre-commit, mypy included, passes against main.
- GPU: CI's GPU job runs on this PR, on one GPU, now that it targets
main. On 2026-12-02, at
|
||
|
|
72da1d2b82 |
[1/4] AutoQuantize: count up_proj of non-gated fused experts in the cost (#3630)
### What does this PR do? Type of change: Bug fix Part of a 4-PR stack (merge in order): **[1/4] this PR (#3630)** → [2/4] static NVFP4 cost (#3631) → [3/4] local Hessian across ranks (#3632) → [4/4] calibrator memory (#3633). **Problem:** AutoQuantize's cost model sizes fused MoE expert containers (no single `weight`) by summing `gate_up_proj` and `down_proj`. Non-gated fused experts name their first projection `up_proj`, so half of every routed expert is left out of the cost and the effective-bits budget is undershot (the exported checkpoint is larger than the requested budget). **Fix:** Also count `up_proj`. Because saved search state holds costs from the old count: - Each candidate group records its cost-weighted `weight_size` with its costs. A resumed search recomputes the costs, the saved budget denominator and the size from the model's weights (saved calibration and scores are kept; groups are looked up by their saved name and formats matched by config, not display name) and solves with them. Costs are priced once per searched group in live order, so ranks issue the same collectives. The resume itself does not rewrite the checkpoint (it may be read-only, and its saved best recipe matches its saved costs), though `aumann_shapley` saves after it solves. To finalize a pre-fix checkpoint with corrected costs, rescore into a new checkpoint (format shards: rescore each, then merge). Counting the experts in full shifts the smallest feasible `effective_bits`, so a previously valid value may need raising. - A model-free re-solve (`get_auto_quantize_config(state, constraints)`, including the HF PTQ `finalize_algorithm` rerun) of a checkpoint without recorded sizes, i.e. saved before this fix, warns that its costs may count non-gated experts short, and proceeds. Format shards merge as before; the merge also compares sizes and costs across shards. - `examples/hf_ptq/README.md` describes how to refresh such a checkpoint, and `CHANGELOG.rst` lists the fix under Bug Fixes. ### Why a separate `weight_size` Checkpoints saved before this fix already carry `uncompressed_cost`, with the half-counted value, so only a new key can tell an old checkpoint from a fixed one offline. A versioned cost signature (as `_auto_quantize_shapley.py` versions its scoring) would also catch later per-format pricing changes such as #3631; that is left for when such a change lands outside this stack. `quantizer_attrs` could narrow the warning to checkpoints with non-gated fused experts, but the warning is advisory and does not block dense or gated-only checkpoints. ### Testing Ran on a GB300 node (4 GPUs) with the four stacked PRs applied to `main`: `tests/unit/torch/quantization/test_local_hessian.py`, `test_autoquant.py`, `tests/unit/torch/utils/test_distributed_calibration.py` and `tests/gpu/torch/quantization/test_local_hessian_gpu.py`: 180 passed, 1 skipped. With the library changes reverted, each new test fails. Not run: other GPU suites, multi-node. The existing fused-experts cost test is parametrized over `gate_up_proj` / `up_proj`. New test `test_auto_quantize_resume_recomputes_costs_saved_by_an_older_cost_model`: a checkpoint with stale (halved) costs and denominator and no recorded sizes warns on a model-free re-solve (a current one does not), merges as before, and when resumed from an extensionless single-file checkpoint with renamed custom formats solves with the fresh costs and denominator and its saved scores, leaving the checkpoint unchanged; it fails with the library change reverted. The two-shard merge test now also refuses shards whose costs or weight sizes differ. A Q/K/V regression resumes on a model that registers `k_proj` before `q_proj`, with only that group's saved costs stale, and checks the group is repriced by its saved name (it fails with the old lookup), and that resume calls `get_cost` no more than once per live choice plus once per saved group (it fails with per-row pricing). ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ (checkpoints saved before it still load; a model-free re-solve of one warns that its costs may be stale) - 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?: ❌ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: weimingc <17592131+meenchen@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d646b19fa7 |
Evaluating Models Efficiently During Optimization Experiments (#3270)
### What does this PR do? Engineers need efficient ways to compare checkpoints during optimization experiments alongside standardized evaluation before model release. Publish **Evaluating Models Efficiently During Optimization Experiments** as a technical announcement at `docs/source/announcements/evaluating_models_efficiently_during_optimization_experiments/index.rst`. Real Baseline/Candidate comparisons illustrate metrics, regression and reliability checks, and evaluation budgets. Move its plots, reproducibility notes, and CSV summaries alongside the article. Keep `docs/source/guides/evaluation/index.rst` as the permanent evaluation landing page, linking to: - The announcement for efficient experimentation. - LLM evaluation examples for benchmark setup and commands. - ModelOpt evaluation and results-comparison skills for standardized evaluation and acceptance checks before release. Add the homepage announcement card with matching author, date, and tags, and update the evaluation examples' documentation link. ### Testing - Focused Sphinx HTML build with warnings treated as errors. - Pre-commit checks on the changed files. - Reviewed rendered article, homepage card, and evaluation landing page; checked metadata and tag filtering. - Verified that moving the files preserved measurement tables, SVG plots, and CSV data. ### Review requirement Merge only after two human reviewers have approved the public announcement. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Documentation** * Added guidance for evaluating optimized models, including paired comparisons, confidence intervals, regression thresholds, reliability measures, and output efficiency. * Added reproducibility notes covering evaluation setup, statistical methods, response budgets, and limitations. * Linked evaluation guidance and related resources from the documentation and examples. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Daniel Korzekwa <dkorzekwa@nvidia.com> |
||
|
|
15a578904c |
Refuse AWQ / SmoothQuant pre_quant_scale in Megatron export, incl. weight-only INT4 AWQ (#3681)
### What does this PR do? Type of change: Bug fix **Problem:** `export_mcore_gpt_to_hf` rejected AWQ / SmoothQuant only when the layer's activations were quantized (the check sat inside `if input_scale is not None`). Weight-only INT4 AWQ (`mtq.INT4_AWQ_CFG`, W4A16) disables the input quantizer, so the check was skipped. But AWQ multiplied the weight by `1 / pre_quant_scale`, and a disabled input quantizer still applies `pre_quant_scale` in forward, so the exporter silently wrote the scaled weights without the scale: a wrong Hugging Face checkpoint. `examples/megatron_bridge/export_quantized_megatron_to_hf.py` falls back to this exporter for INT4 AWQ, so it reached this path. Megatron-Bridge's own quantized export (ModelOpt's functional weight export) had the same gap for FP8 formats (e.g. an FP8 config calibrated with AWQ or SmoothQuant): their format resolution never looks at `pre_quant_scale`, so it was dropped there too. **Fix:** Refuse any active `pre_quant_scale`, whether or not activations are quantized: - `GPTModelExporter.save_pretrained` raises `NotImplementedError` when any rank's base model holds one, and `save_pretrained_extra_modules` when the EAGLE / Medusa modules do (a draft-only export writes none of the base's weights). The check is agreed across ranks before any export collective, since pipeline stages hold different layers. - Direct `state_dict` / `layer_state_dicts` / `extra_state_dict` access runs the same check, over the modules that build writes (the lazy base build leaves out the live MTP), before it caches anything, so a retry refuses again instead of returning partial state; when the build gathers grouped experts at EP>1, it first agrees over the EP group. Other layouts (e.g. SequentialMLP experts) stay rank-local. An exporter's rule book is fixed by `export_extra_modules`, so reading the other export (`extra_state_dict` on a base exporter or the reverse) now raises `ValueError` before touching the caches, rather than returning the other build's cached tensors. - The error points to quantizing and exporting the Hugging Face model instead (`examples/hf_ptq/hf_ptq.py` / `export_hf_checkpoint`). - The vLLM fake-quant exporter (`VllmFqGPTModelExporter`) opts out: it folds weight-side scales into the QDQ weights, and `check_mcore_vllm_fakequant_quantizers` already refuses activation-side ones. - The functional export (`get_quantized_weight_export_spec` / `capture_quantized_weight_export_state`) raises its unsupported-format error, so the Megatron-Bridge example falls back to ModelOpt's exporter and stops there with the clear error. FP4 formats already resolved to `nvfp4_awq` here and were refused. A scale disabled by `disable_pre_quant_scale_and_resmooth` (which restores the weights but keeps the buffer by default) is fine for other formats, but on FP4 layers format resolution still reads it as `nvfp4_awq`: the Megatron exporter refuses those (it would write no quantization config), as it does GGML layers with one (which GGML export refuses), and the functional export already refused that format. SmoothQuant now raises `NotImplementedError` rather than `ValueError`, like the exporter's other unsupported-export errors. ### Modules touched - `modelopt/torch/export` (Megatron exporter, its vLLM fake-quant subclass, functional weight export): the bug is in two export paths that the Megatron-Bridge example reaches; the subclass must opt out because it calls the base `save_pretrained`. ### Usage Unchanged. An AWQ / SmoothQuant Megatron model now fails at export with: ``` NotImplementedError: AWQ / SmoothQuant (pre_quant_scale) export from Megatron is not supported. Quantize and export the Hugging Face model instead (examples/hf_ptq/hf_ptq.py or modelopt.torch.export.export_hf_checkpoint). ``` ### Testing All in `nvcr.io/nvidia/nemo:26.10`: - New `test_export_rejects_weight_only_awq` (`tests/gpu_megatron/torch/export/test_unified_export_megatron.py`, 1 GPU): tiny GPT quantized with `INT4_AWQ_CFG`; `export_mcore_gpt_to_hf` refuses it; direct `state_dict` / `layer_state_dicts` access refuses twice in a row on one exporter; with a BF16 EAGLE draft added, the draft check passes and the base check refuses (called directly: the EAGLE extra-module export itself currently fails earlier, `EagleModule` has no `fc`). Fails with the fix reverted (`DID NOT RAISE`: the export writes the checkpoint), with whole-model scanning (draft case), and with the earlier rank-local per-module check (the retry returned partial state). - New `test_retained_pre_quant_scale_refused_where_format_reads_it[fp4|fp8|ggml]`: a resmoothed (disabled) scale is refused on FP4 and GGML layers, without raising inside the check, and allowed on FP8. - New `test_direct_state_ignores_mtp_only_pre_quant_scale` (1 GPU): an MTP-only scale doesn't block the lazy base build, while `export_mcore_gpt_to_hf` refuses it; that base exporter also refuses `extra_state_dict` and keeps its cache. `test_export_rejects_weight_only_awq` also checks that an EAGLE (`export_extra_modules=True`) exporter refuses `state_dict`. - New `test_direct_state_ep2_one_rank_draft_read_keeps_base_cache` (2 GPUs, EP=2, TE grouped experts): after both ranks build the base, a rank-0-only draft read is refused, and the next base read on both ranks returns the cache without any EP collective. - These, and the GGML case above, fail on the previous heads' source ( |
||
|
|
189a0b9ef0 |
[NVBug 7128507] Plan an MTP checkpoint whole when the distribution is left to decide (#3519)
### What does this PR do?
Type of change: Bug fix
**Problem:** Multi-rank `hf_ptq.py` on Nemotron-3-Super-120B (a
Nemotron-H MoE checkpoint with an MTP head) fails on every rank with
`NotImplementedError: The expert-parallel load cannot build the MTP
head` ([NVBug 7128507](https://nvbugspro.nvidia.com/bug/7128507)). With
no plan and neither `MODELOPT_EP_DEGREE` nor `MODELOPT_FSDP_SIZE` set,
`resolve_distribution_plan` chooses the expert-parallel layout (or, by
GPU memory, FSDP2), but neither sharded load builds the MTP head, so
`_sharded_load_kwargs` refuses the plan the decision just made. The
decision already avoids other layouts the load would refuse; this check
was missing since the expert-parallel routing in #2780.
**Fix:** When the layout is left to decide (`ep_size` auto/1, `dense`
auto/replicate) and the checkpoint carries an MTP head,
`_decide_distribution` plans the whole-model load, which builds and
calibrates the head, with a rank-0 warning saying why. The check uses
the loading hook `load_pretrained`'s `model_type` selects (else the
config's type), the one that decides whether the load builds the head;
for a config handed in with a blank type, `load_pretrained` reads the
checkpoint's type, as it already did for the hook, before planning, in a
step every rank takes once the fetch has succeeded everywhere, while the
standalone resolver reads nothing more of the checkpoint. A layout a
knob or argument asks for is kept, and the load still refuses it with
its existing message naming the way out. A replication both knobs ask
for (`ep_size=1`, `dense="replicate"`) now returns before the meta
build, for any model: on `main` the build it went through left rank 0's
whole load of Nemotron-3-Super with its routed experts uninitialized.
### Usage
```bash
# Unchanged command; now loads whole on every rank instead of failing. Each rank stages a whole
# copy in host RAM while loading (~225 GiB here), so size ranks per node to the node's memory:
# tested as 8 nodes x 2 ranks on 920 GiB GB300 nodes.
torchrun --nnodes 8 --nproc_per_node 2 ... examples/hf_ptq/hf_ptq.py \
--pyt_ckpt_path nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 --qformat fp8 --export_path <out>
```
### Testing
- New `test_a_checkpoint_carrying_an_mtp_head_is_decided_whole` (5
cases: no MTP, auto, too big for one GPU, both knobs replicate, EP
asked). The 2 MTP auto cases fail on `main` and pass with the fix. The
`mtp` case of
`test_a_measured_layout_names_the_way_back_when_it_refuses_a_checkpoint`
asserted the old refusal and is now covered by the new test.
- New
`test_the_mtp_decision_follows_the_loading_hook_load_pretrained_runs`
(review): `load_pretrained`'s `model_type` override decides the MTP
fallback in both directions, and an explicit `model_type=""` selects no
hook (3 cases); each fails without its fix.
- New
`test_a_config_without_a_type_plans_by_the_checkpoints_loading_hook`
(review): `load_pretrained` with a blank-typed config plans by the
checkpoint's hook and loads the MTP head whole; fails without the fix
with the FSDP2 refusal. New
`test_a_loading_hook_only_one_rank_reads_leaves_the_ranks_in_step`
(review): over two bounded gloo ranks, a rank that reads the blank
type's hook and one handed `model_type` stay in step; times out without
the fix. `test_a_rank_that_cannot_see_the_checkpoint_fails_every_rank`
gains a blank-type decided load row and a hidden-subfolder row (review):
no rank reads the checkpoint config past a peer's failed fetch, or a
subfolder a peer cannot see; each fails without the fix. New
`test_a_layout_the_knobs_ask_to_shard_still_refuses_an_mtp_checkpoint`
(review): EP or FSDP2 asked by the knobs, with no plan handed in, is
still refused. New
`test_a_config_without_a_type_is_planned_without_the_checkpoints_config`
(review): a blank-typed config is planned from itself, without reading
the checkpoint's config, on one rank, on two ranks asking for
replication, and on two ranks left on auto (FSDP2 by GPU memory); the
auto row fails on the previous head, which read it. New
`test_ranks_differing_on_the_mtp_head_are_refused_together` (review):
over two bounded gloo ranks, an MTP-bearing Nemotron-H checkpoint that
one rank's hook would build the head for and the other's would not is
refused on every rank before either loads a weight (fails without the
fix), while two hook-free model types still load (fails if the ranks
compare type strings). The whole-load MTP rows of
`test_a_checkpoint_carrying_an_mtp_head_is_decided_whole` fail if
anything builds the model first (review).
- `tests/unit/torch/utils/test_model_load_utils.py`,
`tests/unit/torch/models` and
`tests/examples/hf_ptq/test_hf_ptq_args.py`: 959 passed, 15 skipped (on
main at
|