Skip to content

Exclude exact casts from DASC bounds - #2392

Merged
kaix-nv merged 2 commits into
feature/dasc-state-sparsity-review-contract-cleanupfrom
feature/dasc-state-sparsity-review-rounding
Sep 11, 2026
Merged

kaix-nv merged 2 commits into
feature/dasc-state-sparsity-review-contract-cleanupfrom
feature/dasc-state-sparsity-review-rounding

Conversation

@kaix-nv

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

Copy link
Copy Markdown
Contributor

Addresses the final numerical-bound and cleanup review findings.

Changes:

  • exclude exact widening dtypes from composed inverse rounding bounds
  • retain both bounds only when neither dtype exactly contains the other, such as FP16 versus BF16
  • add direct FP16/BF16-with-FP32 widening regressions
  • remove the ambiguous single-use validated/converting helper and cast inline after validation
  • align the guide with the tightened exact-widening contract

Validation:

  • focused DASC tests: 27 passed, 1 skipped (optional Megatron dependency)
  • pre-commit on all touched files: passed

Commit is ED25519-signed and carries a matching Signed-off-by trailer.

Summary by CodeRabbit

  • Bug Fixes

    • Improved decay-policy validation for sequential rounding operations.
    • Prevented redundant precision conversions from adding incorrect rounding allowances.
    • Preserved accurate validation for BF16 and FP16 decay tensors.
  • Tests

    • Added coverage confirming consistent rounding-radius calculations across FP16, BF16, and FP32 comparisons.
  • Documentation

    • Updated sparsity guidance to clarify decay-policy rounding behavior.

@kaix-nv
kaix-nv requested review from a team as code owners September 11, 2026 03:39
@kaix-nv

kaix-nv commented Sep 11, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@kaix-nv
kaix-nv requested review from kevalmorabia97 and removed request for a team September 11, 2026 03:39
@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 82299ab2-9b2a-4d84-94b1-2c917dfb3ac4

📥 Commits

Reviewing files that changed from the base of the PR and between aca0183 and 28b1f1a.

📒 Files selected for processing (1)
  • modelopt/torch/sparsity/state_sparsity/policy.py

📝 Walkthrough

Walkthrough

The sparsity policy now validates decay tensors directly, converts them to CPU float64, and excludes redundant dtype casts from storage-rounding bounds. Documentation and tests cover the updated FP16 and BF16 behavior.

Changes

Decay policy validation and rounding

Layer / File(s) Summary
Direct decay tensor validation
modelopt/torch/sparsity/state_sparsity/policy.py
Removed the cached validation helper. compute_gdn_decay_horizons now validates and converts decay tensors directly.
Contained dtype rounding
modelopt/torch/sparsity/state_sparsity/policy.py, docs/source/guides/6_sparsity.rst, tests/unit/torch/sparsity/state_sparsity/test_dasc.py
Storage-rounding bounds now discard duplicate and exactly contained dtypes. Documentation and tests cover sequential bounds and FP16/BF16 tensors.

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to aca01

The updated decay validation and rounding behavior is covered by matching tests and documentation, with no current merge-blocking risk identified.

🚥 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 and concisely summarizes the main change: excluding exact casts from DASC bounds.
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 9 functions across 2 files. (1 skipped: 1 …
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 one modelopt Python file and one test file; it adds only dtype-bound calculations and inline tensor validation/conversion. The authoritative diff adds no `torch.load(…
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/dasc-state-sparsity-review-rounding

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

Comment on lines +300 to +307
cast_dtypes = tuple(dict.fromkeys((storage_dtype, tensor.dtype)))
cast_dtypes = tuple(
dtype
for dtype in cast_dtypes
if not any(
dtype != other and _dtype_exactly_contains(other, dtype) for other in cast_dtypes
)
)

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.

[SUGGESTION] The containment filter is correct for every dtype pair reachable here, but it is built as an O(n²) any() scan plus a second rebinding of cast_dtypes over a tuple that can never hold more than two entries — and it can in principle produce an empty tuple.

Two things worth tightening:

  1. Readability / single assignment. cast_dtypes is assigned twice in a row, and the reader has to work out that _dtype_exactly_contains(other, dtype) drops dtype (the wider dtype) rather than other. The three reachable outcomes — drop storage, drop live, keep both — are easier to read stated directly.

  2. The empty-tuple case yields zero slack, silently. If both dtypes were dropped, the for loop never executes, upper stays equal to values, and the function returns exactly 0. _storage_cast_horizon_bounds would then demand bit-exact horizon agreement, and the resulting ApplyModeError would point at the parameters rather than at the dtype pair. That requires two distinct dtypes with identical (max, eps, tiny*eps), which no current torch float dtype pair satisfies (I checked the fp8 variants — e5m2/e5m2fnuz match on max and eps but differ in smallest subnormal), so this is not a live bug. It is a sharp edge that disappears for free with an explicit branch.

Both are addressed by replacing the two statements with:

    live_dtype = tensor.dtype
    if _dtype_exactly_contains(live_dtype, storage_dtype):
        cast_dtypes = (live_dtype,)
    elif _dtype_exactly_contains(storage_dtype, live_dtype):
        cast_dtypes = (storage_dtype,)
    else:
        cast_dtypes = (storage_dtype, live_dtype)

This also subsumes the dict.fromkeys dedup: when the dtypes are equal both predicates hold, the first branch wins, and the result is the single-dtype tuple the old code produced. Non-blocking.

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.

Addressed in #2393. The containment scan is replaced with the explicit three-way branch, which guarantees one or two bound dtypes and makes the keep-live, keep-storage, and compose-both cases direct.

@claude

claude Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Claude review summary

Scope: full review (the trigger comment carried no scoping instructions). 3 files changed / +35 −16 — all three reviewed: modelopt/torch/sparsity/state_sparsity/policy.py, tests/unit/torch/sparsity/state_sparsity/test_dasc.py, docs/source/guides/6_sparsity.rst.

Findings — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 1

What I verified

_dtype_exactly_contains is sound as an exact-representability test. The three conditions map onto the three ways a cast can lose information: max covers the upper exponent range, eps covers mantissa width, and tiny * eps covers the subnormal grid spacing at the low end. A value that is normal in the source but subnormal in the target is still exact, because the target's uniform subnormal spacing is bounded by the source's spacing at that magnitude. Checking the realistic pairs: fp32 ⊃ fp16 ✅, fp32 ⊃ bf16 ✅ (bf16.max 3.3895e38 ≤ fp32.max 3.4028e38), and fp16 ⊅ bf16 / bf16 ⊅ fp16 ✅ — so the FP16-vs-BF16 pair the PR description calls out does retain both bounds, as intended.

The filter drops the right dtype. _dtype_exactly_contains(other, dtype) removes dtype when dtype exactly contains other, i.e. the wider cast is dropped and the lossy one retained. That matches the physical cast chain in _decay_parameters (live → storage_dtype → float32), where a widening leg is a no-op.

The tightening cannot cause false rejections of previously-valid policies — the main backward-compat risk I looked for, since _storage_cast_horizon_bounds recomputes bounds at restore rather than reading stored slack. Walking the reachable calibrate/restore dtype combinations, the slack now removed was always attributable to a cast that is exact for the value in hand:

calib live storage restore live before after error actually incurred
fp32 fp32 (default) fp32 (fp32) (fp32) unchanged
fp32 fp32 bf16 bf16 ⊗ fp32 (bf16) bf16 rounding only
fp32 fp16 fp32 fp16 ⊗ fp32 (fp16) fp16 rounding only
bf16 fp16 bf16 fp16 ⊗ bf16 fp16 ⊗ bf16 unchanged

In every narrowed row the dropped leg is exact for that value, so the retained inverse bound (v + s)/(1 − u) still strictly covers the real deviation. No checkpoint that validated before will start failing.

Helper removal is clean. _validated_gdn_decay_tensors had exactly one caller (compute_gdn_decay_horizons); _validate_gdn_decay_tensors is still reached from all three of its call sites (lines 113, 206, 492). No dangling references.

Docs match the code. The rewritten paragraph in 6_sparsity.rst accurately describes the new contract, and the now-false claim about float32 storage contributing a negligible float32 step is gone. No CHANGELOG.rst entry needed — this is an in-cycle refinement of an unreleased feature.

The one suggestion

Inline on policy.py:300-307: the filter is an O(n²) any() scan plus a second rebinding of cast_dtypes over a tuple that never exceeds two entries, and it can in principle return an empty tuple — which would silently yield a zero radius and demand bit-exact horizon agreement. That requires two distinct dtypes with identical (max, eps, tiny*eps), which no current torch float dtype pair satisfies, so it is a sharp edge rather than a bug. An explicit three-way branch reads better and removes the edge for free.

Not flagged

Two pre-existing items I looked at and deliberately left alone, since neither is introduced here and CONTRIBUTING asks for surgical changes: reversed(cast_dtypes) unwinds the live-dtype leg before the storage leg, which is the opposite of the forward chain — but the leading 1/∏(1−uᵢ) factor is order-independent and only the subnormal terms differ, at magnitudes far below the bound itself; and _analyze_gdn_modules validates before downcasting and then compute_gdn_decay_horizons validates again, which is intentional (it catches non-finite inputs pre-cast).

Risk: low. A narrow, well-tested numerical tightening in a single private helper, with the new FP16/BF16 widening regressions pinning the behavior. The author reports 27 passed / 1 skipped locally; I could not execute the suite in this sandbox, so the numerical reasoning above is analytical rather than empirical.

🤖 Generated with Claude Code

@claude claude 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.

Claude review passed — no blocking issues found. LGTM

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-09-11 03:50 UTC

@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.78%. Comparing base (7298a77) to head (28b1f1a).
⚠️ Report is 1 commits behind head on feature/dasc-state-sparsity-review-contract-cleanup.

Additional details and impacted files
@@                                   Coverage Diff                                    @@
##           feature/dasc-state-sparsity-review-contract-cleanup    #2392       +/-   ##
========================================================================================
+ Coverage                                                68.74%   78.78%   +10.03%     
========================================================================================
  Files                                                      548      548               
  Lines                                                    64220    64228        +8     
========================================================================================
+ Hits                                                     44151    50600     +6449     
+ Misses                                                   20069    13628     -6441     
Flag Coverage Δ
examples-diffusers 20.81% <7.69%> (+0.01%) ⬆️
examples-gpt-oss 13.38% <7.69%> (+<0.01%) ⬆️
examples-hf_ptq 21.78% <7.69%> (+<0.01%) ⬆️
examples-llm_distill 13.45% <7.69%> (+<0.01%) ⬆️
examples-llm_eval 17.25% <7.69%> (+0.02%) ⬆️
examples-llm_sparsity 15.94% <7.69%> (+<0.01%) ⬆️
examples-megatron_bridge 26.25% <7.69%> (-0.01%) ⬇️
examples-specdec_bench 13.14% <7.69%> (+<0.01%) ⬆️
examples-speculative_decoding 17.67% <7.69%> (+0.01%) ⬆️
examples-torch_onnx 21.81% <7.69%> (+<0.01%) ⬆️
examples-torch_trt 15.14% <7.69%> (+<0.01%) ⬆️
gpu 58.35% <7.69%> (+37.44%) ⬆️
regression 15.15% <7.69%> (+<0.01%) ⬆️
unit 57.46% <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.

Addresses the final non-blocking review suggestion on #2392.

Changes:
- replace the generic containment filter with an explicit three-way
dtype selection
- guarantee a non-empty bound tuple
- make the exact outcomes obvious: keep live, keep storage, or compose
both

Validation:
- focused DASC tests: 27 passed, 1 skipped (optional Megatron
dependency)
- pre-commit on the touched file: passed

Commit is ED25519-signed and carries a matching Signed-off-by trailer.

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

## Summary by CodeRabbit

- **Bug Fixes**
- Improved numerical handling when determining storage rounding behavior
across different data types.
- Ensured cast sequences are selected according to exact
representability between live and storage formats.

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

Signed-off-by: kaix-nv <[email protected]>
@kaix-nv
kaix-nv merged commit 6456c40 into feature/dasc-state-sparsity-review-contract-cleanup Sep 11, 2026
8 of 10 checks passed
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