Skip to content

frost(sdpa): GQA/MQA, padding mask, right-band widening, and sink-token gradients for the SM120 f16 backward - #557

Merged
vedaanta merged 8 commits into
NVIDIA:developfrom
Adnios:feat/sm120_sdpa_bwd_padding_mask
Aug 13, 2026
Merged

frost(sdpa): GQA/MQA, padding mask, right-band widening, and sink-token gradients for the SM120 f16 backward#557
vedaanta merged 8 commits into
NVIDIA:developfrom
Adnios:feat/sm120_sdpa_bwd_padding_mask

Conversation

@Adnios

@Adnios Adnios commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Before submitting

  • I agree to license this contribution under the terms of LICENSE.txt.
  • I ran pre-commit run and committed any formatting changes.
  • I added GitHub labels: one cat-*, one or more mod-*, and one orig-* (see label list).

Affected area

  • FE OSS kernels or CuTeDSL

Summary

  • GQA / MQA (H_q a multiple of H_kv, including H_kv == 1)

    • Grid unchanged: one CTA per (KV tile, query head, batch); kv_head = q_head // (H_q/H_kv) picks the K/V slice.
    • Each CTA writes its q-head's dK/dV tiles to dk_ws/dv_ws (H_q-headed workspace); a small _dkv_reduce_kernel sums each group in fp32, fixed q-head order (deterministic, PDL-chained).
  • Padding mask (per-batch actual sequence lengths)

    • Per-batch int32 lengths seq_len_q/kv
    • Trims q/KV tile loops to the actual lengths; only the boundary tile masks scores; padded dQ/dK/dV rows are exact zeros.
    • BR diagonal anchors at seq_len_kv[b] − seq_len_q[b].
  • Right-band widening (diagonal_band_right_bound > 0)

    • keep kv <= q + diag_off + R
  • Sink-token backward (dSink_token output)

    • A new _dsink_kernel to summing over every batch b and query row q and return dSink_token output
    • dsink[h] = -sum_{b,q} exp(sink[h] - LSE[b,h,q]) * delta[b,h,q]

Why

Related issues

#381

API and compatibility impact

Testing


Summary by CodeRabbit

New Features

  • Added sink-token support, including sink gradients.
  • Added variable per-batch query and key/value lengths, padding masks, and zero-length batches.
  • Added GQA/MQA support with deterministic gradient reductions.
  • Expanded causal masking with right-window widening and padded-row handling.

Documentation

  • Updated supported configurations, masking behavior, sink inputs, and workspace guidance.

Tests

  • Added coverage for sinks, padding, GQA/MQA, deterministic execution, and invalid configurations.

@Adnios Adnios self-assigned this Aug 12, 2026
@Adnios Adnios added cat-feature Requests for new functionality, APIs, examples, or behavior improvements. orig-nv-eng Reported or requested by NVIDIA engineering. mod-frost labels Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 5dda2163-79c1-4d18-88f7-8508ee27cf68

📥 Commits

Reviewing files that changed from the base of the PR and between 30de426 and fa63cb2.

📒 Files selected for processing (4)
  • python/cudnn/sdpa/bwd/api_dsl.py
  • python/cudnn/sdpa/bwd/engines.py
  • python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py
  • test/python/sdpa/frost/test_sdpa_graph_analyzer.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • python/cudnn/sdpa/bwd/engines.py
  • test/python/sdpa/frost/test_sdpa_graph_analyzer.py
  • python/cudnn/sdpa/bwd/api_dsl.py
  • python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py

📝 Walkthrough

Walkthrough

The SM120 SDPA backward path adds GQA/MQA support, per-batch Q/KV sequence lengths, right-band masks, sink tokens, deterministic reduction, workspace handling, engine wiring, tests, and documentation.

Changes

SM120 SDPA backward extensions

Layer / File(s) Summary
API specialization and engine wiring
python/cudnn/sdpa/bwd/api_dsl.py, python/cudnn/sdpa/bwd/config_sm120.py, python/cudnn/sdpa/bwd/engines.py
The API validates sequence-length and sink inputs, supports divisible query/KV head counts, updates specialization keys, sizes GQA workspace, and forwards optional tensors through engine bindings.
GQA, padding, and sink kernel execution
python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py
The kernel applies padding and right-band masks, separates query and KV head indexing, writes per-query-head dK/dV partials, performs deterministic reduction, and optionally computes dSink.
Padding, sink, and GQA validation coverage
test/python/sdpa/frost/test_sdpa_bwd_dsl_sm120.py, test/python/sdpa/frost/test_sdpa_graph_analyzer.py
Tests cover right-band masks, padding, zero-length batches, sink gradients, GQA/MQA ratios, deterministic execution, workspace sizing, padded gradients, and invalid configurations.
Public API and behavior documentation
docs/fe-oss-apis/attention/sdpa_bwd_sm120.md
The documentation describes wrapper inputs, masking behavior, sink gradients, GQA/MQA reductions, deterministic ordering, launch counts, and workspace requirements.

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

Mergeability Score: 🟡 Moderate · up to fa63c

This PR adds sink-token gradients, per-batch padding support, and expanded operand handling, but the current implementation can produce incorrect sink gradients for padded queries or fail with invalid/incompatible sink operands. The PR is not merge-ready until these bounded correctness and runtime issues are fixed or explicitly accepted.

Sequence Diagram(s)

sequenceDiagram
  participant SdpaBinding
  participant SdpaBwdDsl
  participant SM120BackwardKernel
  participant GQAReduction
  SdpaBinding->>SdpaBwdDsl: Forward sequence lengths and sink tensors
  SdpaBwdDsl->>SM120BackwardKernel: Launch specialized backward kernel
  SM120BackwardKernel->>GQAReduction: Write grouped dK/dV partials
  GQAReduction->>SdpaBwdDsl: Write final dK/dV outputs
Loading

Suggested labels: mod-cutedsl

Suggested reviewers: yangxu1990uiuc, aneureka

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes the affected area, summary, and related issue, but the Why, API and compatibility impact, and Testing sections are empty. Add the rationale, API and compatibility impact, exact test commands with results, and any explanations for untested areas.
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main SM120 backward changes: GQA/MQA, padding masks, right-band widening, and sink-token gradients.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@Adnios

Adnios commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

@cudnn-ci-bot run frost

@cudnn-ci-bot

Copy link
Copy Markdown

🚀 Running mirror pipeline

Branch: cudnn-gh/pr-557-3048a00
Pipeline: 62272145
Targets: frost

@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: 4

🤖 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 `@docs/fe-oss-apis/attention/sdpa_bwd_sm120.md`:
- Around line 80-86: Add a suitable language identifier, such as text, to the
fenced code block containing the dot/main/reduce/cvt descriptions, without
changing its contents.
- Around line 233-234: Update the padding documentation in the attention SDPA
backward section to use the public wrapper parameter names seq_kv_lens and
seq_q_lens instead of seq_len_kv and seq_len_q, preserving the existing
required/optional and mask-composition descriptions.
- Around line 237-240: Update the GQA workspace description to size the dk_ws
and dv_ws partial buffers using padded head dimension D_padded
(head_dim_padded), not logical D. Alternatively, direct callers to
scratch_workspace_bytes() for the exact workspace requirement, while preserving
the existing element-count and layout details.

In `@python/cudnn/sdpa/bwd/api_dsl.py`:
- Around line 322-336: Update _checked_seq_lens to validate that seq_lens is on
the same CUDA device expected by the SDPA backward kernel before returning its
flattened view. Preserve the existing dtype, element-count, contiguity, and
reshape validations, and raise the established validation error with the tensor
name and device details when the check fails.
🪄 Autofix

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: 71640798-cba8-4ad3-8f02-631f06daf8ff

📥 Commits

Reviewing files that changed from the base of the PR and between ba2e72d and 3048a00.

📒 Files selected for processing (7)
  • docs/fe-oss-apis/attention/sdpa_bwd_sm120.md
  • python/cudnn/sdpa/bwd/api_dsl.py
  • python/cudnn/sdpa/bwd/config_sm120.py
  • python/cudnn/sdpa/bwd/engines.py
  • python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py
  • test/python/sdpa/frost/test_sdpa_bwd_dsl_sm120.py
  • test/python/sdpa/frost/test_sdpa_graph_analyzer.py

Comment thread docs/fe-oss-apis/attention/sdpa_bwd_sm120.md Outdated
Comment thread docs/fe-oss-apis/attention/sdpa_bwd_sm120.md Outdated
Comment thread docs/fe-oss-apis/attention/sdpa_bwd_sm120.md Outdated
Comment thread python/cudnn/sdpa/bwd/api_dsl.py
@Adnios

