Skip to content

Keep calibrated skip-softmax thresholds across save/restore - #3028

Merged
kaix-nv merged 1 commit into
mainfrom
kaix/6982524-sparse-attn-calib-restore
Oct 26, 2026
Merged

kaix-nv merged 1 commit into
mainfrom
kaix/6982524-sparse-attn-calib-restore

Conversation

@kaix-nv

@kaix-nv kaix-nv commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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_calibrated to the static default after mto.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-phase a/b fit, and target_sparse_ratio) as plain attributes on each module's _sparse_method_instance. They are not tensors, so the state dict doesn't carry them, and update_sparse_attention_metadata saved only method and method_config. On restore, restore_sparse_attention_model re-converts the model from the config, which builds fresh method instances with both attributes set to None.

Fix. Follow the quantization design for non-tensor module state (TensorQuantizer.get_modelopt_state / set_from_modelopt_state, collected by update_quantize_metadata and applied by restore_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_metadata stores it per module in the mode metadata.
  • SparseAttentionModule.set_from_modelopt_state() re-applies the enabled flag and calibration results after convert has rebuilt the method from the mode config. restore_sparse_attention_state calls it per module.
  • The old restore body is removed. It only set _<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() after sparsify came back enabled after restore (TensorQuantizer likewise saves its disabled flag).

Usage

No API change. Calibrated models now restore with their thresholds:

model = mtsa.sparsify(model, SKIP_SOFTMAX_TRITON_CALIB, forward_loop=calib_loop)
mto.save(model, "ckpt.pth")
restored = mto.restore(fresh_model, "ckpt.pth")  # modules stay dynamic_calibrated

Testing

  • New unit test test_restore_keeps_calibration_params: injects calibration params, roundtrips through mto.save / mto.restore on a file and checks the params, target sparsity and dynamic_calibrated threshold type. It fails without the fix (calibration_params is None after restore) and passes with it.
  • New unit test test_restore_keeps_disabled_modules: a module disabled after sparsify stays disabled after restore. It fails without the fix.
  • New unit test 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.
  • CPU repro on a 2-layer tiny Llama (flash_skip_softmax, PyTorch backend) through mto.save / mto.restore: before the fix, modules restored as static and a disabled layer came back enabled; with it, both are preserved.
  • Not re-run: QA's GPU TinyLlama-1.1B / triton_skip_softmax case. It goes through the same metadata path.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ (older checkpoints restore 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?: ❌
  • Did you get Claude approval on this PR?: ❌ (pending)

Additional Information

Needs cherry-pick to release/0.48.0 (label cherry-pick-0.48.0).

Known limitation, unchanged: attributes changed with set_sparse_attention_attribute after sparsify are not restored, since restore rebuilds the method from the original mode config.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Sparse-attention models now retain calibrated thresholds and target sparsity when saved and restored, preserving their calibrated behavior.
    • Modules disabled before saving remain disabled after restoration.
    • Older saved states without enabled-status metadata continue to restore sparse attention as enabled, without calibration parameters.

@kaix-nv
kaix-nv requested review from a team as code owners October 26, 2026 18:00
@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between e15c56a and 2f8772d.

Files selected for processing: 3
  • modelopt/torch/sparsity/attention_sparsity/conversion.py
  • modelopt/torch/sparsity/attention_sparsity/sparse_attention.py
  • tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

Walkthrough

Sparse-attention state saving and restoration now includes calibration parameters, target sparse ratios, and enabled status. Conversion metadata uses module state methods. Tests cover calibrated values, disabled modules, and legacy state without enabled metadata.

Changes: Calibrated attention sparsity state

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: Normal

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: Passed 6
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 …
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 3 files.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The pull request changes only sparse-attention state handling and tests. Added code uses copy.deepcopy, metadata access, and state setters. It adds no torch.load(..., weights_only=False), `n…
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 no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, eval, exec, or # nosec. It changes no pyproject.toml or 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.

@kaix-nv
kaix-nv force-pushed the kaix/6982524-sparse-attn-calib-restore branch from cac4e89 to e15c56a Compare October 26, 2026 18:00
@kaix-nv kaix-nv changed the title [NVBug 6982524] Keep calibrated skip-softmax thresholds across save/restore Keep calibrated skip-softmax thresholds across save/restore Oct 26, 2026
@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-26 19:28 UTC

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_softmax TinyLlama 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() after sparsify) deserves a follow-up issue.
  • The same calibration dicts are stored once per module; they are small, so no change needed.

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.16%. Comparing base (1d9ec87) to head (2f8772d).
⚠️ Report is 4 commits behind head on main.

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     
Flag Coverage Δ
examples-diffusers 19.90% <61.11%> (+<0.01%) ⬆️
examples-gpt-oss 13.45% <22.22%> (+<0.01%) ⬆️
examples-hf_ptq 23.34% <22.22%> (-0.04%) ⬇️
examples-llm_distill 13.53% <22.22%> (+<0.01%) ⬆️
examples-llm_eval 17.17% <22.22%> (+<0.01%) ⬆️
examples-llm_qat 17.35% <22.22%> (-0.03%) ⬇️
examples-llm_sparsity 16.76% <61.11%> (+<0.01%) ⬆️
examples-megatron_bridge 26.48% <22.22%> (-0.21%) ⬇️
examples-specdec_bench 13.23% <22.22%> (-0.01%) ⬇️
examples-speculative_decoding 17.43% <22.22%> (-0.06%) ⬇️
examples-torch_onnx 21.22% <22.22%> (-0.03%) ⬇️
examples-torch_trt 15.15% <22.22%> (+<0.01%) ⬆️
examples-vllm_serve 17.39% <22.22%> (+<0.01%) ⬆️
gpu 59.00% <88.88%> (+7.96%) ⬆️
regression 15.05% <22.22%> (+<0.01%) ⬆️
unit 61.15% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kaix-nv
kaix-nv force-pushed the kaix/6982524-sparse-attn-calib-restore branch from e15c56a to 2f8772d Compare October 26, 2026 18:29
@kaix-nv
kaix-nv merged commit 0b953a3 into main Oct 26, 2026
52 checks passed
@kaix-nv
kaix-nv deleted the kaix/6982524-sparse-attn-calib-restore branch October 26, 2026 19:24
kevalmorabia97 added a commit that referenced this pull request Oct 28, 2026
#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]>
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 28, 2026
rohansjoshi added a commit that referenced this pull request Nov 6, 2026
### 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants