Skip to content

Add DASC recurrent state sparsity policy - #2409

Draft
kaix-nv wants to merge 3 commits into
mainfrom
kaix/dasc-state-sparsity
Draft

kaix-nv wants to merge 3 commits into
mainfrom
kaix/dasc-state-sparsity

Conversation

@kaix-nv

@kaix-nv kaix-nv commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: new feature

Adds an experimental modelopt.torch.sparsity.state_sparsity API for the first ModelOpt DASC milestone:

  • derives deterministic GDN whole-head decay horizons from A_log and dt_bias in CPU FP64;
  • selects the largest arbitrary positive Wmax that passes caller-supplied quality, lifecycle, and physical-storage evidence;
  • keeps DASC-NR zero recovery and DASC-WR suffix replay as explicit contracts;
  • records model, checkpoint, calibration provenance, masks, gates, measurements, and decay-storage dtype in versioned JSON-safe ModelOpt state;
  • validates model structure and storage-aware decay bounds during restore and deployment export;
  • fails closed for distributed Megatron GDN policies whose TP or PP geometry would be rank-local.

This change is policy-only and does not alter model execution. Runtime ragged checkpoint packing, suffix replay, KDA support, quantization, and GDN or KDA kernels are intentionally out of scope. A serving implementation must preserve convolution state and materialize ordinary dense recurrent state before continuation.

This draft supersedes #2375 and includes all review fixes accumulated there.

Usage

Import modelopt.torch.sparsity.state_sparsity, call calibrate with the model, configuration, and paired measurements, then call export_policy to obtain the deployment policy. The complete executable example and schema are in the sparsity guide.

Measurements contain paired dense-versus-DASC quality and physical checkpoint-storage results for every configured candidate.

Testing

  • Focused DASC suite: 60 passed, 1 optional Megatron skip
  • State, weight, and attention sparsity compatibility suites: 338 passed, 1 optional Megatron skip
  • Real Transformers Qwen3NextGatedDeltaNet smoke: passed on the prior reviewed tree
  • Pre-commit on all changed files: passed
  • Git diff check: clean

Before your PR is Ready for review

  • Is this change backward compatible?: yes
  • Copied code or new dependency?: no
  • New necessary tests?: yes
  • Changelog updated?: yes
  • Claude approval?: pending; this PR intentionally remains draft

Additional Information

Algorithm reference: https://arxiv.org/abs/2608.30386

The mode stores calibration evidence rather than treating weight-derived horizons as sufficient proof. A future runtime milestone should consume this policy in the serving prefix-cache serializer and loader and qualify matched-HBM capacity plus prefix-hit latency.

## Summary

Consolidates the complete reviewed fix stack for #2375 into one DCO-safe
commit:

- harden package exports, measurement semantics, wrapper handling, and
actionable calibration errors
- validate exact installed GDN identities plus ModelOpt dynamic
subclasses; reject lookalikes, ordinary subclasses, incomplete layers,
and partial layer sets
- make stale checkpoints saveable and restorable while keeping
deployment export strict
- make DASC recalibration replace and deduplicate existing mode state
without stale-metadata refresh
- record the declared decay-parameter checkpoint storage dtype and use
derived FP16/BF16/FP32 rounding bounds
- preserve BF16/FP16 storage and wider/cross-dtype reload compatibility
without globally widening FP32 tolerance
- add installed Transformers path coverage, optional Megatron gating,
lifecycle, tamper, lossy-cast, and mixed-layer regressions
- document the explicit storage-dtype contract

This consolidated PR supersedes the mechanically stacked review-fix PRs
#2377, #2378, #2379, #2380, #2382, #2383, #2384, and #2385. Its tree is
byte-identical to the independently reviewed leaf commit from #2386.

## Validation

- focused DASC suite: 23 passed, 1 absent optional Megatron skip
- DASC plus weight sparsity plus attention sparsity compatibility suite:
134 passed, 1 optional skip
- DASC package coverage: 408/408 statements, 100%
- full pre-commit on all touched files: passed
- real Transformers Qwen3NextGatedDeltaNet BF16 storage to FP32 reload
smoke: passed
- commit author and Signed-off-by identity both use kaix-nv
<[email protected]>

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

## Summary by CodeRabbit

* **New Features**
* Added support for configuring decay-parameter storage precision with
FP16, BF16, or FP32.
  * Added safer recalibration that replaces existing DASC state.
* Expanded compatibility with supported GDN adapter classes and model
wrappers.
* Added improved validation for sparsity policies, measurements, model
structure, and decay parameters.
  * Added support for perplexity-retention values above 1.

* **Documentation**
* Clarified evaluation responsibilities, recalibration behavior,
stale-policy handling, supported adapters, and dtype requirements.

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

---------

Signed-off-by: kaix-nv <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 11, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-2409/

Built to branch gh-pages at 2026-09-11 18:41 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant