Skip to content

[dsv4] Share sparse attention metadata and encapsulate index selection - #5722

Closed
sdmyzlp wants to merge 2 commits into
pytorch:mainfrom
sdmyzlp:dsv4-sparse-attn-cleanup
Closed

sdmyzlp wants to merge 2 commits into
pytorch:mainfrom
sdmyzlp:dsv4-sparse-attn-cleanup

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Summary (human-written)

Why

DeepSeek-V4 has three sparse-attention variants (sliding window, heavily compressed, compressed sparse) that share one metadata entry keyed by inner-attention class. Everything that depends on compress_ratio was therefore rebuilt inside each layer on every forward: the compressed offsets (cu_seqlens_k), the per-token document-local to pool-index base, the HCA [T, n_cmp] causal block mask, and the compressor's per-document group starts via searchsorted. The indexer also leaked its internals: attention.py called Indexer.select(idx_q, idx_k, idx_w, ...) on tensors the indexer had just computed, so the attention module owned a selection detail that belongs behind the indexer's module boundary.

Example. Compressed-sparse layer, before and after:

# before: attention.py, every CSA layer, every forward
idx_q, idx_k, idx_w = self.indexer(x, qr, positions=positions, cu_seqlens=cu_seqlens)
cmp_topk, topk_scores = Indexer.select(idx_q, idx_k, idx_w, max_seqlen=..., ratio=4, topk=..., cu_seqlens=...)
cu_seqlens_k = compressed_cu_seqlens(cu_seqlens, self.compress_ratio)   # per layer

# after: metadata is built once per variant, the selector owns its inputs
metadata = attention_config.build_attention_metadata(positions, ...)     # once per variant
topk_indices, topk_scores = self.indexer(x, qr, positions=positions, attention_metadata=metadata, ...)

SparseAttentionMetadata carries cu_seq_cmp, cmp_base, causal_cmp, and the compressor's group_start / group_first / group_position, so no layer derives them again. With align_documents, the compressor regroups the packed stream instead of gathering per document.

What changed

  • models/deepseek_v4/metadata.py (new): SparseAttentionMetadata (a NamedTuple wrapping VarlenAttentionMetadata) and build_sparse_metadata, which computes the geometry once per variant; compressed_cu_seqlens moves here.
  • models/deepseek_v4/attention.py: DSV4InnerAttention.Config.build_attention_metadata returns the variant metadata (plain varlen for sliding window). The inner attention consumes cu_seq_cmp / causal_cmp from it; HCA drops its per-layer mask construction. CompressedSparseAttention.forward now takes topk_indices (and keyword topk_scores) instead of the indexer's idx_q / idx_k / idx_w.
  • models/deepseek_v4/compressor.py: InnerIndexer is a module with its own local-SPMD boundary; Indexer.forward returns (topk_indices, topk_scores), so the attention module never sees indexer internals. The compressor and the auxiliary loss take attention_metadata and use its cmp_base / group_* fields.
  • models/deepseek_v4/model.py: align_documents (off by default) with a document_alignment property (the lcm of the layer compression ratios); __post_init__ validates the per-variant geometry and propagates the alignment to the inner-attention configs; preprocess_inputs annotates the metadata container, which annotate_input_spmd_types does not visit.
  • models/deepseek_v4/sharding.py, flavors.py: the 3-D attention activation placement for q, topk_indices / topk_scores in the kernel boundary, and a separate inner_indexer sharding config.
  • torchtitan_recipes/tests/models/deepseek_v4.py: align_documents flag on the debug/flash/pro factories; a trainer config hook enables the data-side alignment from [data] Add opt-in per-sample padding for packed segments #6059.
  • Tests: new test_sparse_metadata.py; the DSA, indexer-loss and GPU attention tests now drive the new interfaces.

Mechanical: none.

Numerics / performance

Refactor, no intended numerics change. The new test_cached_compression_matches_legacy_forward_and_backward keeps the old cu_seqlens path as the oracle and asserts the metadata path is bitwise equal in forward and backward (rtol=0, atol=0) for both ratios and both aligned and unaligned layouts. align_documents defaults to off, so existing runs keep the current packing.

The per-layer [T, n_cmp] mask and the per-forward searchsorted calls are gone; no end-to-end throughput claim is made here.

Testing

pytest tests/unit_tests/cpu/models/deepseek_v4 tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py -q   # 38 passed
pytest tests/unit_tests/cpu/components/data tests/unit_tests/cpu/models/test_state_dict_adapter.py::DeepSeekV4StateDictAdapterTest tests/unit_tests/cpu/recipes/test_deepseek_v4_dist_muon.py -q  # 245 passed

New coverage in test_sparse_metadata.py:

  • test_cached_compression_matches_legacy_forward_and_backward catches a metadata-derived group start or cmp_base that disagrees with the per-document path, in gradients as well as activations.
  • test_aligned_reshape_matches_general_compressor catches the aligned reshape path diverging from the general compressor for the same packed input.
  • test_alignment_rejects_unaligned_documents catches a document boundary that the configured alignment does not divide.
  • test_variant_geometry_must_be_uniform catches two layers that claim one variant but disagree on compress_ratio / window_size, which would make the shared metadata wrong for one of them.
  • test_hca_width_is_bounded_by_document_length pins the causal mask width to the longest document rather than the packed length.
  • test_padding_does_not_change_real_token_attention catches a padded tail that changes the output on the real tokens.

Known issues / follow-ups

  • Stacked on [data] Add opt-in per-sample padding for packed segments #6059: this branch contains that PR's commit as the first commit; review the second commit only.
  • Context parallel is not supported for DeepSeek-V4 yet. The metadata is DP-varying and CP-replicated (see its docstring); a CP variant will have to shard or permute it.
  • align_documents is opt-in; enabling it by default for the DeepSeek-V4 recipes is a separate decision.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 31, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 31, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-attn-cleanup branch 2 times, most recently from ad6d069 to b7320bf Compare October 31, 2026 03:25
@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-attn-cleanup branch 2 times, most recently from 0250162 to ec2a692 Compare November 5, 2026 08:42
Packing concatenates documents of arbitrary length, so compression groups
(and any consumer that works on document-sized blocks) can straddle a
document boundary. Add `document_alignment` to the data loader config: the
document-aware packer pads each emitted segment up to a multiple of it,
continuing positions through the padded tail so the tail belongs to the
same segment.

The alignment must divide `max_context_length` and
`num_tokens_per_microbatch`, which keeps every emitted segment aligned
without changing the packers' splitting rules. Alignment is opt-in and
currently only the document-aware packer supports it.
The three DeepSeek-V4 sparse-attention variants each rebuilt the same
compression geometry per layer: `cu_seqlens_k`, the per-token doc-local to
pool-index base, the HCA causal block mask, and the compressor's group
starts. The indexer also leaked its internal `idx_q / idx_k / idx_w` to the
attention module, which called `Indexer.select` itself.

Build one `SparseAttentionMetadata` per variant in
`build_attention_metadata` and pass it to the inner attention, compressor,
indexer and auxiliary loss. `InnerIndexer` owns the selection behind its own
module boundary and returns `(topk_indices, topk_scores)`, so the attention
module no longer touches indexer internals. With `align_documents`, the
compressor regroups the packed stream instead of gathering per document.
@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-attn-cleanup branch from ec2a692 to 3059730 Compare November 12, 2026 12:25
@sdmyzlp sdmyzlp changed the title [dsv4] Build sparse-attention metadata per layer variant; merge the inner-attention classes [dsv4] Share sparse attention metadata and encapsulate index selection Nov 12, 2026
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this stacked branch. Its content is now carried by three decoupled PRs:

Thanks for the reviews and discussion here.

@sdmyzlp sdmyzlp closed this Nov 19, 2026
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Nov 19, 2026
The indexer returned its internal idx_q / idx_k / idx_w to the attention module, which called Indexer.select itself; the attention module therefore owned a selection detail that belongs behind the indexer's module boundary.

Move the selection into InnerIndexer.forward behind a local-SPMD boundary, have Indexer.forward return (topk_indices, topk_scores), and pass those to CompressedSparseAttention. The sharding configs follow the new boundary and the flavors build the InnerIndexer. This is the indexer half of pytorch#5722, decoupled from the metadata/alignment work; the interfaces still take cu_seqlens.

No intended numerics change: the selection code moves into InnerIndexer.forward and the existing selection tests exercise it through the module.
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Nov 19, 2026
The indexer returned its internal idx_q / idx_k / idx_w to the attention module, which called Indexer.select itself; the attention module therefore owned a selection detail that belongs behind the indexer's module boundary.

Move the selection into the stateless InnerIndexer module, have Indexer.forward return (topk_indices, topk_scores), and pass those to CompressedSparseAttention. The inner-attention sharding config now declares topk_indices / topk_scores; a separate InnerIndexer sharding boundary is deferred until the module needs state. This is the indexer half of pytorch#5722, decoupled from the metadata/alignment work; the interfaces still take cu_seqlens.

No intended numerics change: the selection code moves into InnerIndexer.forward and the existing selection tests exercise it through the module.
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Nov 22, 2026
Indexer.select used to be a static method called by
CompressedSparseAttention, so the attention kernel owned the selection
detail and the indexer returned its raw q/k/weights. Move selection into
an InnerIndexer submodule owned by Indexer; Indexer.forward now returns
(topk_indices, topk_scores), and the inner-attention kernel takes those
tensors instead.

InnerIndexer reads attention_metadata.max_k, so packed documents keep the
per-document selection width. When the auxiliary loss is inactive,
Indexer.forward runs under no_grad and InnerIndexer returns right after
top-k selection with an empty [T, 0] score tensor: no selected-key gather
or dot products are built. Both outputs are TP-replicated, and the
local-SPMD boundary declares the same placement.

This is the indexer half of pytorch#5722, built on the shared attention metadata
from pytorch#6181. Tests cover the selection width for packed and empty pools,
the no-rescoring eval path, the CSA kernel output, and the DSV4 recipe and
state-dict adapter.
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Nov 22, 2026
Indexer.select used to be a static method called by
CompressedSparseAttention, so the attention kernel owned the selection
detail and the indexer returned its raw q/k/weights. Move selection into
an InnerIndexer submodule owned by Indexer; Indexer.forward now returns
(topk_indices, topk_scores), and the inner-attention kernel takes those
tensors instead.

InnerIndexer reads attention_metadata.max_k, so packed documents keep the
per-document selection width. When the auxiliary loss is inactive,
Indexer.forward runs under no_grad and InnerIndexer returns right after
top-k selection with an empty [T, 0] score tensor: no selected-key gather
or dot products are built. Both outputs are TP-replicated, and the
local-SPMD boundary declares the same placement.

This is the indexer half of pytorch#5722, built on the shared attention metadata
from pytorch#6181. Tests cover the selection width for packed and empty pools,
the no-rescoring eval path, the CSA kernel output, and the DSV4 recipe and
state-dict adapter.
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 23, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant