Repository navigation
[dsv4] Build sparse-attention geometry once per variant - #6181
Conversation
|
|
4a159e6 to
499d9d7
Compare
decd512 to
76417b7
Compare
|
@claude review |
There was a problem hiding this comment.
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
tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py:103-113(not in the diff) --test_matches_dense_masked_attentionstill callsmodule(q, swa_k, attn_sink),module(q, swa_k, cmp_k, attn_sink)andmodule(..., attn_sink)without metadata.attention_metadatais now a required keyword-only argument, so all three cases fail withTypeError. 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: buildmodule.config.build_attention_metadata(torch.arange(SEQLEN, device=device))(or the equivalent) and pass it in, including toIndexer.select.torchtitan/models/deepseek_v4/model.py:219-- the uniformity check includeswindow_size, which the shared metadata doesn't depend on, so it rejects configs that work (inline).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=Nonebranch and thegroup_positionfield have no non-test caller (inline).torchtitan/models/deepseek_v4/compressor.py:254--Indexer.select/compressed_gather_indices/_teacherkeep a test-onlyNonepath (inline).torchtitan/models/deepseek_v4/attention.py:150-- the_gather_attndocstring still says "With packedcu_seqlens"._compressed_geometryand the newattention_metadataparameters incompressor.pyhave 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 usedunflatten, but production always took the packed path, sinceDecoder.preprocess_inputsbuilds metadata wheneverpositionsis present. The HCA mask now takes the in-document index frompositions, while the old code took it fromcu_seq_q. The two agree because the data pipeline canonicalizes positions to reset at everycuboundary (components/data/packing.py), and fixed-capacity overflow is caught by_assert_asyncincreate_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 remainingNonebranches, and part of the new tests.
Not verified: GPU numerics and the GPU attention test (CPU-only review).
| geometry = {} | ||
| for layer in (*self.layers, *(self.mtp_layers or ())): | ||
| inner = layer.attention.inner_attention | ||
| key = (max(1, inner.compress_ratio), inner.window_size) |
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
|
@sdmyzlp please address claude review |
76417b7 to
fe38bec
Compare
|
Addressed in fe38bec:
|
fe38bec to
5f2ef3a
Compare
|
@claude review again |
There was a problem hiding this comment.
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_sizein the uniformity check: resolved.- Tautological HCA mask test: removed.
positions=None/group_position: removed.Nonebranches inIndexer.select/compressed_gather_indices/_teacher: removed._gather_attndocstring and type hints: fixed.- Still open: whether this has a measured step-time or memory effect, or is only a cleanup.
Must fix
- PR description -- the "Summary (human-written)" section is empty. Per
CONTRIBUTING.md, the author fills it in; agents leave it. tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py:123-- the CSA oracleIndexer.selectgets 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 buildgroup_start(inline).torchtitan/models/deepseek_v4/attention.py:419--positionsstill defaults toNone, but the compressor now requires it (inline).
Details
_get_attention_metadata(decoder.py:504) iterates only overconfig.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 covermtp_layersfor 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_kis the Python intmax_context_length. No new host syncs. tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.pyis a model test that sits outsidetests/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, |
There was a problem hiding this comment.
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:
| attention_metadata=metadata, | |
| attention_metadata=config.build_attention_metadata( | |
| torch.arange(SEQLEN) | |
| ), |
| if max(1, layer.attention.compress_ratio) != ratio: | ||
| raise ValueError( | ||
| "Attention and inner attention compression ratios must agree" | ||
| ) |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
5f2ef3a to
411ec7c
Compare
|
Addressed in 411ec7c:
Pre-commit: all hooks pass except pyrefly's two pre-existing baseline errors in untouched files ( |
|
@claude review again |
There was a problem hiding this comment.
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=Nonedefault onDeepSeekV4Attention.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 andpositionsbreaks no other in-repo caller. - MTP blocks (
flavors.py:_make_mtp_inner_block) setcompressor,compressor_128andindexertoNoneand both ratios to 1, so they pass the new__post_init__. - The explicit
Decoder.Config.__post_init__(self)call, rather thansuper(), is needed: zero-argsuper()doesn't work inslots=Truedataclasses. - Unchanged from the last review:
_get_attention_metadataonly iteratesconfig.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).
| 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" | ||
| ) |
There was a problem hiding this comment.
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.
411ec7c to
c734ce4
Compare
|
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: |
c734ce4 to
43dff58
Compare
|
Updated in 43dff58:
|
43dff58 to
09061d8
Compare
|
Renamed the fields as requested in 43dff58's follow-up: |
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.
09061d8 to
1aabf5b
Compare
|
Renamed the nested helper as well: |
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.
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.
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.
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.
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.
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.
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.
Summary (human-written)
compress_ratio-derived quantity — compressed pool offsets, compressor group indices, and the heavily compressed variant's causal mask — is now computed once per variant inbuild_attention_metadata, instead of being rebuilt inside every layer on every forward.attention_metadatainstead ofcu_seqlens, so an overridingInnerAttentioncan pair its ownbuild_attention_metadatawith 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.This is independent of the document-padding work (#6059); the geometry uses the current unaligned layout.
What changed
attention.py:DeepSeekV4CompressedSparseAttentionMetadataextendsVarlenAttentionMetadatawithcu_seq_compressed,group_start,group_firstandcompressed_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.positionsis required onDeepSeekV4Attention.forward.compressor.py:Compressor,Indexer.forward,Indexer.selectandSparseIndexerLosstake the metadata and unpack it internally; positions and metadata are required, and the per-layersearchsorted/arangework is gone.model.py:forwardrequires attention metadata. The flavors derive attention, inner attention, compressors and indexer from onecompress_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.