Skip to content

[dsv4] Build sparse-attention geometry once per variant - #6181

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
sdmyzlp:dsv4-sparse-metadata-clean
Nov 19, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
sdmyzlp:dsv4-sparse-metadata-clean

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary (human-written)

  1. Every compress_ratio-derived quantity — compressed pool offsets, compressor group indices, and the heavily compressed variant's causal mask — is now computed once per variant in build_attention_metadata, instead of being rebuilt inside every layer on every forward.
  2. The layer and indexer interfaces take attention_metadata instead of cu_seqlens, so an overriding InnerAttention can pair its own build_attention_metadata with its consumers and have the produced metadata flow to them automatically.

Why

All sparse-attention layers share one metadata entry per variant, yet each layer still rebuilt everything derived from compress_ratio: the compressed pool offsets, the compressor's group indices, and the heavily compressed variant's causal mask.

before: each layer, each forward
    cu_seqlens_k = compressed_cu_seqlens(cu_seq_q, ratio)
    group_start / group_first = searchsorted + arange
    cmp_topk = where(cmp_s < (pos_t + 1) // ratio, ...)   # HCA only

after: once per variant in build_attention_metadata
    metadata.cu_seq_compressed / group_start / group_first / compressed_causal_indices

This is independent of the document-padding work (#6059); the geometry uses the current unaligned layout.

What changed

  • attention.py: DeepSeekV4CompressedSparseAttentionMetadata extends VarlenAttentionMetadata with cu_seq_compressed, group_start, group_first and compressed_causal_indices. The sliding-window builder creates the empty-compressed-pool default; HCA and CSA override it with their geometry, and HCA adds the causal mask. positions is required on DeepSeekV4Attention.forward.
  • compressor.py: Compressor, Indexer.forward, Indexer.select and SparseIndexerLoss take the metadata and unpack it internally; positions and metadata are required, and the per-layer searchsorted/arange work is gone.
  • model.py: forward requires attention metadata. The flavors derive attention, inner attention, compressors and indexer from one compress_ratio, so the shared metadata and its consumers agree by construction.

Numerics / performance

Cleanup, no intended numerics change: the packed-vs-per-document tests and the dense-masked GPU test still match. No step-time or memory measurement is claimed.

Testing

pytest -q tests/unit_tests/cpu/models/deepseek_v4 tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py — 27 passed, 3 CUDA cases skipped.

pytest -q tests/unit_tests/cpu/recipes/test_deepseek_v4_dist_muon.py tests/unit_tests/cpu/models/test_state_dict_adapter.py::DeepSeekV4StateDictAdapterTest — 10 passed.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 18, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 4a159e6 to 499d9d7 Compare November 18, 2026 14:53
@sdmyzlp
sdmyzlp marked this pull request as draft November 18, 2026 14:55
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch 4 times, most recently from decd512 to 76417b7 Compare November 18, 2026 17:08
@sdmyzlp
sdmyzlp marked this pull request as ready for review November 18, 2026 17:15
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 28s —— View job


Approve -- please address the items before merging (the GPU attention test this PR breaks, the over-broad window_size check, and a test that re-implements _causal_mask): 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.

Verdict: Approve -- please address the items below before merging. Moving the geometry derived from compress_ratio into the per-variant AttentionMetadataMap entry puts it in the layer that owns it. The remaining items are local edits: a GPU test this PR breaks, one over-broad validation, and one redundant test. A maintainer still needs to review.

What this PR does. DSV4 already shares one metadata entry per inner-attention class. This PR moves into that entry the values every layer used to recompute on each forward: the compressed-pool offsets, the compressor's group indices, and the HCA causal top-k mask. The compressor, indexer, indexer loss and inner attentions now take the metadata instead of cu_seqlens. The unpacked path (no metadata) is deleted from the compressor and the inner attentions, and the model raises if metadata is missing.

Example. On a debug model with 2 HCA layers and seq 4096, one forward:

before: each HCA layer: compressed_cu_seqlens + searchsorted + arange (compressor)
                        + repeat_interleave + where -> [4096, 32] mask (attention)
after:  HeavilyCompressedAttention.Config.build_attention_metadata runs once
        both layers read metadata.cu_seq_cmp / group_start / group_first / causal_cmp

Must fix

  1. tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py:103-113 (not in the diff) -- test_matches_dense_masked_attention still calls module(q, swa_k, attn_sink), module(q, swa_k, cmp_k, attn_sink) and module(..., attn_sink) without metadata. attention_metadata is now a required keyword-only argument, so all three cases fail with TypeError. This is the only dense-oracle check of HCA/CSA causality, and the PR's test run didn't include it because it only ran CPU suites. Fix: build module.config.build_attention_metadata(torch.arange(SEQLEN, device=device)) (or the equivalent) and pass it in, including to Indexer.select.
  2. torchtitan/models/deepseek_v4/model.py:219 -- the uniformity check includes window_size, which the shared metadata doesn't depend on, so it rejects configs that work (inline).
  3. tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_dsa.py:180-202 -- this test re-implements _causal_mask, so it is a tautology, and its docstring misdescribes the deleted formula. Delete it (inline).

Should consider

  • torchtitan/models/deepseek_v4/compressor.py:163 -- positions=None branch and the group_position field have no non-test caller (inline).
  • torchtitan/models/deepseek_v4/compressor.py:254 -- Indexer.select / compressed_gather_indices / _teacher keep a test-only None path (inline).
  • torchtitan/models/deepseek_v4/attention.py:150 -- the _gather_attn docstring still says "With packed cu_seqlens". _compressed_geometry and the new attention_metadata parameters in compressor.py have no type hints.

Questions

  • The motivation is per-layer recompute. Is there a measured step-time or memory difference on a real DSV4 config? The description doesn't say whether this is a perf change or only a cleanup.
Details
  • Numerics: the claim of no change is plausible. The compressor now always gathers by group_start, where the deleted no-metadata path used unflatten, but production always took the packed path, since Decoder.preprocess_inputs builds metadata whenever positions is present. The HCA mask now takes the in-document index from positions, while the old code took it from cu_seq_q. The two agree because the data pipeline canonicalizes positions to reset at every cu boundary (components/data/packing.py), and fixed-capacity overflow is caught by _assert_async in create_varlen_metadata_for_document.
  • CUDA graphs: the new dataclass is registered as a pytree, and all new tensors have static shapes (T // ratio, [T, min(T, max_k) // ratio]). No new host syncs.
  • PP: metadata already flows to every stage through model kwargs. CP is rejected for DSV4 at model.py:274.
  • Net LoC +127, of which about +75 is tests. Source changes: attention +47, compressor -18, model +20. Applying the should-consider items would remove group_position, the remaining None branches, and part of the new tests.

Not verified: GPU numerics and the GPU attention test (CPU-only review).

Comment thread torchtitan/models/deepseek_v4/model.py Outdated
geometry = {}
for layer in (*self.layers, *(self.mtp_layers or ())):
inner = layer.attention.inner_attention
key = (max(1, inner.compress_ratio), inner.window_size)

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.

window_size isn't part of the shared metadata. DSV4InnerAttention.Config.build_attention_metadata never reads self.window_size (the metadata's window_size is the varlen default), and _gather_attn uses the per-layer self.window_size (attention.py:164). So two layers of one variant with different windows are handled correctly per layer, and this check rejects a config that works. The same goes for SWA's compress_ratio: the SWA builder doesn't read it either. Key only on what the builder actually reads, which is compress_ratio for HCA/CSA. You can then drop the window_size half of test_variant_geometry_must_be_uniform.

Comment on lines +180 to +202
def test_hca_metadata_matches_the_per_layer_formula(self):
"""The precomputed mask is the deleted formula, and attention uses it."""
attention, attention_config = self._hca_attention()
lengths = [133, 7, 116]
positions = torch.cat([torch.arange(n) for n in lengths])
x = torch.randn(len(positions), attention_config.dim, dtype=torch.float64)
sparse = attention_config.inner_attention.build_attention_metadata(positions)

ratio = attention_config.compress_ratio
width = min(len(positions) // ratio, sparse.max_k // ratio)
candidates = torch.arange(width, dtype=torch.int32)
expected = torch.where(
candidates < ((positions + 1) // ratio)[:, None], candidates, -1
)
torch.testing.assert_close(sparse.causal_cmp, expected)

# A corrupted mask must change the output: an inert metadata field
# would leave attention unchanged.
with torch.no_grad():
output = attention(x, attention_metadata=sparse, positions=positions)
broken = replace(sparse, causal_cmp=torch.full_like(sparse.causal_cmp, -1))
differs = attention(x, attention_metadata=broken, positions=positions)
self.assertFalse(torch.allclose(output, differs))

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.

This test doesn't earn its place. expected is _causal_mask copied line for line, so it can only fail if someone edits one copy and not the other. Despite the docstring, it isn't "the deleted formula" either: the deleted code took the in-document index from cu_seqlens (arange - repeat_interleave(cu[:-1])), not from positions. The second half only checks that forward reads causal_cmp, which the code shows directly. The real causality invariant is already covered by the HCA case in tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py::test_matches_dense_masked_attention (dense oracle with causal_cmp_allowed), with packing covered by test_packed_attention_matches_each_document_alone. Suggest deleting this test and keeping that GPU test working (see the review body).

comp_positions = (
positions[start_G]
if positions is not None
else attention_metadata.group_position

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.

Metadata is now required, and it can only be built from positions. Every in-repo caller that passes metadata also passes positions: Decoder.preprocess_inputs builds both from input_dict["positions"]. That makes the positions is None branch, and therefore the group_position metadata field, reachable only from test_default_positions_match_explicit_positions. Consider making positions required here (and in DeepSeekV4Attention.forward, which already raises on missing metadata at the model level). Then delete group_position and that test.

ratio: int,
topk: int,
cu_seqlens: torch.Tensor | None = None,
attention_metadata=None,

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.

Compressor, the inner attentions and the model now require metadata, but Indexer.select, compressed_gather_indices and SparseIndexerLoss._teacher still accept None and keep a separate unpacked code path. After this PR, only tests reach that path (_metadata(None) in test_deepseek_v4_indexer_loss.py and the GPU attention test). Consider requiring metadata here too and typing it as DeepSeekV4CompressedSparseAttentionMetadata. That deletes the None branches and makes the unpacked test cases build single-document metadata.

@tianyu-l

Copy link
Copy Markdown
Contributor

@sdmyzlp please address claude review

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 76417b7 to fe38bec Compare November 19, 2026 01:22
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in fe38bec:

  • test_deepseek_v4_attention.py now builds build_attention_metadata(torch.arange(SEQLEN, device=device)) and passes it to the modules and Indexer.select (CPU params pass, CUDA params skip locally).
  • The variant check now keys only on compress_ratio; the window_size half and its test mutation are gone.
  • Removed the tautological HCA mask test.
  • positions is required in Compressor.forward; group_position and the positions is None branch are deleted.
  • Indexer.select, compressed_gather_indices and SparseIndexerLoss._teacher require metadata; the None branches and unpacked test paths are gone (tests build single-document metadata).
  • Added type hints to the metadata parameters and fixed the _gather_attn docstring.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from fe38bec to 5f2ef3a Compare November 19, 2026 01:26
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 18s —— View job


Approve -- please address the items before merging (earlier items are resolved; the CSA GPU oracle now gets CPU inputs with CUDA metadata, and the human-written summary is empty): 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.

Verdict: Approve -- please address the items below before merging. Every must-fix and should-consider item from the previous review is resolved at 5f2ef3a. The new commit leaves one GPU-test device mismatch and one description gap, both small local edits. A maintainer still needs to review.

What this PR does. It moves the geometry derived from compress_ratio into the per-variant metadata entry: compressed pool offsets, the compressor's group indices, and the HCA causal top-k mask. The compressor, indexer, indexer loss and inner attentions read that geometry instead of rebuilding it in every layer. Metadata and positions are now required, and the unpacked path is deleted.

Example.

before: Compressor.forward(x, positions, cu_seqlens)  -> searchsorted + arange per layer
        HCA.forward(...)                               -> repeat_interleave + where per layer
after:  HCA.Config.build_attention_metadata(positions) -> once per forward
        Compressor.forward(x, positions, attention_metadata)  # reads group_start / group_first
        HCA.forward(...)                                      # reads causal_cmp

Previous review

  • GPU attention test missing metadata: resolved for SWA/HCA. The CSA oracle call has a new device mismatch (below).
  • window_size in the uniformity check: resolved.
  • Tautological HCA mask test: removed.
  • positions=None / group_position: removed.
  • None branches in Indexer.select / compressed_gather_indices / _teacher: removed.
  • _gather_attn docstring and type hints: fixed.
  • Still open: whether this has a measured step-time or memory effect, or is only a cleanup.

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. Per CONTRIBUTING.md, the author fills it in; agents leave it.
  2. tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py:123 -- the CSA oracle Indexer.select gets CPU indexer inputs but CUDA metadata, so the CUDA case likely fails. Build CPU metadata for the oracle (inline, unverified).

Should consider

  • torchtitan/models/deepseek_v4/model.py:220 -- the new attention-vs-inner ratio check misses the coupling this PR creates: the compressor's ratio vs. the inner ratio used to build group_start (inline).
  • torchtitan/models/deepseek_v4/attention.py:419 -- positions still defaults to None, but the compressor now requires it (inline).
Details
  • _get_attention_metadata (decoder.py:504) iterates only over config.layers. An MTP layer whose variant doesn't appear in the main layers would get no metadata entry. This is pre-existing and not introduced here; the new __post_init__ check does cover mtp_layers for ratio agreement.
  • CUDA graphs and compile: the subclass is registered as a pytree, and the new tensors have static shapes (T // ratio, [T, min(T, max_k) // ratio]). In fixed-capacity mode, max_k is the Python int max_context_length. No new host syncs.
  • tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py is a model test that sits outside tests/unit_tests/cpu/models/deepseek_v4/. This is pre-existing; moving it fits a follow-up better than this PR.

Not verified: the CUDA parametrizations of test_matches_dense_masked_attention (no GPU here, and I couldn't read the attention-gym reference implementation to confirm the device error).

max_seqlen=SEQLEN,
ratio=ratio,
topk=TOPK,
attention_metadata=metadata,

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.

This oracle call uses the CPU copies idx_q, idx_k, idx_w (not idx), but metadata was built on device (line 83). In the cuda x csa case, lightning_indexer gets CPU queries with CUDA cu_seqlens / cu_seqlens_k, so the reference path will most likely fail with a device mismatch. Before this PR the oracle passed no offsets, so this didn't happen. The CPU case passes and the CUDA case was skipped locally, so this hasn't been run (unverified, no GPU here). Build CPU metadata for the oracle:

Suggested change
attention_metadata=metadata,
attention_metadata=config.build_attention_metadata(
torch.arange(SEQLEN)
),

Comment thread torchtitan/models/deepseek_v4/model.py Outdated
Comment on lines +220 to +223
if max(1, layer.attention.compress_ratio) != ratio:
raise ValueError(
"Attention and inner attention compression ratios must agree"
)

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.

This checks a different pair from the contract the PR adds. DeepSeekV4Attention.compress_ratio only selects a branch. The new coupling is that Compressor.forward gathers arange(self.compress_ratio) tokens from group_start, and group_start is built with the inner attention's ratio (attention.py:263, compressor.py:154,170). If compressor / compressor_128 / indexer.compressor disagree with inner_attention.compress_ratio, the groups silently overlap or skip tokens, and this check doesn't catch it. Before this PR the compressor derived its own geometry, so the mismatch couldn't happen. If this check stays, compare the compressor configs against inner.compress_ratio instead. The flavors set all of these from one value, so you could also drop it.

x,
attention_metadata=None,
attention_metadata: DeepSeekV4CompressedSparseAttentionMetadata,
positions=None,

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.

Compressor.forward and Indexer.forward now require positions (positions[start_G]), but the wrapper still defaults it to None. On HCA/CSA layers, a call without it fails with an opaque TypeError deep in the compressor instead of at the signature. Every caller already passes it, so make it required here, next to attention_metadata.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 5f2ef3a to 411ec7c Compare November 19, 2026 01:37
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 411ec7c:

  • The human-written summary is filled in (the two sentences now in the description).
  • The CSA GPU oracle now builds CPU metadata (config.build_attention_metadata(torch.arange(SEQLEN))) instead of reusing the device metadata.
  • DeepSeekV4Attention.forward requires positions.
  • The model config now checks the compressor(s) and indexer compressor against the inner-attention compress_ratio, with a test.
  • Perf question: this is a cleanup; the description makes no step-time or memory claim.

Pre-commit: all hooks pass except pyrefly's two pre-existing baseline errors in untouched files (distributed/fsdp.py, models/common/dist_moe/runtime.py). Tests: 28 passed, 3 CUDA cases skipped.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 43s —— View job


Approve -- every earlier item is resolved, and there's one optional simplification of the ratio checks: 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.

Verdict: Approve -- every item from the previous two reviews is resolved at 411ec7c. The new commit adds no new problems, only one optional simplification. A maintainer still needs to review.

What this PR does. It moves the geometry derived from compress_ratio into the per-variant DeepSeekV4CompressedSparseAttentionMetadata entry: compressed pool offsets, the compressor's group indices, and the HCA causal top-k mask. The compressor, indexer, indexer loss and inner attentions read that geometry instead of rebuilding it in every layer on every forward. Metadata and positions are now required everywhere, and the unpacked path is deleted.

Example.

before: each HCA layer, each forward
          Compressor:  compressed_cu_seqlens + searchsorted + arange
          HCA.forward: repeat_interleave + where -> [T, n_cmp] mask
after:  HeavilyCompressedAttention.Config.build_attention_metadata(positions), once
          Compressor reads metadata.group_start / group_first
          HCA.forward passes metadata.causal_cmp to _gather_attn

Previous review

  • Empty human-written summary: filled in.
  • CSA GPU oracle given CUDA metadata with CPU inputs: it now builds CPU metadata (test_deepseek_v4_attention.py:123).
  • Ratio check covering the wrong pair: the compressor(s) and the indexer compressor are now checked against inner.compress_ratio, with a test.
  • positions=None default on DeepSeekV4Attention.forward: now required.
  • Perf question: answered, this is a cleanup and makes no step-time or memory claim.

Should consider

  • torchtitan/models/deepseek_v4/model.py:217-244 -- the three ratio checks can be one set comparison whose error names the ratios that disagree (inline).
Details
  • Callsites: nothing outside torchtitan/models/deepseek_v4/ (RL, graph_trainer, experiments) imports DSV4 attention or the compressor, so requiring metadata and positions breaks no other in-repo caller.
  • MTP blocks (flavors.py:_make_mtp_inner_block) set compressor, compressor_128 and indexer to None and both ratios to 1, so they pass the new __post_init__.
  • The explicit Decoder.Config.__post_init__(self) call, rather than super(), is needed: zero-arg super() doesn't work in slots=True dataclasses.
  • Unchanged from the last review: _get_attention_metadata only iterates config.layers. This predates the PR and is harmless today, because MTP uses SWA, which the main layers also use.

Not verified: CUDA parametrizations of test_matches_dense_masked_attention (CPU-only review).

Comment thread torchtitan/models/deepseek_v4/model.py Outdated
Comment on lines +217 to +244
for layer in (*self.layers, *(self.mtp_layers or ())):
inner = layer.attention.inner_attention
ratio = max(1, inner.compress_ratio)
if max(1, layer.attention.compress_ratio) != ratio:
raise ValueError(
"Attention and inner attention compression ratios must agree"
)
for compressor in (
layer.attention.compressor,
layer.attention.compressor_128,
):
if (
compressor is not None
and max(1, compressor.compress_ratio) != ratio
):
raise ValueError(
"Compressor and inner attention compression ratios "
"must agree"
)
indexer = layer.attention.indexer
if (
indexer is not None
and max(1, indexer.compressor.compress_ratio) != ratio
):
raise ValueError(
"Indexer compressor and inner attention compression ratios "
"must agree"
)

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.

All three checks enforce the same invariant: every ratio on the layer agrees. They are split into three branches with three messages, and none of the messages names the layer or the values that disagree. One set comparison does the same job in about a third of the lines and gives a more useful error:

attention = layer.attention
inner = attention.inner_attention
ratios = [attention.compress_ratio, inner.compress_ratio]
ratios += [
    c.compress_ratio
    for c in (attention.compressor, attention.compressor_128)
    if c is not None
]
if attention.indexer is not None:
    ratios.append(attention.indexer.compressor.compress_ratio)
if len({max(1, r) for r in ratios}) > 1:
    raise ValueError(
        f"Layer compression ratios must agree, got {ratios}"
    )
ratio = max(1, inner.compress_ratio)

If you take this, test_compressor_ratio_must_match_inner_attention needs its regex updated.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 411ec7c to c734ce4 Compare November 19, 2026 03:13
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Took the optional simplification in c734ce4: the three ratio checks are now one set comparison whose error lists the disagreeing ratios, and the now-redundant compressor-mismatch test is removed.

Also tightened the helper placement while there: _causal_mask is inlined in HeavilyCompressedAttention.Config.build_attention_metadata (it had one caller), and the shared compressed geometry is a method on DSV4InnerAttention.Config rather than a module-level function.

@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Updated in 43dff58:

  • compressed_causal_mask is a nested function inside HeavilyCompressedAttention.Config.build_attention_metadata rather than an inline expression.
  • Renamed cu_seq_cmp -> cu_seq_pool and causal_cmp -> compressed_causal_mask.
  • Removed the DeepSeekV4Model.Config.__post_init__ ratio validation (and its test): the flavors derive attention, inner attention, compressors and indexer from one compress_ratio, so the shared metadata and its consumers agree by construction.

@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 43dff58 to 09061d8 Compare November 19, 2026 06:55
@sdmyzlp

sdmyzlp commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Renamed the fields as requested in 43dff58's follow-up: cu_seq_cmp -> cu_seq_compressed, causal_cmp -> compressed_causal_indices. The nested helper keeps the name compressed_causal_mask.

All sparse-attention variants share one DeepSeekV4CompressedSparseAttentionMetadata: it extends VarlenAttentionMetadata with the compressed pool offsets, the compressor's group indices and the heavily compressed variant's causal mask. build_attention_metadata builds the empty-compressed-pool default (sliding window); HCA and CSA override it with their geometry.

The compressor, Indexer.forward, Indexer.select and the indexer loss take the metadata and unpack it internally, so the per-layer searchsorted/arange work and the _packed_cu_seqlens helper are gone. Metadata and positions are required, and the flavors build every ratio-bearing component from one compress_ratio, so the shared metadata agrees with its consumers by construction.

No intended numerics change: the packed-vs-per-document attention tests still match, and the dense-masked GPU test now runs through the new metadata.
@sdmyzlp
sdmyzlp force-pushed the dsv4-sparse-metadata-clean branch from 09061d8 to 1aabf5b Compare November 19, 2026 06:57
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Renamed the nested helper as well: compressed_causal_mask -> compressed_causal_indices, so the helper and the metadata field share one name.

@tianyu-l
tianyu-l merged commit 1ae2914 into pytorch:main Nov 19, 2026
15 checks passed
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
pytorch#6181 changed Indexer.select and SparseIndexerLoss to take
DeepSeekV4CompressedSparseAttentionMetadata instead of cu_seqlens.
KimiSparseAttention now builds that metadata once per variant, with the
compressed pool equal to the token pool since K3.1 selects at ratio 1.
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. Built on top of pytorch#6181, the indexer consumes the shared attention_metadata.

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 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. InnerIndexer is stateless: it has no __init__, and its Config builds the module without passing a config argument while still applying the local-SPMD sharding config. Indexer.forward returns (topk_indices, topk_scores), and CompressedSparseAttention takes those instead of the indexer's internals. Built on top of pytorch#6181, the indexer consumes the shared attention_metadata.

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 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. InnerIndexer is a stateless module with the usual two-line __init__, and its Config carries the local-SPMD sharding config. Indexer.forward returns (topk_indices, topk_scores), and CompressedSparseAttention takes those instead of the indexer's internals. Built on top of pytorch#6181, the indexer consumes the shared attention_metadata.

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
pytorch#6181 changed Indexer.select and SparseIndexerLoss to take
DeepSeekV4CompressedSparseAttentionMetadata instead of cu_seqlens.
KimiSparseAttention now builds that metadata once per variant, with the
compressed pool equal to the token pool since K3.1 selects at ratio 1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

2 participants