Skip to content

[2/2] Add TileLang fused DSA kernels support with THD and CP & Clean up - #5049

Merged
HollowMan6 merged 7 commits into
NVIDIA:mainfrom
HollowMan6:dsa_cp_thd_tilelang
Jul 24, 2026
Merged

[2/2] Add TileLang fused DSA kernels support with THD and CP & Clean up#5049
HollowMan6 merged 7 commits into
NVIDIA:mainfrom
HollowMan6:dsa_cp_thd_tilelang

Conversation

@HollowMan6

@HollowMan6 HollowMan6 commented May 29, 2026

Copy link
Copy Markdown
Contributor

What does this PR do ?

Closes #5703

This PR adds the TileLang implementation of the fused DSA operations.

⚠️ For major changes (either in lines of code or in its impact), please make sure to first share a design doc with the team. If you're unsure what's the best way to do so, contact the @mcore-oncall.

Main changes

  • Adds TileLang kernels for DSA indexer forward and backward.
  • Adds TileLang kernels for absorbed sparse-MLA forward and backward.
  • Adds Python wrapper code under megatron/core/transformer/experimental_attention_variant/ops/.

Packed THD and CP behavior

The TileLang path uses the metadata and bounds produced by PR 1. When the current TileLang kernel path cannot safely handle a packed THD or CP case, DSA falls back to the unfused implementation instead of changing semantics. This keeps packed-sequence and context-parallel correctness owned by the common DSA path while allowing supported dense cases to use TileLang.

Contribution process

flowchart LR
    A[Pre-checks] --> B[PR Tests]
    subgraph Code Review/Approval
        C1[Expert Review] --> C2[Final Review]
    end
    B --> C1
    C2 --> D[Merge]
Loading

Pre-checks

  • I want this PR in a versioned release and have added the appropriate Milestone (e.g., Core 0.8)
  • I have added relevant unit tests
  • I have added relevant functional tests
  • I have added proper typing to my code Typing guidelines
  • I have added relevant documentation
  • I have run the autoformatter.sh on my PR

Code review

The following process is enforced via the CODEOWNERS file for changes into megatron/core. For changes outside of megatron/core, it is up to the PR author whether or not to tag the Final Reviewer team.

For MRs into `main` branch

Feel free to message or comment the @mcore-oncall to help accelerate your merge into main. The less complex your PR is, the faster it will be approved and merged!

(Step 1): Add PR label Expert Review

(Step 2): Collect the expert reviewers reviews

  1. Attach the Expert Review label when your PR is ready for review.
  2. GitHub auto-assigns expert reviewers based on your changes. They will get notified and pick up your PR soon.

⚠️ Only proceed to the next step once all reviewers have approved, merge-conflict are resolved and the CI is passing.
Final Review might get declined if these requirements are not fulfilled.

(Step 3): Final Review

  1. Add Final Review label
  2. GitHub auto-assigns final reviewers based on your changes. They will get notified and pick up your PR soon.

(Optional Step 4): Cherry-pick into release branch

If this PR also needs to be merged into core_r* release branches, after this PR has been merged, select Cherry-pick to open a new PR into the release branch.

For MRs into `dev` branch The proposed review process for `dev` branch is under active discussion.

MRs are mergable after one approval by either eharper@nvidia.com or zijiey@nvidia.com.

Merging your PR

Any member of core-adlr and core-nemo will be able to merge your PR.

@copy-pr-bot

copy-pr-bot Bot commented May 29, 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.

@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch 6 times, most recently from c52cb66 to 51f051b Compare June 2, 2026 04:31
@HollowMan6
HollowMan6 marked this pull request as ready for review June 2, 2026 04:32
Copilot AI review requested due to automatic review settings June 2, 2026 04:32
@HollowMan6
HollowMan6 requested review from a team as code owners June 2, 2026 04:32

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds a TileLang-backed fused implementation for the experimental DSA attention variant (indexer + SparseMLA + optional streaming sparse-KL), along with a native PyTorch parity test.

Changes:

  • Introduces TileLang utility helpers (availability detection, no-op jit, and runtime guard).
  • Adds TileLang fused kernels for the sparse MLA forward/backward and indexer forward/backward, plus DSA hook glue.
  • Adds a unit test comparing TileLang-backed DSA against a native baseline for outputs and gradients.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
tests/unit_tests/transformer/experimental_attention_variant/test_dsa_tilelang_native_parity.py Adds parity test for TileLang vs native DSA outputs/grads across configs.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_utils.py Adds TileLang availability detection + no-op jit + explicit runtime requirement checks.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_sparse_mla_fwd.py Adds TileLang sparse MLA forward kernel + caching + padding/bucketing wrapper.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_sparse_mla_bwd.py Adds TileLang sparse MLA backward + preprocess/postprocess kernels + caching + padding/bucketing wrapper.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_indexer_fwd.py Adds TileLang fused indexer forward kernel + logits cleaning + caching.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_indexer_bwd.py Adds TileLang fused indexer backward kernel + caching + topk padding wrapper.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Adds TileLang-backed DSA hooks (topk, SparseMLA, streaming sparse-KL) + scratch buffer cache.
megatron/core/transformer/experimental_attention_variant/ops/sparse_mla.py Wraps TileLang sparse MLA fwd/bwd in a torch.autograd.Function.
megatron/core/transformer/experimental_attention_variant/ops/indexer.py Wraps TileLang indexer fwd/bwd in an autograd Function and exposes lighting_indexer.
megatron/core/transformer/experimental_attention_variant/dsa_tilelang_kernels.py Exposes TileLang hook entrypoints for the DSA backend integration.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated
@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch from 51f051b to 716a699 Compare June 2, 2026 05:03
@HollowMan6
HollowMan6 requested a review from Copilot June 2, 2026 05:06

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 8 comments.

Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated
@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch from 716a699 to 14807da Compare June 2, 2026 05:21
@HollowMan6
HollowMan6 requested a review from Copilot June 2, 2026 05:22

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 6 comments.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14807dae90

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated
@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch from 14807da to 953f210 Compare June 2, 2026 05:46
@HollowMan6
HollowMan6 requested a review from Copilot June 2, 2026 05:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 953f210933

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch from 953f210 to d4ed0ef Compare June 2, 2026 06:12
@HollowMan6
HollowMan6 requested a review from Copilot June 2, 2026 06:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Comment thread megatron/core/transformer/experimental_attention_variant/ops/tilelang_dsa.py Outdated
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd_tilelang branch 2 times, most recently from db0579b to ffe3a16 Compare June 2, 2026 06:25
@HollowMan6

Copy link
Copy Markdown
Contributor Author

/claude strict-review

@HollowMan6

Copy link
Copy Markdown
Contributor Author

@codex review

Signed-off-by: Hollow Man <hollowman@opensuse.org>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: fa3573d52a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

Strict review passed — no significant issues found. LGTM

Scope: 11 net-new files adding the TileLang fused DSA backend (indexer fwd/bwd, sparse-MLA fwd/bwd, indexer-loss KL kernels) plus Python wrappers under ops/, and 1 new unit-test file (1181 lines). No existing files are modified, so there is no checkpoint-format, default-value, or API-contract backward-compat surface at risk.

Verified correctness surfaces:

  • Autograd gradient ordering in IndexerFunction.backward correctly re-maps (grad_q, grad_w, grad_k)(grad_q, grad_k, grad_w, None×5) to match the 8 forward inputs.
  • SparseMLA small-head padding (pad→16, slice back, _zero_invalid_heads) prevents gradient leakage into padded heads (unit-tested).
  • Fused KL target/normalization matches the backend-neutral dsa_indexer_loss reference, including all-invalid/empty rows; TP async all-reduce double-buffering uses correct ping-pong slot ordering.
  • Bucket-padding in fwd/bwd interfaces is symmetric (pad → run → slice) with -1 sentinel fill.
  • Every unsupported case (non-bf16 dtype, unsupported head count, dim≠576/v_channels≠512, THD/CP the kernel can't handle) returns None and falls back to the unfused path — extensively guard-tested.

Compliance: No new parallel_state.get_*_group() reads in megatron/core; the TP group flows in via ProcessGroupCollection, per CLAUDE.md guidance.

Findings: CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 0.

Risk: Low. The change is additive, opt-in via dsa_kernel_backend="tilelang", with clean unfused fallbacks and strong unit coverage (including CUDA reference-match tests). Vendored kernel bodies carry clear upstream-provenance comments. Note the CUDA reference tests only exercise coverage where TileLang + a GPU are available in CI.

seen["use_relu"] = use_relu
return torch.arange(6, dtype=torch.float32).view(2, 3)

monkeypatch.setattr(indexer, "indexer_fwd_interface", fake_indexer_fwd_interface)

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.

Are the TileLang indexer forward/backward kernels tested anywhere? we should add numerical-parity tests against the pytorch for both forward and backward, similar to the coverage for the cudnn kernels.

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.

now added real TileLang numerical-parity tests

from megatron.core.transformer.transformer_config import TransformerConfig


def run_fused_qk_topk(

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.

Is this a pure wrapper around tilelang_dsa.run_fused_qk_topk?

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.

Yes, It forwards the backend inputs and converts TileLang’s indices-only return value to the common DSA backend contract (topk_indices, topk_length), with topk_length=None

return sanitized_indices, topk_scores


def _build_packed_cp_indexer_inputs(

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.

The multi-sequence packed-CP branch duplicates the segment-length, cumulative-offset, and source_indices construction in _indexer_topk_multi_packed_cp_thd. Could we extract that backend-neutral layout construction into dsa_layout.py and let TileLang and cuDNN consume the same metadata? The kernel invocation and bounds/remapping can remain backend-specific, but the packed THD layout should have one authoritative implementation.

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.

I extracted the backend-neutral packed-CP metadata construction into dsa_layout.build_packed_cp_indexer_layout. Both cuDNN and TileLang now consume the same segment lengths, cumulative offsets, key starts, and source-index mapping. Kernel invocation, bounds handling, and result remapping remain backend-specific.

)


def _canonicalize_topk_scores_for_tp_reduce(

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.

Mostly to the sort/gather/mask logic in _sort_valid_topk_indices_and_scores_by_index. This ordering is backend-neutral and correctness-critical. The only difference seems to be: TileLang uses -1 sentinels. cuDNN uses a compact prefix described by topk_length. Could we move it into a shared top-k/masking helper that accepts an explicit validity mask.?

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.

I moved the common sort/gather/mask behavior into dsa_masking.sort_topk_by_index, which accepts an explicit validity mask. TileLang supplies indices >= 0, while cuDNN supplies validity derived from its compact-prefix topk_length, preserving each backend’s representation without duplicating the ordering semantics.

Signed-off-by: Hollow Man <hollowman@opensuse.org>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: cab7852c19

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@claude

claude Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Strict Review Summary

Reviewed all 14 changed files (~4.4k additions) for the TileLang fused DSA kernels, tracing dtype/gradient flow, TP reduction, packed-THD/CP layout remapping, and the availability-gated fallback contract.

Findings by severity:

  • CRITICAL: 0
  • IMPORTANT: 1
  • SUGGESTION: 1

Most impactful:

  • [IMPORTANT Performance] ops/tilelang_dsa.py: the PyTorch fallback _compute_topk_target_chunk_sum runs with autograd enabled over the main query/key activations, but the KL target is treated as a stop-gradient constant (the surrogate in _compute_sparse_topk_kl_chunk detaches it, matching bwd_fused_indexer_loss_naive). Wrapping the fallback target in torch.no_grad() avoids retaining that graph and building autograd metadata on an in-place-mutated scratch buffer. Affects only configs where the fused target kernel is unsupported.
  • [SUGGESTION Simplification] ops/indexer.py: ctx.topk/ctx.head_num are saved but never read in backward.

What's good:

  • Every fused entry point (fused_qk_topk_lighting, fused_sparse_mla_absorbed, streaming KL) has thorough shape/dtype/head-count guards and returns None to fall back to the unfused path rather than silently changing semantics — including the head-padding bounds analysis in _is_supported_sparse_mla_head_count and the packed-CP local_key_layout handling.
  • Process-group usage is compliant: passes ProcessGroupCollection/explicit groups via get_pg_size, no new direct parallel_state.get_*_group() reads in core library code.
  • Shared layout/masking logic was correctly factored into dsa_layout.build_packed_cp_indexer_layout and dsa_masking.sort_topk_by_index, and the refactor of the cuDNN path preserves behavior.
  • Extensive unit tests cover guard paths, sanitization, TP-reduce canonicalization, sentinel handling, and real-kernel parity (CUDA-gated).

Overall risk: LOW–MODERATE. The feature is experimental and fully gated behind availability + input guards with a correct unfused fallback, so blast radius on existing training runs is minimal. No correctness or backward-compatibility blockers found.

Comment thread megatron/core/transformer/experimental_attention_variant/ops/indexer.py Outdated
Signed-off-by: Hollow Man <hollowman@opensuse.org>
@HollowMan6

Copy link
Copy Markdown
Contributor Author

/claude strict-review

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

Strict review passed — no significant issues found. LGTM

I traced the correctness-critical paths in this PR:

  • Hook signature contract: The dsa_kernels dispatcher passes config as a keyword only to run_fused_qk_topk_with_loss; the TileLang wrapper's del config is intentional interface parity with the cuDNN backend (not a dead argument). The no-loss and absorbed-attention hooks line up with the dispatcher's call sites.
  • Process groups: No new direct parallel_state.get_*_group() reads in megatron/core — TP access threads through the injected ProcessGroupCollection (pg_collection.tp), consistent with repo guidance.
  • CP packed-THD segment remap: _build_packed_cp_indexer_inputs sanitizes in local segmented key space then remaps back to global int32 indices; the extracted build_packed_cp_indexer_layout is behavior-preserving vs. the deleted inline cuDNN logic (the sk % (2*cp_size) guard moved intact).
  • Scratch-buffer aliasing: The streaming-KL double buffer (two slots, chunk_id & 1) copies each target chunk into a slot before the shared kl_attn_chunk_sum buffer is reused, and consumes the pending chunk from the other slot — no stale aliasing.
  • SparseMLA head padding: _is_supported_sparse_mla_head_count correctly requires head_kv be a power-of-two ≥16 to match the kernel's unbounded padded-head indexing, with caller-side pad-then-slice; unsupported shapes decline to the unfused path.
  • TP score alignment: top-k slots are sorted by key index before slot-wise TP all-reduce.
  • Fallback safety: the entire path is gated on HAVE_TILELANG with graceful decline (return None) to the authoritative unfused reference implementation, and dtype boundaries (bf16 compute → fp32 accumulation) are explicit throughout.

Test coverage is thorough (~1300 lines exercising wrappers, masking, segment remap, head-mask helpers, scratch cache, and env parsing). No confirmed correctness, performance, or backward-compatibility defects.

Findings by severity — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 0. Overall risk: low (additive, behind a feature gate with an unfused fallback).

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30025819135

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30040566352

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30045776196

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30051554542

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30116068044

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/30117538144

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

Labels

Approved All necessary approvals have been made complexity: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Question about missing DSA fused backend modules: dsa_tilelang_kernels and dsa_cudnn_kernels

7 participants