Skip to content

Emit VisualGen-compatible sparse_attention_config for diffusion skip-softmax export - #1816

Closed
jingyu-ml wants to merge 4 commits into
mainfrom
skip-softmax-visualgen-export
Closed

jingyu-ml wants to merge 4 commits into
mainfrom
skip-softmax-visualgen-export

Conversation

@jingyu-ml

@jingyu-ml jingyu-ml commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix (+ small backward-incompatible config-field rename)

TensorRT-LLM's VisualGen runtime consumes a single-phase skip-softmax checkpoint schema that differs from the LLM (prefill/decode) schema export_sparse_attention_config emits for every model. As a result a diffusion checkpoint (e.g. WAN 2.2 T2V) calibrated and exported by ModelOpt today is not loadable by VisualGen:

  • coefficients are nested under threshold_scale_factor.prefill instead of threshold_scale_factor.coefficients — VisualGen's formula parser reads .coefficients, and its flat fallback then raises TypeError on the nested dict;
  • target_sparsity is a {phase: ratio} dict, which the VisualGen config parser explicitly rejects (it requires a scalar); and
  • the dense-window knob is the integer initial_disabled_steps, which no longer exists in TensorRT-LLM — it was renamed to the normalized [0, 1] disabled_until_timestep.

This PR makes export_sparse_attention_config diffusion-aware:

  • new for_diffusion argument (set by the diffusers export path in unified_export_hf) emits the VisualGen schema: threshold_scale_factor.coefficients, a scalar target_sparsity, and disabled_until_timestep;
  • the LLM (transformers) export path is unchanged (byte-for-byte);
  • the passthrough config field and the WAN 2.2 example CLI flag are renamed initial_disabled_steps → disabled_until_timestep (normalized [0, 1], validated) to match the deployed vocabulary.

Usage

from modelopt.torch.export import export_hf_checkpoint

# Diffusion pipelines automatically get the VisualGen schema (diffusers path -> for_diffusion=True):
export_hf_checkpoint(pipe, export_dir="Wan2.2-T2V-A14B-Diffusers-Skip-Softmax")

The exported <component>/config.json then contains:

"sparse_attention_config": {
  "config_groups": {
    "group_0": {
      "algorithm": "skip_softmax",
      "threshold_scale_factor": {
        "formula": "a * exp(b * target_sparsity)",
        "coefficients": {"a": 2142.73, "b": 4.28}
      },
      "target_sparsity": 0.5,
      "ignore": ["blocks.0.attn1", "blocks.0.attn2"]
    }
  }
}

Testing

  • New unit test test_exports_diffusion_visual_gen_format asserts the single-phase schema and that the default (LLM) schema is unchanged: pytest tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py::TestExportSparseAttentionConfig → 5 passed.
  • Updated the diffusers example integration test (tests/examples/diffusers/sparsity/test_sparsity.py) to assert the new schema.
  • Emitted format validated field-for-field against TensorRT-LLM main (tensorrt_llm/visual_gen/sparse_attention.py::SkipSoftmaxAttentionConfig.resolve_threshold_scale_factor, tensorrt_llm/_torch/attention_backend/sparse/skip_softmax.py) and the VisualGen docs/source/visual-gen/features/sparse-attention.md checkpoint-config example.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ❌ — renames the skip-softmax initial_disabled_steps config field to disabled_until_timestep (new field, normalized [0,1] units). The skip-softmax attention-sparsity export is new and not yet broadly adopted, so this aligns the metadata with the consuming runtime before it ships widely.
  • If you copied code from any other sources or added a new PIP dependency: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: N/A (maintainer to run /claude review)

Additional Information

The VisualGen consumer is SkipSoftmaxAttentionConfig.resolve_threshold_scale_factor; the LLM consumer (tensorrt_llm/llmapi/llm_args.py) keeps the phase-keyed schema, which is why the LLM export path is intentionally left unchanged.

Summary by CodeRabbit

  • New Features
    • Added diffusion-compatible sparse-attention export that targets the TRT-LLM VisualGen diffusion-transformer checkpoint schema (including new calibration/export fields and single-phase coefficient layout for skip-softmax).
    • Replaced skip-softmax “initial disabled steps” metadata with a normalized disabled_until_timestep cutoff.
  • Documentation
    • Updated the changelog and example CLI/options to reflect the new disabled-until-timestep export metadata.
  • Tests
    • Updated Wan 2.2 calibrated export assertions and coefficient expectations.
    • Added unit coverage for the diffusion (VisualGen) export schema.

TensorRT-LLM's VisualGen runtime consumes a single-phase skip-softmax
checkpoint schema that differs from the LLM (prefill/decode) schema
``export_sparse_attention_config`` emits for every model, so a diffusion
checkpoint (e.g. WAN 2.2 T2V) calibrated and exported by ModelOpt today is
not loadable by VisualGen:

  * coefficients are nested under ``threshold_scale_factor.prefill`` instead of
    ``threshold_scale_factor.coefficients`` (the VisualGen formula parser reads
    ``.coefficients`` and its flat fallback raises TypeError on the nested dict);
  * ``target_sparsity`` is a ``{phase: ratio}`` dict, which the VisualGen config
    parser explicitly rejects (it requires a scalar); and
  * the dense-window knob is the integer ``initial_disabled_steps``, which no
    longer exists in TensorRT-LLM (renamed to the normalized [0, 1]
    ``disabled_until_timestep``).

Make export_sparse_attention_config diffusion-aware: a new ``for_diffusion``
argument (set by the diffusers export path in unified_export_hf) emits the
VisualGen schema for diffusion transformers, while the LLM (transformers)
export path is left byte-for-byte unchanged. The passthrough config field and
the WAN 2.2 example flag are renamed initial_disabled_steps ->
disabled_until_timestep (normalized [0, 1], validated) to match the deployed
vocabulary.

Verified against TensorRT-LLM main: SkipSoftmaxAttentionConfig.
resolve_threshold_scale_factor reads threshold_scale_factor.coefficients,
raises on a dict target_sparsity, and reads disabled_until_timestep.

Signed-off-by: jingyux <[email protected]>
@jingyu-ml
jingyu-ml requested review from a team as code owners June 24, 2026 18:56
@copy-pr-bot

copy-pr-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: b9eabbe1-9fe1-493a-b3d8-483d34417e61

📥 Commits

Reviewing files that changed from the base of the PR and between fb06815 and c94f628.

📒 Files selected for processing (2)
  • CHANGELOG.rst
  • modelopt/torch/export/unified_export_hf.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.rst

📝 Walkthrough

Walkthrough

Skip-softmax sparse-attention export now uses normalized disabled_until_timestep metadata and a diffusion-specific VisualGen checkpoint schema. Diffusers wiring, the Wan 2.2 example, configuration validation, export tests, and changelog were updated accordingly.

Changes

Diffusion sparse-attention export

Layer / File(s) Summary
Config and export surface
modelopt/torch/sparsity/attention_sparsity/config.py, modelopt/torch/sparsity/attention_sparsity/conversion.py, modelopt/torch/export/unified_export_hf.py
SparseAttentionAttributeConfig replaces initial_disabled_steps with validated disabled_until_timestep; the exporter accepts for_diffusion, and Diffusers export enables it.
Diffusion export output
modelopt/torch/sparsity/attention_sparsity/conversion.py
Diffusion exports use top-level calibration coefficients, scalar target_sparsity, and optional disabled_until_timestep, while the default LLM schema remains phase-based.
Wan 2.2 example and validation
examples/diffusers/sparsity/wan22_skip_softmax.py, tests/examples/diffusers/sparsity/test_sparsity.py, tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py, CHANGELOG.rst
The CLI and sparse config use the normalized cutoff, tests validate the updated VisualGen fields, and the changelog documents the schema changes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DiffusersExport
  participant SparseAttentionExporter
  participant SparseAttentionModule
  participant ComponentConfig
  DiffusersExport->>SparseAttentionExporter: export_sparse_attention_config(for_diffusion=True)
  SparseAttentionExporter->>SparseAttentionModule: read calibration and cutoff metadata
  SparseAttentionExporter-->>DiffusersExport: VisualGen sparse_attention_config
  DiffusersExport->>ComponentConfig: persist sparse_attention_config
