Skip to content

[1/2] Enable DSA CP, THD with absorbed MLA - #3674

Closed
HollowMan6 wants to merge 2 commits into
NVIDIA:mainfrom
HollowMan6:dsa_cp_thd
Closed

[1/2] Enable DSA CP, THD with absorbed MLA#3674
HollowMan6 wants to merge 2 commits into
NVIDIA:mainfrom
HollowMan6:dsa_cp_thd

Conversation

@HollowMan6

@HollowMan6 HollowMan6 commented Mar 3, 2026

Copy link
Copy Markdown
Contributor

What does this PR do ?

This PR refactors the DSv3.2 DSA attention implementation so the matrix-absorbed MLA structure and DSA control flow are backend-neutral. It does not add a TileLang or cuDNN kernel; it creates the shared foundation that those kernels can plug into later.

Need together with #3026

⚠️ 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.

Background

DSA uses an indexer to choose the top-k key/value tokens for each query token, then runs sparse attention over those selected tokens. DSv3.2 also uses matrix absorption for MLA: the key up-projection is absorbed into the query side, and the value up-projection is applied after sparse attention. That absorbed structure is specific to this experimental attention path, so keeping it inside the already large generic multi_latent_attention.py makes the original MLA implementation harder to maintain.

This PR separates that DSv3.2-specific absorbed MLA path from the generic MLA file and reorganizes dsa.py around a small set of overridable fused-kernel hooks. The default behavior remains the PyTorch/MCore implementation; backend-specific kernels are intentionally left to follow-up PRs.

Main changes

  • Moves the DSv3.2 absorbed MLA implementation into megatron/core/transformer/experimental_attention_variant/absorbed_mla.py.
  • Removes the DSv3.2 matrix-absorption logic from megatron/core/transformer/multi_latent_attention.py.
  • Refactors DSA so backend kernels only need to implement three hook points:
    • qk score computation plus top-k selection,
    • qk score computation plus top-k selection plus indexer loss,
    • absorbed sparse attention over the selected key/value tokens.
  • Preserves the unfused PyTorch path as the default implementation.
  • Adds common metadata handling needed by any future fused backend, including packed-sequence and context-parallel masking.

Packed THD and CP support

  • Packed THD means the attention input is represented as packed tokens with cumulative sequence lengths instead of a dense [sequence, batch] layout. This PR builds masks from the packed sequence metadata so DSA top-k selection and sparse attention do not attend across packed sequence boundaries.
  • CP means context parallelism. For allgather CP, each rank has local query tokens but attends over gathered key/value tokens. This PR maps local query tokens and gathered key/value tokens back to global token positions before applying causal masks.
  • The CP logic covers the zigzag local-token layout used by MCore allgather CP, reorders gathered key/value tokens into global order when needed, and handles uneven per-rank query lengths.

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.

@HollowMan6
HollowMan6 requested a review from a team as a code owner March 3, 2026 10:15
Copilot AI review requested due to automatic review settings March 3, 2026 10:15
@HollowMan6
HollowMan6 requested a review from a team as a code owner March 3, 2026 10:15
@copy-pr-bot

copy-pr-bot Bot commented Mar 3, 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.

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

This PR extends the experimental DSAttention (DSA) path to support context parallelism (allgather CP) and packed THD masking, adds an “absorbed MLA” integration path, and introduces TileLang-based fused kernels (indexer + sparse MLA) with fallbacks and expanded unit coverage.

Changes:

  • Enable DSAttention CP allgather masking and packed THD (varlen) masking, including sparse-KL streaming for indexer loss.
  • Integrate absorbed-MLA tensor rewrite in MultiLatentAttention and route absorbed execution through DSAttention (with optional fused SparseMLA).
  • Add TileLang fused kernels/interfaces for indexer and sparse MLA, plus extensive new unit tests for CP/THD/absorbed parity and fused plumbing.

Reviewed changes

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

Show a summary per file
File Description
tests/unit_tests/transformer/test_attention_variant_dsa.py Adds coverage for CP layout helpers, packed THD varlen masking parity, fused indexer loop behavior, streaming sparse-KL, and absorbed parity.
megatron/core/transformer/transformer_config.py Removes the config-time guard that previously disallowed DSA with context parallelism.
megatron/core/transformer/multi_latent_attention.py Adds absorbed MLA tensor rewrite and passes position_ids/up_v_weight into DSA for CP + absorbed execution.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_sparse_mla_fwd.py New TileLang sparse-MLA forward kernel + Python interface.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_sparse_mla_bwd.py New TileLang sparse-MLA backward kernels + Python interface.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_indexer_fwd.py New TileLang fused indexer forward kernel + logits “cleaning” kernel.
megatron/core/transformer/experimental_attention_variant/ops/tilelang_indexer_bwd.py New TileLang fused indexer backward kernel + Python interface.
megatron/core/transformer/experimental_attention_variant/ops/sparse_mla.py Autograd wrapper around TileLang sparse-MLA forward/backward.
megatron/core/transformer/experimental_attention_variant/ops/indexer.py Autograd wrapper around TileLang indexer forward/backward and a helper for extracting top-k scores.
megatron/core/transformer/experimental_attention_variant/dsa.py Core DSA updates: CP position/masking helpers, varlen bounds, fused top-k + streaming sparse-KL, scratch caching, absorbed sparse attention routing, and updated loss/masking plumbing.

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

Comment thread megatron/core/transformer/experimental_attention_variant/ops/indexer.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/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: e0d5681007

ℹ️ 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/indexer.py Outdated
@Phlip79

Phlip79 commented Mar 4, 2026

Copy link
Copy Markdown
Member

We are changing our review process and marking all open, unlabeled PRs as draft. This change will go in effect starting once #3659 is merged.

Moving forward, all PRs will be required to start as draft PRs. If you wish to get your PR merged, mark your PR as “Ready for review”. Read more about the new process at submit.md.

@Phlip79
Phlip79 marked this pull request as draft March 4, 2026 23:44
@HollowMan6
HollowMan6 marked this pull request as ready for review March 5, 2026 19:58

@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: 58df45053a

ℹ️ 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".

@chtruong814 chtruong814 added the needs-follow-up Issue needs follow-up label Mar 7, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the Final Review PR is in the "final review" stage label Mar 9, 2026
@HollowMan6
HollowMan6 force-pushed the dsa_cp_thd branch 3 times, most recently from 291e439 to 0c51ebe Compare March 16, 2026 18:34
@chtruong814 chtruong814 added needs-follow-up Issue needs follow-up and removed needs-follow-up Issue needs follow-up labels Mar 24, 2026
@chtruong814 chtruong814 added needs-follow-up Issue needs follow-up and removed needs-follow-up Issue needs follow-up labels Apr 4, 2026
@HollowMan6
HollowMan6 requested a review from a team as a code owner April 21, 2026 13:08
@HollowMan6

Copy link
Copy Markdown
Contributor Author

@codex review

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 15 out of 15 changed files in this pull request and generated 8 comments.

Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/pipeline_parallel/schedules.py Outdated
Comment thread megatron/core/transformer/transformer_config.py
Comment thread megatron/core/transformer/experimental_attention_variant/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: e04b1b44cc

ℹ️ 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

Copy link
Copy Markdown
Contributor Author

@codex review

@HollowMan6
HollowMan6 requested a review from Copilot June 2, 2026 06:16

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 15 out of 15 changed files in this pull request and generated 10 comments.

Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/pipeline_parallel/schedules.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
Comment thread megatron/core/models/common/embeddings/rope_utils.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/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: 8a3e5ae2f1

ℹ️ 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/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: 774df97500

ℹ️ 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/models/hybrid/hybrid_layer_specs.py Outdated
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

ℹ️ 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".

@greptile-apps

greptile-apps Bot commented Jun 2, 2026

Copy link
Copy Markdown

Greptile Summary

This PR adds Context Parallelism (allgather) and packed THD format support to DeepSeek Sparse Attention (DSA), along with absorbed Matrix-Latent Attention (MLA) integration. It introduces new layout helpers (dsa_layout.py), refactors the absorbed MLA forward pass into a dedicated module, adds backend-neutral fused kernel hooks, and wires the DSA indexer auxiliary loss into the pipeline schedule.

  • DSA CP + THD: Adds zigzag and packed-THD position/reorder utilities; CP now works with cp_comm_type=allgather by gathering and reordering KV tensors using pre-built permutation indices.
  • Absorbed MLA refactor: Extracts AbsorbedMLASelfAttention into its own file; adds _unfused_absorbed_dsa_fn that computes QK scores and applies the V up-projection after sparse gather.
  • Loss scale integration: _get_experimental_attention_variant_loss_scale_func in schedules.py attaches DSAIndexerLossAutoScaler.set_loss_scale consistently with MoE/MTP auxiliary loss patterns.

Confidence Score: 4/5

PR is mostly safe but contains a P1 crash bug in the absorbed MLA shape assertion that will always fire for any TP > 1 configuration.

The rope_utils.py fixes are correct, the CP layout and masking logic is sound, and the loss-scale integration is clean. The single P1 issue (incorrect TP shape assertion in absorbed_mla.py) would cause an unconditional crash for any TP > 1 run, which must be fixed before merging. Everything else is P2 or lower.

megatron/core/transformer/experimental_attention_variant/absorbed_mla.py — shape assertion on line 852 must be corrected before merging.

Important Files Changed

Filename Overview
megatron/core/transformer/experimental_attention_variant/absorbed_mla.py Extracts AbsorbedMLASelfAttention; contains a P1 shape assertion that always fires for TP > 1 + SP.
megatron/core/transformer/experimental_attention_variant/dsa.py Main DSA forward refactored with absorbed MLA, CP key gathering, and THD masking; per-forward all_gather for validation is a throughput concern.
megatron/core/transformer/experimental_attention_variant/dsa_kernels.py Backend-neutral dispatch for fused kernels; fused hook signature missing mask/varlen params needed by future backends.
megatron/core/transformer/experimental_attention_variant/dsa_layout.py New CP position/reorder utilities for zigzag and packed THD layouts; logic verified correct.
megatron/core/transformer/experimental_attention_variant/dsa_masking.py Masking helpers for sparse DSA attention; causal mask, varlen bounds, topk scatter all verified correct.
megatron/core/models/common/embeddings/rope_utils.py Fixes broken return paths in _apply_rotary_pos_emb_thd; both CASE 1 and CASE 2 now return correctly.
megatron/core/pipeline_parallel/schedules.py Wires DSA indexer loss scale into forward_step_calc_loss consistently with MoE/MTP patterns.
megatron/core/transformer/transformer_config.py Adds new DSA config fields and removes the CP size==1 restriction for DSA; allgather-only validation added.

Sequence Diagram

sequenceDiagram
    participant AML as AbsorbedMLASelfAttention
    participant DSA as DSAttention
    participant LAY as dsa_layout
    participant MSK as dsa_masking
    participant KRN as dsa_kernels

    AML->>AML: project Q, compress KV
    AML->>DSA: forward(q, k, v, packed_seq_params, up_v_weight)
    DSA->>LAY: "get_cp_positions_from_layout / build_packed_*"
    LAY-->>DSA: query_pos, key_pos / kv_reorder_idx
    DSA->>DSA: all_gather KV (CP allgather)
    DSA->>MSK: build_dsattention_forward_mask
    MSK-->>DSA: index_mask, varlen bounds
    DSA->>KRN: run_fused_qk_topk_with_loss (→ None, unfused fallback)
    DSA->>DSA: _unfused_absorbed_dsa_fn: QK scores → topk → sparse gather
    DSA->>DSA: einsum V up-projection (up_v_weight)
    DSA-->>AML: core_attn_out [sq, b, np, v_channels]
    AML->>AML: _apply_absorbed_v_up_projection → output projection
Loading

Reviews (4): Last reviewed commit: "Address review issue" | Re-trigger Greptile

Comment thread megatron/core/models/common/embeddings/rope_utils.py Outdated
Comment thread megatron/core/transformer/experimental_attention_variant/dsa.py Outdated
@HollowMan6

Copy link
Copy Markdown
Contributor Author

@greptileai review

Copy link
Copy Markdown
Contributor Author

Split draft PRs opened to reduce review scope:

I left this original PR branch unchanged.

Signed-off-by: Hollow Man <hollowman@opensuse.org>
Signed-off-by: Hollow Man <hollowman@opensuse.org>
@HollowMan6

Copy link
Copy Markdown
Contributor Author

Close as superseded by split PRs: #3674 (comment)

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.

9 participants