Adnios commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

@cudnn-ci-bot run frost

@cudnn-ci-bot

Copy link
Copy Markdown

🚀 Running mirror pipeline

Branch: cudnn-gh/pr-557-57ebcc6
Pipeline: 62279162
Targets: frost

@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: 4

🤖 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 `@python/cudnn/sdpa/bwd/api_dsl.py`:
- Around line 275-286: The sink descriptor validation near lines 275-286 must
require every non-None sink descriptor to use self.q_desc.device, while
preserving the existing shape, contiguity, and dtype checks. In
python/cudnn/sdpa/bwd/api_dsl.py lines 579-584, update the cache key
construction to include _tensor_signature(sink_token) whenever sink_token is
present, so cached APIs distinguish sink dtype, stride, and device; both sites
require direct changes.

In `@python/cudnn/sdpa/bwd/engines.py`:
- Around line 341-342: Update the lowering around sample_dsink and
check_support() to validate dSink_token’s dtype before kernel execution. Ensure
non-float32 facts.dsink_t descriptors are rejected, either by adding the
corresponding graph dtype check or by deriving sample_dsink’s dtype from
facts.dsink_t while preserving the fp32 kernel requirement.

In `@python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py`:
- Around line 1655-1659: Update _dsink_kernel to accept optional seq_q_lens and
skip rows where q >= seq_q_lens[batch] before accumulating dSink. Propagate the
same optional specialization through the dSink compile and launch signatures,
preserving existing behavior when sequence lengths are absent.

In `@test/python/sdpa/frost/test_sdpa_graph_analyzer.py`:
- Around line 1029-1035: Add the pytest.mark.L0 decorator before
test_bwd_probe_accepts_right_band_widening and test_bwd_probe_accepts_sink in
test/python/sdpa/frost/test_sdpa_graph_analyzer.py at lines 1029-1035 and
1059-1064, respectively; no other changes are needed.
🪄 Autofix

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: 60dd6c33-1628-476b-ac02-6962ea19882a

📥 Commits

Reviewing files that changed from the base of the PR and between 57ebcc6 and 30de426.

📒 Files selected for processing (7)
  • docs/fe-oss-apis/attention/sdpa_bwd_sm120.md
  • python/cudnn/sdpa/bwd/api_dsl.py
  • python/cudnn/sdpa/bwd/config_sm120.py
  • python/cudnn/sdpa/bwd/engines.py
  • python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py
  • test/python/sdpa/frost/test_sdpa_bwd_dsl_sm120.py
  • test/python/sdpa/frost/test_sdpa_graph_analyzer.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/fe-oss-apis/attention/sdpa_bwd_sm120.md

Comment thread python/cudnn/sdpa/bwd/api_dsl.py
Comment thread python/cudnn/sdpa/bwd/engines.py Outdated
Comment thread python/cudnn/sdpa/bwd/kernels/bprop_f16_sm120.py
Comment thread test/python/sdpa/frost/test_sdpa_graph_analyzer.py
@Adnios Adnios changed the title frost(sdpa): GQA/MQA and padding mask (per-batch seq lens) for the SM120 f16 backward frost(sdpa): GQA/MQA, padding mask and sink support for the SM120 f16 backward Aug 13, 2026
@Adnios Adnios changed the title frost(sdpa): GQA/MQA, padding mask and sink support for the SM120 f16 backward frost(sdpa): GQA/MQA, padding mask, right-band widening, and sink-token gradients for the SM120 f16 backward Aug 13, 2026
@Adnios
Adnios marked this pull request as ready for review August 13, 2026 06:58
@Adnios

Adnios commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

@cudnn-ci-bot run frost

1 similar comment
@Adnios

Adnios commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

@cudnn-ci-bot run frost

@cudnn-ci-bot

Copy link
Copy Markdown

🚀 Running mirror pipeline

Branch: cudnn-gh/pr-557-fa63cb2
Pipeline: 62477080
Targets: frost

@vedaanta
vedaanta merged commit f3dd34a into NVIDIA:develop Aug 13, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cat-feature Requests for new functionality, APIs, examples, or behavior improvements. mod-frost orig-nv-eng Reported or requested by NVIDIA engineering.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants