Repository navigation
Conversation
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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
force-pushed
the
dsv4-sparse-attn-cleanup
branch
2 times, most recently
from
October 31, 2026 03:25
ad6d069 to
b7320bf
Compare
sdmyzlp
force-pushed
the
dsv4-sparse-attn-cleanup
branch
2 times, most recently
from
November 5, 2026 08:42
0250162 to
ec2a692
Compare
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
force-pushed
the
dsv4-sparse-attn-cleanup
branch
from
November 12, 2026 12:25
ec2a692 to
3059730
Compare
Collaborator
Author
|
Closing this stacked branch. Its content is now carried by three decoupled PRs:
Thanks for the reviews and discussion here. |
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_ratiowas 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 viasearchsorted. The indexer also leaked its internals:attention.pycalledIndexer.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:
SparseAttentionMetadatacarriescu_seq_cmp,cmp_base,causal_cmp, and the compressor'sgroup_start/group_first/group_position, so no layer derives them again. Withalign_documents, the compressor regroups the packed stream instead of gathering per document.What changed
models/deepseek_v4/metadata.py(new):SparseAttentionMetadata(aNamedTuplewrappingVarlenAttentionMetadata) andbuild_sparse_metadata, which computes the geometry once per variant;compressed_cu_seqlensmoves here.models/deepseek_v4/attention.py:DSV4InnerAttention.Config.build_attention_metadatareturns the variant metadata (plain varlen for sliding window). The inner attention consumescu_seq_cmp/causal_cmpfrom it; HCA drops its per-layer mask construction.CompressedSparseAttention.forwardnow takestopk_indices(and keywordtopk_scores) instead of the indexer'sidx_q / idx_k / idx_w.models/deepseek_v4/compressor.py:InnerIndexeris a module with its own local-SPMD boundary;Indexer.forwardreturns(topk_indices, topk_scores), so the attention module never sees indexer internals. The compressor and the auxiliary loss takeattention_metadataand use itscmp_base/group_*fields.models/deepseek_v4/model.py:align_documents(off by default) with adocument_alignmentproperty (the lcm of the layer compression ratios);__post_init__validates the per-variant geometry and propagates the alignment to the inner-attention configs;preprocess_inputsannotates the metadata container, whichannotate_input_spmd_typesdoes not visit.models/deepseek_v4/sharding.py,flavors.py: the 3-D attention activation placement forq,topk_indices/topk_scoresin the kernel boundary, and a separateinner_indexersharding config.torchtitan_recipes/tests/models/deepseek_v4.py:align_documentsflag 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.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_backwardkeeps the oldcu_seqlenspath 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_documentsdefaults to off, so existing runs keep the current packing.The per-layer
[T, n_cmp]mask and the per-forwardsearchsortedcalls are gone; no end-to-end throughput claim is made here.Testing
New coverage in
test_sparse_metadata.py:test_cached_compression_matches_legacy_forward_and_backwardcatches a metadata-derived group start orcmp_basethat disagrees with the per-document path, in gradients as well as activations.test_aligned_reshape_matches_general_compressorcatches the aligned reshape path diverging from the general compressor for the same packed input.test_alignment_rejects_unaligned_documentscatches a document boundary that the configured alignment does not divide.test_variant_geometry_must_be_uniformcatches two layers that claim one variant but disagree oncompress_ratio/window_size, which would make the shared metadata wrong for one of them.test_hca_width_is_bounded_by_document_lengthpins the causal mask width to the longest document rather than the packed length.test_padding_does_not_change_real_token_attentioncatches a padded tail that changes the output on the real tokens.Known issues / follow-ups
align_documentsis opt-in; enabling it by default for the DeepSeek-V4 recipes is a separate decision.