Loading

Suggested reviewers: edwardf0t1, kevalmorabia97, cjluo-nv, sugunav14

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: VisualGen-compatible sparse_attention_config export for diffusion skip-softmax.
Docstring Coverage ✅ Passed Docstring coverage is 91.67% which is sufficient. The required threshold is 80.00%.
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 Touched Python files add no torch.load(weights_only=False), numpy.load(allow_pickle=True), trust_remote_code=True, eval/exec, or # nosec; no dependency files changed.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch skip-softmax-visualgen-export

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

@github-actions

github-actions Bot commented Jun 24, 2026 •

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-1816/

Built to branch gh-pages at 2026-07-14 16:56 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modelopt/torch/sparsity/attention_sparsity/config.py (1)

158-185: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep a backward-compatible path for initial_disabled_steps.

This schema rename will reject older sparse-attention configs and saved ModelOpt state: config reload goes back through Pydantic, and ModeloptBaseConfig forbids unknown keys, so existing payloads that still contain initial_disabled_steps will fail to deserialize. Please keep a deprecated alias/legacy field (or another explicit migration path) until older checkpoints can still load. As per coding guidelines, "Preserve config and checkpoint backward compatibility for Pydantic-based configs to ensure older checkpoints remain loadable."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/sparsity/attention_sparsity/config.py` around lines 158 - 185,
Keep backward compatibility in the sparse-attention config schema by preserving
support for the legacy initial_disabled_steps key while introducing
disabled_until_timestep. Update the config in attention_sparsity/config.py so
ModeloptBaseConfig/Pydantic can still deserialize older checkpoints, either by
adding a deprecated alias or explicit migration/translation logic in the config
model before validation. Make sure the validation path in the config class
handles both names consistently and does not reject existing saved state that
still uses initial_disabled_steps.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@modelopt/torch/sparsity/attention_sparsity/config.py`:
- Around line 158-185: Keep backward compatibility in the sparse-attention
config schema by preserving support for the legacy initial_disabled_steps key
while introducing disabled_until_timestep. Update the config in
attention_sparsity/config.py so ModeloptBaseConfig/Pydantic can still
deserialize older checkpoints, either by adding a deprecated alias or explicit
migration/translation logic in the config model before validation. Make sure the
validation path in the config class handles both names consistently and does not
reject existing saved state that still uses initial_disabled_steps.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 12bcaeda-a7ed-4c72-aa9c-e1871d5b8493

📥 Commits

Reviewing files that changed from the base of the PR and between aa2a6a1 and 96b2eb4.

📒 Files selected for processing (7)
  • CHANGELOG.rst
  • examples/diffusers/sparsity/wan22_skip_softmax.py
  • modelopt/torch/export/unified_export_hf.py
  • modelopt/torch/sparsity/attention_sparsity/config.py
  • modelopt/torch/sparsity/attention_sparsity/conversion.py
  • tests/examples/diffusers/sparsity/test_sparsity.py
  • tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py

@cjluo-nv cjluo-nv 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.

Bot review — DM the bot to share feedback.

Focused, well-tested change (+114/-37, 7 files). Adds a for_diffusion kwarg to the existing export_sparse_attention_config to emit the TRT-LLM VisualGen single-phase skip-softmax schema (coefficients under threshold_scale_factor.coefficients, scalar target_sparsity, normalized disabled_until_timestep), and renames the passthrough config field initial_disabled_steps → disabled_until_timestep with a [0,1] validator.

Design review (gate fired on 5-directory span): this is NOT an architectural change — it extends an existing function and reuses existing config infrastructure rather than introducing a new subsystem/loader/DSL. No new design alternative needs justification.

Correctness looks good: the diffusion branch picks prefill (or first) coefficients and the prefill sparsity scalar; the LLM (for_diffusion=False) path is left byte-for-byte unchanged in a separate branch, and a unit test asserts the LLM {phase: ratio} schema is preserved. Validation, harvesting pattern, and example CLI rename are all consistent. Tests cover the new schema, the unchanged LLM schema, and the example integration. No licensing changes; no injection in the PR text.

Why nudge rather than approve: the field rename is an explicitly backward-incompatible change with a semantics shift (integer step count → normalized [0,1] cutoff). Old configs/checkpoints using initial_disabled_steps won't error — the field is silently ignored and simply not emitted. The author justifies this as acceptable because the skip-softmax export is new and not broadly adopted; that's a reasonable but product-level call that warrants a maintainer's explicit sign-off. Also, the new schema was validated against TRT-LLM main by hand (no automated cross-repo check), so a human with VisualGen context should confirm the field names/units match the deployed consumer.

@jingyu-ml
jingyu-ml requested a review from cjluo-nv July 1, 2026 05:48
skip_group["threshold_scale_factor"] = threshold_scale_factor
if target_sparse_ratio is not None:
scalar_sparsity = (
target_sparse_ratio.get("prefill")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Asymmetric phase fallback between coefficients and target_sparsity. coefficients above falls back to next(iter(calibration_params.values())) when "prefill" is absent, but target_sparsity here reads only target_sparse_ratio.get("prefill") with no fallback.

If a diffusion checkpoint is ever calibrated with a non-prefill phase (the decode path in calibration/calibrate.py supports this), the export would emit coefficients (from the fallback phase) but silently drop target_sparsity — producing a VisualGen config missing the scalar sparsity it requires, i.e. exactly the parse failure this PR aims to prevent. The WAN example hardcodes {"prefill": ...} so it can't trigger today, but the two lookups should share the same phase resolution to stay robust — e.g. resolve the phase key once and use it for both.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch on the asymmetry — the two lookups do differ. Leaving it as-is though, because the divergent case can't be reached by any supported calibration path:

  • Decode-phase calibration is LLM-only. The decode calibrator needs the RULER dataset + tokenizer (create_decode_calibration_forward_loop drives tokenizer-based KV-cache generation), and those are only built when no custom forward_loop is passed. Diffusion models are always calibrated with a custom pipeline forward_loop (as in the WAN example), so enabling decode there raises RuntimeError("calibration_data and tokenizer must be built before decode") in calibration/calibrate.py before any params are produced. A diffusion checkpoint whose calibration_params lacks "prefill" can't be created.
  • target_sparse_ratio on this path is always prefill-keyed too — the CalibConfig default is {"prefill": 0.5, "decode": 0.5} and the WAN example passes {"prefill": ...}.

So under for_diffusion=True both lookups always resolve the same "prefill" entry; the next(iter(...)) on coefficients is belt-and-braces rather than a fallback that can diverge from target_sparsity in practice. This branch deliberately mirrors, field-for-field, what VisualGen's SkipSoftmaxAttentionConfig on TRT-LLM main parses today (single coefficients block + scalar target_sparsity), so I'd rather not add speculative phase resolution the consumer can't use. If diffusion ever grows a second calibration phase, the VisualGen schema has to change first anyway — I'll unify the phase-key resolution as part of that alignment.

threshold_scale_factor[phase] = {
"a": calibration_params[phase]["a"],
"b": calibration_params[phase]["b"],
if for_diffusion:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional cleanup: the if for_diffusion / else branches duplicate skip_group["threshold_scale_factor"] = threshold_scale_factor and the target_sparsity gating — only the shape differs (single vs per-phase coeffs; scalar vs dict sparsity). Computing the two shape-specific values first and assigning them once after the branch would remove the copy-paste and reduce the chance the two paths drift on future edits. Not a correctness issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Considered it, but keeping the two branches flat is deliberate: each one assembles a single consumer's schema (TRT-LLM VisualGen vs. the LLM runtime) in one linear block that can be checked line-by-line against the runtime parser — the VisualGen format was just pinned down on the TRT-LLM side and this PR mirrors it verbatim. Since the two schemas serve different runtimes and are expected to evolve independently (that's why the for_diffusion switch exists), hoisting the shared assignments would couple them to save ~2 lines. Happy to revisit if a third consumer format shows up.

@mxinO mxinO left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thanks.

@jingyu-ml

Copy link
Copy Markdown
Contributor Author

/ok to test 88b8e44

@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.26%. Comparing base (f479e78) to head (c94f628).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1816      +/-   ##
==========================================
+ Coverage   76.33%   77.26%   +0.92%     
==========================================
  Files         522      522              
  Lines       58452    58466      +14     
==========================================
+ Hits        44618    45171     +553     
+ Misses      13834    13295     -539     
Flag Coverage Δ
examples 43.29% <78.57%> (+2.21%) ⬆️
gpu 57.93% <25.00%> (-0.67%) ⬇️
regression 15.08% <17.85%> (+0.12%) ⬆️
unit 55.40% <92.85%> (+<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.

@jingyu-ml
jingyu-ml enabled auto-merge (squash) July 6, 2026 20:44
@jingyu-ml
jingyu-ml requested a review from Edwardf0t1 July 6, 2026 22:07
@jingyu-ml

Copy link
Copy Markdown
Contributor Author

/ok to test fb06815

@jingyu-ml

Copy link
Copy Markdown
Contributor Author

/ok to test c94f628

@cjluo-nv cjluo-nv 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.

Bot review (bedrock-claude-opus-4-8) — DM the bot to share feedback.

Focused change (+114/-37, 7 files): adds a for_diffusion kwarg to the existing export_sparse_attention_config to emit the TRT-LLM VisualGen single-phase skip-softmax schema (coefficients under threshold_scale_factor.coefficients, scalar target_sparsity, normalized disabled_until_timestep), and renames the passthrough config field initial_disabled_steps → disabled_until_timestep with a [0,1] validator.

Design review (gate fired on 5-directory span): NOT an architectural change — it extends an existing function and reuses the existing Pydantic config infrastructure (SparseAttentionAttributeConfig, ModeloptBaseConfig) rather than introducing a new subsystem/loader/DSL. No design alternative needs justifying. Correctness is sound: the diffusion branch resolves prefill (or first) coefficients + the prefill scalar sparsity; the LLM (for_diffusion=False) path is left byte-for-byte in a separate branch. Tests cover the new schema, the unchanged LLM {phase: ratio} schema, and the example integration. No injection in the PR text; no licensing changes (2024 headers pre-exist, untouched).

Re-review of prior comments:

  • 💬 Edwardf0t1 (conversion.py:498, asymmetric phase fallback — correctness): Author replied that the divergent case is unreachable — diffusion always calibrates with a custom pipeline forward_loop, so decode-phase calibration (LLM-only, needs RULER+tokenizer) can't run, and target_sparse_ratio on this path is always prefill-keyed. Rationale is reasonable; the WAN example hardcodes {"prefill": ...}. Considered resolved.
  • Edwardf0t1 (conversion.py:486, dedup the branches — minor/optional): Author declined with a reasonable "keep each consumer schema flat and line-checkable" rationale. Fine to leave.

Why nudge rather than approve:

  • 💬 CodeRabbit flagged (config.py:158-185, Major) that the initial_disabled_steps → disabled_until_timestep rename breaks backward compat — ModeloptBaseConfig uses extra="forbid", so restoring old ModelOpt state whose sparse_cfg still carries initial_disabled_steps will raise a Pydantic validation error inside set_from_attribute_config during restore. No alias/migration was added. Author/PR body argue this is acceptable because the skip-softmax export is new and not broadly adopted — a deliberate product call, not a bug — but the repo's coding guideline ("preserve config/checkpoint backward compat for Pydantic configs") means a maintainer should explicitly sign off on shipping the incompatible rename (and the int-step → normalized-[0,1] semantics shift) rather than adding a deprecated alias. Note only checkpoints that set initial_disabled_steps > 0 are affected (default 0 was never emitted).
  • The emitted VisualGen schema (field names/units) was validated by hand against TRT-LLM main, with no automated cross-repo check — a human with VisualGen context should confirm the deployed consumer matches.

@Edwardf0t1 Edwardf0t1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approve to unblock

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
modelopt/torch/export/unified_export_hf.py (1)

67-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep imports at the top, or document the ordering exception.

These module-level imports occur after executable declarations. Move them into the top import block, or document a required circular/registration ordering.

As per coding guidelines, imports must remain at the top unless a circular, optional, or unusually heavy dependency justifies a documented exception.

Also applies to: 113-113

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/export/unified_export_hf.py` around lines 67 - 68, Move the
module-level hf_export_handlers import to the file’s top import block while
preserving its registry-registration side effect; if ordering is required for
circularity or registration, retain the current placement and add a concise
explanatory comment documenting that exception.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modelopt/torch/export/unified_export_hf.py`:
- Around line 1058-1070: Make the temporary-buffer lifecycle in the export flow
transactional: snapshot any existing buffers named pre_quant_scale,
svdquant_lora_a, and svdquant_lora_b before promotion, then begin the try block
before the register_buffer calls so partial promotion is covered. In the
corresponding finally cleanup paths, restore each snapshotted original buffer
(or remove only newly promoted buffers when no original existed), including the
additional promotion sites noted in the comment, without altering unrelated
model state.

---

Nitpick comments:
In `@modelopt/torch/export/unified_export_hf.py`:
- Around line 67-68: Move the module-level hf_export_handlers import to the
file’s top import block while preserving its registry-registration side effect;
if ordering is required for circularity or registration, retain the current
placement and add a concise explanatory comment documenting that exception.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: b9eabbe1-9fe1-493a-b3d8-483d34417e61

📥 Commits

Reviewing files that changed from the base of the PR and between fb06815 and c94f628.

📒 Files selected for processing (2)
  • CHANGELOG.rst
  • modelopt/torch/export/unified_export_hf.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.rst

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (1)
modelopt/torch/export/unified_export_hf.py (1)

67-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep imports at the top, or document the ordering exception.

These module-level imports occur after executable declarations. Move them into the top import block, or document a required circular/registration ordering.

As per coding guidelines, imports must remain at the top unless a circular, optional, or unusually heavy dependency justifies a documented exception.

Also applies to: 113-113

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/export/unified_export_hf.py` around lines 67 - 68, Move the
module-level hf_export_handlers import to the file’s top import block while
preserving its registry-registration side effect; if ordering is required for
circularity or registration, retain the current placement and add a concise
explanatory comment documenting that exception.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modelopt/torch/export/unified_export_hf.py`:
- Around line 1058-1070: Make the temporary-buffer lifecycle in the export flow
transactional: snapshot any existing buffers named pre_quant_scale,
svdquant_lora_a, and svdquant_lora_b before promotion, then begin the try block
before the register_buffer calls so partial promotion is covered. In the
corresponding finally cleanup paths, restore each snapshotted original buffer
(or remove only newly promoted buffers when no original existed), including the
additional promotion sites noted in the comment, without altering unrelated
model state.

---

Nitpick comments:
In `@modelopt/torch/export/unified_export_hf.py`:
- Around line 67-68: Move the module-level hf_export_handlers import to the
file’s top import block while preserving its registry-registration side effect;
if ordering is required for circularity or registration, retain the current
placement and add a concise explanatory comment documenting that exception.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: b9eabbe1-9fe1-493a-b3d8-483d34417e61

📥 Commits

Reviewing files that changed from the base of the PR and between fb06815 and c94f628.

📒 Files selected for processing (2)
  • CHANGELOG.rst
  • modelopt/torch/export/unified_export_hf.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.rst
🛑 Comments failed to post (1)
modelopt/torch/export/unified_export_hf.py (1)

1058-1070: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Make temporary-buffer cleanup transactional and preserve originals.

register_buffer can replace an existing buffer, while cleanup unconditionally deletes these names. This can permanently alter the live model. Also, promotion occurs before the try, so a partial promotion can leak temporary buffers if it raises. Snapshot existing buffers, start the try before promotion, and restore originals in finally.

Suggested lifecycle fix
-            _promote_quantizer_tensors_to_module(component)
-
-            try:
+            original_buffers = {}
+            try:
+                original_buffers = _promote_quantizer_tensors_to_module(component)
                 ...
             finally:
-                _remove_promoted_quantizer_tensors(component)
+                _restore_promoted_quantizer_tensors(component, original_buffers)

Also applies to: 1082-1085, 1171-1180, 1222-1225

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/export/unified_export_hf.py` around lines 1058 - 1070, Make
the temporary-buffer lifecycle in the export flow transactional: snapshot any
existing buffers named pre_quant_scale, svdquant_lora_a, and svdquant_lora_b
before promotion, then begin the try block before the register_buffer calls so
partial promotion is covered. In the corresponding finally cleanup paths,
restore each snapshotted original buffer (or remove only newly promoted buffers
when no original existed), including the additional promotion sites noted in the
comment, without altering unrelated model state.

@jingyu-ml jingyu-ml closed this Oct 2, 2026
auto-merge was automatically disabled October 2, 2026 19:00

Pull request was closed

Edwardf0t1 added a commit that referenced this pull request Oct 26, 2026
…softmax export (#2868)

### What does this PR do?

Type of change: Bug fix

The diffusers skip-softmax HF export wrote the LLM phase-keyed schema
(`threshold_scale_factor.prefill` and a `{phase: ratio}`
`target_sparsity`). TRT-LLM VisualGen (PR #14687) expects
`threshold_scale_factor.coefficients` and a scalar `target_sparsity`, so
the exported Wan2.2 checkpoint fails to load (`float() ... not 'dict'`).
NVBug 6927804.

- `export_sparse_attention_config(model, *, for_diffusion=False)`: with
`for_diffusion=True`, emit one `coefficients` block and a scalar
`target_sparsity`. The LLM path and the vLLM calibration plugin are
unchanged. `_export_diffusers_checkpoint` passes `for_diffusion=True`.
- Fix the READMEs, which referenced the removed
`resolve_for_target_sparsity`.

Based on #1816 (closed, approved). Deliberately dropped its
`initial_disabled_steps` -> `disabled_until_timestep` rename:
`initial_disabled_steps` shipped in 0.46 and the vLLM calibration path
now depends on it, so the rename is a separate, breaking change.

### Usage

```bash
python examples/diffusers/sparsity/wan22_skip_softmax.py --calibrate --target-sparsity 0.5 --export-dir ckpt ...
# transformer/config.json -> sparse_attention_config.config_groups.group_0:
#   threshold_scale_factor: {formula, coefficients: {a, b}}, target_sparsity: 0.5
```

### Testing
- Extended `test_sparse_attention_conversion.py` (diffusion schema) and
the Wan calibrated-export example test.
- **Not run:** no torch environment was available where this was
written, so pytest has not been executed; only pre-commit passed and the
conversion logic was checked standalone. Relying on CI. No TRT-LLM
VisualGen load was tested.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ❌ Diffusers skip-softmax
checkpoints are now emitted in the VisualGen schema (previous ones did
not load in VisualGen); LLM export 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?: ✅
- Did you get Claude approval on this PR?: ❌

### Additional Information
NVBug 6927804; supersedes #1816.

🤖 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 skip-softmax Hugging Face exports for diffusion models to use
the TRT-LLM VisualGen format, including grouped threshold coefficients
and scalar target sparsity.
* Existing affected checkpoints must be re-exported to apply the
corrected format.
* **Documentation**
* Updated diffusion sparsity documentation to describe the exported
checkpoint schema and its calibration and runtime-sparsity settings.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Zhiyu Cheng <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
@kevalmorabia97
kevalmorabia97 deleted the skip-softmax-visualgen-export branch November 3, 2026 06:30
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.

6 participants