Repository navigation
Keep calibrated skip-softmax thresholds across save/restore - #3028
Conversation
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Save and restore sparse-attention state modelopt/torch/sparsity/attention_sparsity/sparse_attention.py, modelopt/torch/sparsity/attention_sparsity/conversion.py, tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py |
get_modelopt_state saves the method name, a copy of the method configuration, enabled status, and non-None calibration values. set_from_modelopt_state restores enabled status when present and copies saved calibration values onto the existing method instance. Conversion metadata uses these methods. Tests cover calibration round-trips, disabled modules, and legacy state without enabled metadata. |
Priority:
Estimated code review effort: 2 (Simple) | ~10 minutes
Change: Bug fix
Merge Risk: 
Minimal · up to 2f877
-
The configuration concern does not block merging: the previous restore did not apply that saved configuration either. No actionable merge-blocking issue remains after normal checks.
Pre-merge checks: 
6
-
Full details: Title check
-
Explanation
The title "Keep calibrated skip-softmax thresholds across save/restore" matches the main change. The PR saves calibration_params and target_sparse_ratio in sparse-attention mode metadata and restores them onto the method instance, so restored modules keep their calibrated thresholds. The title is specific, short, and free of file lists or vague terms. Its one gap is that it does not mention the new get_modelopt_state and set_from_modelopt_state methods, but the title does not need to cover every detail.
Full details: Security Anti-Patterns
-
Explanation
PASS. The pull request changes only sparse-attention state handling and tests. Added code uses
copy.deepcopy, metadata access, and state setters. It adds notorch.load(..., weights_only=False),numpy.load(..., allow_pickle=True), hardcodedtrust_remote_code=True,eval,exec, or# nosec. It changes nopyproject.tomlor requirements file, so it adds no dependency licensing issue.
-
Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Comment @coderabbitai help to get the list of available commands.
cac4e89 to
e15c56a
Compare
|
kevalmorabia97
left a comment
There was a problem hiding this comment.
LGTM. The root cause is right (the method instance's calibration_params / target_sparse_ratio aren't in the state dict and are rebuilt as None on restore). Restoring them after module._setup() is the correct order, and both the flash and triton skip-softmax methods read these same two attributes. Older checkpoints restore unchanged. I ran test_restore_keeps_calibration_params: it passes on this branch and fails with conversion.py reverted.
Minor, non-blocking:
- The GPU
triton_skip_softmaxTinyLlama case from the NVBug was not re-run; the code path is the same, so I'm fine with that. - The unpersisted per-module enable flag (
disable_sparse_attention()aftersparsify) deserves a follow-up issue. - The same calibration dicts are stored once per module; they are small, so no change needed.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3028 +/- ##
==========================================
+ Coverage 77.49% 79.16% +1.66%
==========================================
Files 661 661
Lines 74949 74954 +5
==========================================
+ Hits 58085 59334 +1249
+ Misses 16864 15620 -1244
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…estore Signed-off-by: Kai Xu <[email protected]>
e15c56a to
2f8772d
Compare
#2928 #2885 #2908 #2929 #2950 #2972 #2877 #2951 #2816 #3005 #3012 #2971 #3015 #3006 #3026 #2988 #3028 #1860 #3030 #2612 #3033 #2653 #2599 #2655 #2618 #2868 #3032 #3027 #2869 #2984 #2975 #2345 #3020 #2997 (#3072) ## Cherry-picked PRs - #2817 - #2671 - #2892 - #2876 - #2910 - #2911 - #2919 - #2904 - #2937 - #2928 - #2885 - #2908 - #2929 - #2950 - #2972 - #2877 - #2951 - #2816 - #3005 - #3012 - #2971 - #3015 - #3006 - #3026 - #2988 - #3028 - #1860 - #3030 - #2612 - #3033 - #2653 - #2599 - #2655 - #2618 - #2868 - #3032 - #3027 - #2869 - #2984 - #2975 - #2345 - #3020 - #2997 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Diffusion exports now offer more control over attention-quantizer metadata and preserve sparse-attention settings in a format compatible with downstream tooling. * Model loading better handles select bundled model implementations, and Docker guidance now covers writable CUDA-extension cache locations. * **Bug Fixes** * Improved reliability for model export and checkpoint saving, quantization across devices, ONNX processing, and calibration. * Temporary TensorRT and autotuning artifacts now use private directories by default. * **Documentation** * Updated installation guidance, compatibility notes, and links; corrected typos across guides and examples. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Chad Voegele <[email protected]> Signed-off-by: Rohan Joshi <[email protected]> Signed-off-by: LinCanNerd <[email protected]> Signed-off-by: Keval Morabia <[email protected]> Signed-off-by: weimingc <[email protected]> Signed-off-by: Noey Yang <[email protected]> Signed-off-by: Kai Xu <[email protected]> Signed-off-by: Zhehao Hu <[email protected]> Signed-off-by: noeyy-mino <[email protected]> Signed-off-by: joe-nv <[email protected]> Signed-off-by: yingguo-trt <[email protected]> Signed-off-by: Shengliang Xu <[email protected]> Signed-off-by: Chenjie Luo <[email protected]> Signed-off-by: anmaurya001 <[email protected]> Signed-off-by: Connor Baker <[email protected]> Signed-off-by: wiederse <[email protected]> Signed-off-by: Vu Dinh <[email protected]> Signed-off-by: Pratik Gandhi <[email protected]> Signed-off-by: Michael Rusu <[email protected]> Signed-off-by: Michael-Rusu <[email protected]> Signed-off-by: namgyu-youn <[email protected]> Signed-off-by: Sylvester Kaczmarek <[email protected]> Signed-off-by: Javier de Jesus <[email protected]> Signed-off-by: javierdejesusda <[email protected]> Signed-off-by: Zhiyu Cheng <[email protected]> Signed-off-by: Juhi Mittal <[email protected]> Signed-off-by: Dmitry Rantovov <[email protected]> Signed-off-by: h-guo18 <[email protected]> Co-authored-by: Chad Voegele <[email protected]> Co-authored-by: LinCanNerd <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: Keval Morabia <[email protected]> Co-authored-by: Wei-Ming Chen <[email protected]> Co-authored-by: noeyy-mino <[email protected]> Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: kaix-nv <[email protected]> Co-authored-by: Zhehao Hu <[email protected]> Co-authored-by: joe <[email protected]> Co-authored-by: yingguo-trt <[email protected]> Co-authored-by: Shengliang Xu <[email protected]> Co-authored-by: Chenjie Luo <[email protected]> Co-authored-by: anmaurya001 <[email protected]> Co-authored-by: Connor Baker <[email protected]> Co-authored-by: Jiao Mingyang <[email protected]> Co-authored-by: Vu Dinh <[email protected]> Co-authored-by: Pratik Gandhi <[email protected]> Co-authored-by: Michael R <[email protected]> Co-authored-by: Michael-Rusu <[email protected]> Co-authored-by: namgyu-youn <[email protected]> Co-authored-by: Sylvester Kaczmarek <[email protected]> Co-authored-by: Javier De Jesus <[email protected]> Co-authored-by: Zhiyu <[email protected]> Co-authored-by: Juhi Mittal <[email protected]> Co-authored-by: Dmitry Rantovov <[email protected]> Co-authored-by: h-guo18 <[email protected]>
### What does this PR do? Type of change: new feature Weight sparsity and attention sparsity had two entry points with conflicting signatures: `mts.sparsify(model, mode, config)`, where `config` holds search options, and `mtsa.sparsify(model, config, forward_loop)`, where `config` is the sparse attention config. This PR makes `mts.sparsify` the single entry point for both and deprecates `mtsa.sparsify`. Existing weight-sparsity calls are unchanged. - **One API.** A sparse attention config (e.g. `mts.SKIP_SOFTMAX_CALIB`) can be passed in place of the mode, or as the `"sparse_attention"` mode next to weight-sparsity modes. Each mode is applied and then searched (weight masks) or calibrated (attention thresholds) by its mode's searcher, one at a time. Search options go to the searchers that accept them, and a new `forward_loop` keyword is shorthand for `config["forward_loop"]`. Before the model is modified, `mts.sparsify` validates the modes and their order against the model's existing modes, each mode config including every attention pattern's attributes and calibration settings, the option keys, a decode calibration target given with a loop, and a one-shot `data_loader` shared by several modes. - **Attention calibration as a searcher.** A new `SparseAttentionSearcher` runs the existing threshold calibration, so attention calibration can also take a `data_loader`. - **Mode chaining and export.** - `sparse_attention` may now follow `sparse_magnitude` / `sparsegpt`. Before, that order failed at the chaining check. - `sparse_attention` no longer declares the export mode `export_sparse_attention`, which was never registered. Because of it, `mts.export` failed on any model with sparse attention applied after weight sparsity. - `mts.export` folds weight masks as before and keeps sparse attention modules, which `export_hf_checkpoint` reads to write `sparse_attention_config`. A model with only sparse attention left is returned unchanged. - **Calibration results persist.** Saving refreshes only the last mode's metadata, and attention calibration results live in that metadata since #3028. Two consequences: - `mts.sparsify` searches each mode before applying the next. - `calibrate()` now writes its results into the `sparse_attention` metadata of each converted model it is given, including models inside a wrapper or a container. Before, results were lost when another mode, e.g. `quantize`, was applied after sparse attention. - **Training modes.** `BaseSearcher.search` ends with `model.train(is_training)`, which gives every module the model's mode. `mts.sparsify` gives each module back its own mode afterwards, with the helper `mtq.calibrate` already uses, moved from `quantization/model_quant.py` to `modelopt.torch.utils`. The deprecated `mtsa.sparsify` now calls `mts.sparsify`. - **Registration.** `modelopt.torch.sparsity` imports `attention_sparsity` directly. Before, the `sparse_attention` mode was registered only through an indirect import chain via `modelopt.torch.export`, which needs `transformers`. - **Smaller fixes and migration.** - Removed `{"sparsity"}` from the `next_prohibited_modes` of `sparse_attention`. That set compares mode names, and `"sparsity"` is a registry name, so it never matched. - Examples, docs and tests now use `mts.sparsify`. The `:meth:` links to `modelopt.torch.sparsity.sparsification.sparsify` in the sparsity guide now resolve. Unchanged limitation, now documented: a `forward_loop` or `data_loader` serves only prefill calibration. A config with a decode target, such as `SKIP_SOFTMAX_CALIB`, still needs the generated RULER data, so it raises if any loop is given, now before the model is converted. In particular it can't share one call with SparseGPT; use two calls. Not changed: `quantize.next_prohibited_modes` also lists `"sparsity"`. Making it effective would newly forbid quantize → weight sparsity, so it is left for a separate decision. The `"sparse_gpt"` typo in the `next_modes` of AutoNAS / FastNAS / Minitron is also left for a separate PR. ### Usage ```python import modelopt.torch.sparsity as mts # Weight sparsity (unchanged) model = mts.sparsify(model, "sparsegpt", config={"data_loader": data_loader, "collect_func": lambda x: x}) # Attention sparsity (was mtsa.sparsify(model, config, forward_loop=forward_loop)) model = mts.sparsify(model, mts.SKIP_SOFTMAX_CALIB) # calibrates on generated RULER data model = mts.sparsify(transformer, diffusion_cfg, forward_loop=forward_loop) # prefill-only calibration # Both in one call; "device" goes to SparseGPT only model = mts.sparsify( model, [("sparsegpt", {}), ("sparse_attention", mts.SKIP_SOFTMAX_DEFAULT)], config={"data_loader": data_loader, "collect_func": lambda x: x, "device": "cuda"}, ) mts.export(model) # folds the weight masks, keeps sparse attention for export_hf_checkpoint ``` ### Testing All of the following ran on CPU (torch 2.8, transformers 4.57): - **Unit tests:** `tests/unit/torch/sparsity` and `tests/unit/torch/opt` pass. `tests/unit/torch/opt/plugins/test_diffusers_save_load.py` was excluded because its diffusers import fails in my environment, on unmodified `main` too. Full `tests/unit`: 4992 passed; the 173 failures and 25 errors are the same 198 test IDs that fail on unmodified `main` in this environment (ONNX, diffusers, and transformers-version imports). - **New unit tests:** - weight + attention sparsity in one call, in both orders, with option routing, save/restore and export; - `calibrate()` after a later mode keeps its results through save/restore; - invalid input fails before the model is converted; - the deprecated `mtsa.sparsify` warns and gives the same modelopt state as `mts.sparsify`; - the `calibrate()` persistence test also runs on a container of two separately converted models; - invalid input also covers an incompatible mode order, invalid attention attributes, invalid calibration settings in a mode after `sparse_magnitude`, a decode target with a loop, and a one-shot `data_loader` with two modes; each case also checks that the weights are unchanged; - both `mts.sparsify` and `mtsa.sparsify` keep a submodule in eval mode inside a model in training mode. With the corresponding source changes reverted, the weight-first chain test, the `calibrate()` persistence tests, the training-mode tests and every new invalid-input case fail. - **Follow-up commit (`31a1393eed`):** `tests/unit/torch/sparsity`: 343 passed. `tests/unit/torch/quantization/test_quantize_cpu.py`, `tests/unit/torch/opt` and `tests/unit/torch/utils`: 457 passed, excluding `test_dataset_utils.py` (read-only Hugging Face cache in my sandbox) and 4 modules that fail to import `transformers.conversion_mapping` in my environment. - **Calibration parity:** on Qwen2.5-0.5B (6 layers, fp32, eager), prefill calibration at target 0.5 gave `a = 13.789706561886458`, `b = 10.903199376937502` through all three paths: the old `mtsa.sparsify(forward_loop=...)`, the new searcher with `forward_loop`, and the new searcher with `data_loader`. Save/restore keeps them. This was a local script, not checked in. - **Not run locally (no GPU here):** `tests/gpu`, `tests/gpu_vllm` and `tests/examples`. Their call sites were renamed `mtsa.sparsify` / `sparse_attn.sparsify` → `mts.sparsify` with unchanged arguments. The edited modules collect, except the wan2.2 diffusers test, which hits the same diffusers import failure here as on `main`. Decode-phase and RULER auto-calibration, the Triton backend and diffusers models are therefore covered only by CI. ### Before your PR is "*Ready for review*" - Is this change backward compatible?: ✅ `mtsa.sparsify` keeps working with a `DeprecationWarning`. `mts.sparsify` / `mts.export` behave as before for weight sparsity, except that invalid options now raise `ValueError` before the model is converted instead of an `AssertionError` from the searcher, and an incompatible mode order raises its `AssertionError` before the first mode is applied. With `mtsa.sparsify`, a decode target with a loop now raises `ValueError` before conversion instead of `RuntimeError` after it. For weight sparsity too, each module now keeps its train/eval mode, where the searcher used to give every module the model's mode. Mode names and saved state are unchanged, so existing checkpoints restore. - 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 Related open PR: #2409 (draft) adds `state_sparsity`. It is policy-only and takes external measurements through `mode_kwargs`, so it is not folded into `mts.sparsify` here. 🤖 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 a unified API for applying attention sparsity, weight sparsity, or both in one workflow. * Sparse attention supports fixed or calibrated skip-softmax thresholds, with calibration results preserved when applying additional sparsity modes. * Export preserves sparse attention without requiring a separate export step. * Combined sparsity workflows support applying weight and attention sparsity in either order. * **Documentation** * Updated guides and examples to show the unified API and combined sparsity workflows. * **Compatibility** * The previous attention-sparsification API is deprecated; use the unified API instead. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Rohan Joshi <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
What does this PR do?
Type of change: Bug fix
A calibrated skip-softmax model loses its fitted thresholds after a ModelOpt checkpoint roundtrip. QA saw all 22 attention modules of TinyLlama-1.1B go from
dynamic_calibratedto the static default aftermto.save/mto.restore(max logit difference 2.09 on the same input), on both the PyTorch and Triton backends.Root cause. Calibration stores its results (
calibration_params, the per-phasea/bfit, andtarget_sparse_ratio) as plain attributes on each module's_sparse_method_instance. They are not tensors, so the state dict doesn't carry them, andupdate_sparse_attention_metadatasaved onlymethodandmethod_config. On restore,restore_sparse_attention_modelre-converts the model from the config, which builds fresh method instances with both attributes set toNone.Fix. Follow the quantization design for non-tensor module state (
TensorQuantizer.get_modelopt_state/set_from_modelopt_state, collected byupdate_quantize_metadataand applied byrestore_quantizer_state):SparseAttentionModule.get_modelopt_state()returns the module's state:method,method_config, the enabled flag, and the calibration results when present.update_sparse_attention_metadatastores it per module in the mode metadata.SparseAttentionModule.set_from_modelopt_state()re-applies the enabled flag and calibration results afterconverthas rebuilt the method from the mode config.restore_sparse_attention_statecalls it per module._<key>attributes that nothing reads and called a_setup()that returns early, so removing it changes no behavior.The state stays in metadata rather than becoming buffers, so exported HF / vLLM weights gain no extra keys. The values are plain floats and dicts, so they load under
weights_only=True. Checkpoints saved before this change carry none of the new keys and restore as before.Persisting the enabled flag also fixes a related loss: layers turned off with
disable_sparse_attention()aftersparsifycame back enabled after restore (TensorQuantizerlikewise saves its disabled flag).Usage
No API change. Calibrated models now restore with their thresholds:
Testing
test_restore_keeps_calibration_params: injects calibration params, roundtrips throughmto.save/mto.restoreon a file and checks the params, target sparsity anddynamic_calibratedthreshold type. It fails without the fix (calibration_paramsisNoneafter restore) and passes with it.test_restore_keeps_disabled_modules: a module disabled aftersparsifystays disabled after restore. It fails without the fix.test_restore_legacy_state_without_calibration_keys: metadata without the new keys still restores (enabled, uncalibrated). It passes both with and without the fix.pytest tests/unit/torch/sparsity/attention_sparsity: 218 passed.flash_skip_softmax, PyTorch backend) throughmto.save/mto.restore: before the fix, modules restored asstaticand a disabled layer came back enabled; with it, both are preserved.triton_skip_softmaxcase. It goes through the same metadata path.Before your PR is "Ready for review"
CONTRIBUTING.md: N/AAdditional Information
Needs cherry-pick to
release/0.48.0(labelcherry-pick-0.48.0).Known limitation, unchanged: attributes changed with
set_sparse_attention_attributeaftersparsifyare not restored, since restore rebuilds the method from the original mode config.🤖 Generated with Claude Code
Summary by CodeRabbit