Repository navigation
[dsv4] Encapsulate index selection behind InnerIndexer - #6216
Conversation
|
|
45d8ae3 to
5c48bbf
Compare
28e2078 to
0412bbb
Compare
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 31s —— View job Verdict: Request changes -- the top-k width now depends on total tokens instead of document length, and there is no evidence that numerics hold under TP. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- the refactor quietly changes the top-k width for packed documents, and it moves a local-SPMD boundary without any evidence that numerics hold under TP.
What this PR does. Before, DeepSeekV4Attention received the indexer's idx_q / idx_k / idx_w and called Indexer.select itself. Now selection lives in a new InnerIndexer submodule with its own local-SPMD ShardingConfig. Indexer.forward returns (topk_indices, topk_scores), and CompressedSparseAttention takes those tensors instead of the raw features. Moving selection into the module that owns it is reasonable.
Example.
# before (CSA layer)
idx_q, idx_k, idx_w = self.indexer(x, qr, positions=..., attention_metadata=md)
self.inner_attention(q, kv, cmp_k, idx_q, idx_k, idx_w, sink, ...) # select() inside, max_seqlen=md.max_k
# after
topk_indices, topk_scores = self.indexer(x, qr, ..., topk=16, return_scores=True) # max_seqlen=x.size(0)
self.inner_attention(q, kv, cmp_k, topk_indices, sink, topk_scores=topk_scores)With documents packed into one microbatch, the selection width changes from min(topk, max_doc_len // 4) to min(topk, T // 4).
Must fix
torchtitan/models/deepseek_v4/compressor.py:260--max_seqlen=seqlenshould beattention_metadata.max_k. Better: drop the parameter and readmax_kinsideInnerIndexer. As written, the selection grows wider with packed documents (see inline).- Numerics proof is missing.
idx_q / idx_k / idx_wused to enter the inner-attentionlocal_mapregion as TP-replicated. Nowtopk_scoresleaves a newlocal_mapregion and enters a second one, so its gradient path changes under TP/CP. Tests were CPU-only, without parallelism. Please add a bitwise loss/grad_norm comparison againstmain(scripts/loss_compare.py) on debugmodel with the indexer aux loss enabled andspmd_typecheckingon, for at least FSDP2 + TP2, and with packed documents so item 1 is exercised.
Should consider
torchtitan/models/deepseek_v4/compressor.py:332-- the empty-tensor placeholder round trip needs a TODO naming the spmd_types limitation, and the test should stop assertingnumel() == 0(inline).torchtitan/models/deepseek_v4/compressor.py:284-289-- annotations dropped, andreturn_scores=Truedefaults that the caller always overrides (inline).tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py-- this pre-existing file doesn't follow the mirrored layout; it belongs undertests/unit_tests/cpu/models/deepseek_v4/(a separate PR is fine).
Questions
- #5863 ([QSA] sparseindexerloss teacher) edits the same four files, including the selection/loss path. Which one lands first, and does that PR's teacher path still fit once selection sits behind
InnerIndexer?
Not verified: whether the wider -1 padding is bitwise-neutral in gather_attn / SparseIndexerLoss, and whether the TP gradient on topk_scores is reduced exactly as before. Both need the GPU run in item 2.
|
|
||
| if not return_scores: | ||
| # local_map requires tensors at both declared output leaves. | ||
| return topk_indices, idx_w.new_empty((0, 0)) |
There was a problem hiding this comment.
The (0, 0) placeholder works around local_map not accepting None at a declared output. Indexer.forward then converts it back to None (line 266), and a test now asserts numel() == 0, which pins the workaround in place. Please add a TODO here naming the spmd_types limitation, with an issue link if one exists, so the round trip can be removed later. Also drop the numel() == 0 assertion: callers only ever see None.
|
Added the FSDP2 + TP2 verification to the PR description:
Limitations are in the description: 4 ranks, no PP/CP, debugmodel only, equality check rather than convergence. |
|
@claude review again |
|
Claude finished @tianyu-l's task in 2m 37s —— View job Verdict: Approve -- both earlier must-fix items are fixed, and two small items remain (a TODO link and a redundant test assertion). See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. Both earlier must-fix items are resolved. The packed-document width is back to max_k, and the bitwise FSDP2 + TP2 comparison against base matches exactly. What remains is small and local.
What this PR does. Index selection used to be a static Indexer.select called inside CompressedSparseAttention. It is now an InnerIndexer submodule with its own local-SPMD boundary. Indexer.forward returns (topk_indices, topk_scores), and the inner-attention kernel takes those two tensors instead of idx_q/idx_k/idx_w.
Example.
# before
idx_q, idx_k, idx_w = self.indexer(x, qr, ...)
self.inner_attention(q, kv, cmp_k, idx_q, idx_k, idx_w, sink, ...) # select() inside
# after
topk_indices, topk_scores = self.indexer(x, qr, ..., topk=index_topk, return_scores=training and aux_loss)
self.inner_attention(q, kv, cmp_k, topk_indices, sink, topk_scores=topk_scores)With packed docs of 40/40/48 tokens, ratio 4, and topk 16, the width is min(16, 48 // 4) = 12, the same as on main.
Earlier findings
compressor.pytop-k width: resolved.InnerIndexerreadsattention_metadata.max_k, and there is a regression test for it.- Numerics proof: resolved. FSDP2+TP2 and the TP2 control are bit-identical to base
8592e69c3over 10 steps with packed docs and aux loss on. Theindex_topk=1024run also confirms the width fix: 4.21 GiB at tip vs 6.71 GiB pre-fix.spmd_typecheckingwas off. I confirmed that the blocker is pre-existing on main:dsa_inner_attention_sharding_configgives the 3-Dqa 2-entry partition spec fromdense_activation_placement. The follow-up PR owns that. (0, 0)placeholder: TODO added and thenumel()assertion removed. The issue link is still missing (inline).- Annotations and the required
return_scores: resolved.
Must fix
torchtitan/models/deepseek_v4/compressor.py:329-- add the spmd_types issue link to the TODO.tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_dsa.py:88-- drop the assertion that just repeats the formula; the hard-coded12is the guard.
Should consider
torchtitan/models/deepseek_v4/attention.py:279--topk_scoresis keyword-only, so its newinput_shardingsentry only feeds the boundary assert, neverlocal_map'sin_types(module.py:543-549). The follow-up typing PR should decide whether the scores need a real input type (inline).
Questions
- Merge order with #5863: the author proposes landing this first and rebasing #5863 onto it. A maintainer should confirm with the #5863 author.
A maintainer still needs to review.
Not verified: how spmd.local_map treats a typed tensor passed as a kwarg when typechecking is on; this matters only once the follow-up enables typechecking for DSv4. I could not run the CPU tests in this environment.
| topk_indices, | ||
| attn_sink, | ||
| *, | ||
| topk_scores=None, |
There was a problem hiding this comment.
topk_scores is keyword-only, so the "topk_scores" entry this PR adds in dsa_inner_attention_sharding_config never reaches spmd.local_map. Module._maybe_wrap_with_local_region (torchtitan/models/base/module.py:543-549) builds in_types from positional args only. Keyword args are only checked by _assert_input_types at the boundary. Before this PR, idx_q/idx_k/idx_w were positional, so their R types were part of in_types. padding_mask_T already works this way, so this follows an existing pattern. It is not a bug while typechecking is off, but the follow-up typing PR should decide whether the scores need a real local-map input type. If they don't, a short comment here would stop the declared sharding entry from looking like it does more than it does.
| attention_metadata=metadata, | ||
| return_scores=False, | ||
| ) | ||
| self.assertEqual(indices.shape[1], min(topk, metadata.max_k // ratio)) |
There was a problem hiding this comment.
This line repeats the implementation's formula, so it would still pass if max_k were swapped for any other value that happens to give the same width. The hard-coded 12 on the next line is the real regression guard (packed width 32 // 4 would be 16 here). Drop this line.
| self.assertEqual(indices.shape[1], min(topk, metadata.max_k // ratio)) |
| ).squeeze(0) | ||
|
|
||
| if not return_scores: | ||
| # TODO(spmd_types): local_map cannot declare a None output; |
There was a problem hiding this comment.
This TODO waits on spmd_types (meta-pytorch), so please add an upstream issue link, as CLAUDE.md asks for upstream workarounds. Without one, nobody will know when the (0, 0) round trip in Indexer.forward can be deleted.
|
@sdmyzlp please fix remaining comments |
| state_shardings: dict[str, SpmdType] = field(default_factory=dict) | ||
| input_shardings: dict[str, SpmdType] | None = None | ||
| output_shardings: SpmdType | tuple[SpmdType, ...] | None = None | ||
| output_shardings: SpmdType | tuple[SpmdType | None, ...] | None = None |
There was a problem hiding this comment.
oh, I didn't understand where does spmd_types break.
Before making this core change, could you draw some pictures explaining what's going on?
There was a problem hiding this comment.
The indexer's second output used to depend on the caller.
training with aux loss -> (indices, scores)
eval or aux loss off -> (indices, None)
A tensor layout rejected the eval None. Passing it through TorchTitan required a None entry in output_shardings. In spmd_types.local_map, that entry requires a non-tensor, so it rejected the training score. Boundary check
I removed the core changes and followed Qwen3.8 Flash-Next. The indexer now always computes and returns scores, with (replicated, replicated) for its two outputs. Qwen sharding
There was a problem hiding this comment.
Verdict: Needs discussion -- the core ShardingConfig change is gone, but in its place eval and aux-disabled training now compute indexer scores that nothing reads. A maintainer has to decide whether that cost is acceptable, or the computation should be skipped.
What this PR does. Indexer now owns top-k selection through an InnerIndexer local-SPMD submodule and returns (topk_indices, topk_scores). Before, CompressedSparseAttention received idx_q/idx_k/idx_w and selected inside itself. The latest commit (4012271) drops the None output and the base/ changes and always returns both tensors as TP-replicated. When the loss is off, the indexer call runs under no_grad.
Example.
# eval, or indexer_loss_coeff=0
# before: Indexer.select(..., return_scores=False) -> (indices, None); no gather, no einsum
# after: InnerIndexer -> (indices, scores)
# gather [T, K, D] + einsum [T, H, K]; _gather_attn never reads scoresEarlier findings
- @tianyu-l's question on
base/sharding.py: addressed. The core change was reverted, somodule.py,sharding.pyandvalidation.pyno longer appear in the diff, and the author explained whyNonefailed inspmd_types.local_map. - The TODO link for the
(0, 0)placeholder and the redundant width assertion are both moot now: the placeholder is gone, and the new width test hard-codes12and0. - The
topk_scoreskeyword-only typing note now has a comment atsharding.py:89.
Must fix
torchtitan/models/deepseek_v4/compressor.py:325-333-- scores are computed and then discarded in eval and inindexer_loss_coeff=0training. At Pro sizes this is about 4 GiB of transient memory and about 137 GFLOP per CSA layer at T=8192, and every TP rank pays it. Either skip the computation (requiredreturn_scoresplus an empty[T, 0]tensor), or post GPU numbers and get a maintainer to accept the cost (inline).
Questions
- Summary point 2 says V4.1 reuses indexer outputs across layers. Does that reuse need
topk_scoresin eval or with the loss disabled, or onlytopk_indices? The answer decides between the two options above. - Merge order with #5863 is still open for a maintainer to confirm.
Details
- Main training path: default
indexer_loss_coeff=0.01keeps training with the loss enabled the same as before, so the cost only hits eval/validation and coeff-0 runs. The CPU bitwise check on this revision and the earlier FSDP2+TP2 run (sameInnerIndexerboundary,(R, R)outputs) cover the training gradient path. torch.set_grad_enabled(...)atattention.py:457: the indexer parameters still get no gradient when the loss is off, as on main. The only difference is that their autograd graph is no longer built and then dropped.- The empty-pool guard
k = ... if idx_k.size(0) else 0exists because scores are now always gathered fromidx_k. Its shape depends only onT // ratio, so it stays static under fixed-shape metadata.
Not verified: actual eval latency and peak-memory deltas on GPU (the estimates above are arithmetic); the Qwen3.8 Flash-Next precedent, because that file is not in this checkout. A maintainer still needs to review.
| valid_TK = topk_indices >= 0 | ||
| gather_indices_TK = compressed_gather_indices( | ||
| topk_indices, attention_metadata, ratio | ||
| ) | ||
| selected_TKD = idx_k[gather_indices_TK] | ||
| logits_THK = torch.einsum("thd,tkd->thk", idx_q, selected_TKD) | ||
| topk_scores = (logits_THK.relu() * idx_w.unsqueeze(-1)).sum(dim=1) | ||
| topk_scores = topk_scores.masked_fill(~valid_TK, -torch.inf) | ||
| return topk_indices, topk_scores |
There was a problem hiding this comment.
This block now runs in eval and in indexer_loss_coeff=0 training too, and _gather_attn throws the result away in both cases (attention.py:155: aux_loss = self.aux_loss if self.training else None; the scores are only read when aux_loss is set). Before this commit, those paths never built it.
Rough per-CSA-layer cost at Pro sizes (H=64, D=128, K=index_topk=1024), with T=8192 tokens per rank:
selected_TKD: TKD bf16 = 2 GiB transientlogits_THK: THK = 1 GiB, plus about 1 GiB each for thereluand* wtemporaries- about 2THKD = 137 GFLOP of extra compute, plus a bandwidth-bound gather
Under TP, every rank pays this because the inputs are replicated. The PR description says GPU latency and memory weren't measured.
Two ways to resolve this:
- Skip it (my recommendation). Bring back a required
return_scores: bool. When it is False, return an empty[T, 0]tensor. That needs noNoneround trip any more, becausetopk_scoresis now a plain tensor argument that_gather_attnignores when the loss is off. Theidx_k.size(0)guard above may then only be needed on the scored path. - Keep always-compute. If V4.1 needs the scores outside the loss, post eval and aux-off latency and peak memory at Flash/Pro sizes, and get a maintainer to accept the cost.
|
@claude review |
|
Claude finished @sdmyzlp's task in 1m 37s —— View job Verdict: Approve -- eval and aux-disabled training skip rescoring again; one optional test cleanup remains. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- the last must-fix is resolved: eval and aux-disabled training skip rescoring again, and nothing else blocks.
What this PR does. Indexer now owns top-k selection through an InnerIndexer local-SPMD submodule and returns (topk_indices, topk_scores) as TP-replicated tensors. CompressedSparseAttention takes those tensors in place of the raw idx_q/idx_k/idx_w. The latest commit (4b49b40) brings back a required return_scores. When it is False, InnerIndexer returns right after lightning_indexer with a [T, 0] score tensor, and the indexer projection runs under no_grad.
Example.
# eval, or indexer_loss_coeff=0
# main: Indexer.select(..., return_scores=False) -> (indices, None)
# 4012271: InnerIndexer -> (indices, scores) # gather [T,K,D] + einsum, then discarded
# this rev: InnerIndexer -> (indices, empty[T, 0]) # no gather, no einsum
# training with the loss on: (indices [T,K], scores [T,K]), the same as mainEarlier findings
- Always-computed scores (
compressor.py): resolved.compressor.py:328-329returns beforecompressed_gather_indices. The[T, 0]placeholder goes through(R, R)output shardings, sobase/needs no change._gather_attnnever reads it whenaux_lossis inactive (attention.py:155).SlidingWindowAttentionalready passes[T, 0]tensors togather_attn, so zero-width inputs are an existing path. - The question about V4.1 reuse is moot: scores are only produced when the loss consumes them.
Should consider
tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py:264-276-- the mock-call assertion oncompressed_gather_indicescan become a shape check (inline).
Questions
- Merge order with #5863 is still open; a maintainer should confirm it with that PR's author.
Details
return_scores(attention.py:455-458) uses the same condition as_gather_attn(inner_attention.training and aux_loss is not None), so scores are never missing when the loss needs them.indexer_loss_coeff=0givesaux_loss=None(flavors.py:1215).torch.set_grad_enabled(... and return_scores): the indexer parameters already got no gradient on main with the loss off. Now their autograd graph is not built at all. The CPU 10-step bitwise run with the loss disabled covers this path.- Empty-pool guard (
compressor.py:312): it applies to both paths, so index width does not depend onreturn_scores, and the test at line 277 checks exactly that.idx_k.size(0)isT // ratio, which is static under fixed-shape metadata. - All in-repo callers of the old
Indexer.selectand the oldidx_q/idx_k/idx_wsignature are updated (only DSv4 and its tests use them).
Not verified: GPU latency and memory for eval or aux-off at Flash/Pro sizes (the skip should restore main's cost). This touches only DSv4 model code, but a maintainer still needs to review.
| with patch( | ||
| "torchtitan.models.deepseek_v4.compressor.compressed_gather_indices" | ||
| ) as score_gather: | ||
| index_only, _ = indexer( | ||
| q, | ||
| k, | ||
| w, | ||
| ratio=4, | ||
| topk=2, | ||
| attention_metadata=metadata, | ||
| return_scores=False, | ||
| ) | ||
| score_gather.assert_not_called() |
There was a problem hiding this comment.
Patching compressed_gather_indices and asserting it wasn't called is a mock-call check (.claude/rules/tests.md), and it ties the test to a private helper name. The observable contract is already covered: return_scores=False yields a [T, 0] score tensor, which only the early return produces, and test_eval_and_disabled_loss_do_not_rescore asserts exactly that at the attention level. Asserting the shape here does the same job without the patch:
| with patch( | |
| "torchtitan.models.deepseek_v4.compressor.compressed_gather_indices" | |
| ) as score_gather: | |
| index_only, _ = indexer( | |
| q, | |
| k, | |
| w, | |
| ratio=4, | |
| topk=2, | |
| attention_metadata=metadata, | |
| return_scores=False, | |
| ) | |
| score_gather.assert_not_called() | |
| index_only, no_scores = indexer( | |
| q, | |
| k, | |
| w, | |
| ratio=4, | |
| topk=2, | |
| attention_metadata=metadata, | |
| return_scores=False, | |
| ) | |
| self.assertEqual(no_scores.shape, (12, 0)) |
4b49b40 to
a1713c1
Compare
|
Rebased onto latest main ( Cleanup in the squashed revision:
Verification: 36 passed, 3 CUDA skipped (DSV4 + indexer-loss + GPU attention + recipe + state-dict); pre-commit clean. Pyrefly still reports only the environment's attn-gym mismatch (the venv has 0.0.20; requirements pin a newer commit). |
a1713c1 to
4ddfcf6
Compare
|
Updated the branch with two commits:
Verification: 37 passed, 3 CUDA skipped; pre-commit clean. The new TP-invariant sharding is typechecked on CPU, but a fresh H800 TP2 loss/gradient run is still needed to confirm the removed all-reduce numerically. @claude review |
|
Claude finished @sdmyzlp's task in 5m 12s —— View job Verdict: Request changes -- the TP-invariant indexer commit changes how gradients are reduced under TP and has no TP numerics run yet. It also sets top-k in two config fields and weakens two existing tests. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- dfbe9ad changes how indexer gradients are reduced under TP and has no TP numerics run yet. It also leaves top-k configured in two places and weakens two existing tests.
What this PR does. Same refactor as the approved 4ddfcf6: InnerIndexer owns top-k selection, and Indexer returns (topk_indices, topk_scores). The new commit has three parts:
- It moves
ratio/topkintoInnerIndexer.Config. - It retypes the indexer's params, inputs and outputs from
RtoIon TP (identical value and gradient on every rank). With that, it deletes the1/TPscaling of the aux-loss gradient. - It fixes the 3-D
qpartition spec, so a fake-PG TP=2 forward typechecks.
Example. TP=2, aux loss on. g is d(aux)/d(wq_b) on one rank, identical on both, because _teacher all-reduces p_TK.
4ddfcf6: wq_b typed R -> loss grad scaled 1/2 -> FSDP sums over TP -> g/2 + g/2 = g
dfbe9ad: wq_b typed I -> no scaling -> no TP reduction -> g
I checked the math (compressor.py:398-425): the I declaration holds because x/qr are detached R tensors (attention.py:421,463) and the teacher is TP-summed. The reduction path is different, though. The FSDP2+TP2 numbers in the description predate this commit, and with dp_shard > 1 the summation order changes. The PR still needs a 10-step loss/grad_norm comparison against base on 4x H800 (FSDP2+TP2 with the aux loss on, spmd_typechecking on) before merge. The description already lists this as pending.
Earlier findings
- The
compressed_gather_indicesmock assertion is gone. The test now checks the(T, 0)shape. Resolved. - The q partition-spec blocker on typechecking, earlier deferred to a follow-up, is fixed here (
attention_activation_placement()).
Must fix
- TP numerics for the new
Isharding (see above). No inline line: the change is spread oversharding.py,flavors.pyand the deletedcompressor.pyscaling. flavors.py:195--topkis now set inInnerIndexer.Configand inDSV4InnerAttention.Config.index_topk, which only flops reads. An override of the latter silently doesn't change selection (inline).test_deepseek_v4_dsa.py:30--seqlen=64makesn_cmp == topk, so the top-k equivalence test no longer tests ranking (inline).test_deepseek_v4_dsa.py:72-73-- the group-aligned[256, 128, 384]case was dropped without explanation (inline).
Should consider
compressor.py:171-178-- type the metadata geometry in aDeepSeekV4CompressedSparseAttentionMetadata.annotate_spmd_types()override, not once per compressor call in every layer (inline).sharding.py:158-163--invariant_activation_placementduplicatesdense_activation_placement(tp=spmd.I, cp=spmd.S(0))(inline).flavors.py:136-142-- thestate_tpdefault and theis spmd.Ibranch can go away (inline).test_deepseek_v4_indexer_loss.py:50-58--**kwargsis now unused (inline).- Scope:
4ddfcf6is validated and approved, whiledfbe9adis a separate concern (TP gradient typing) with its own numerics debt. Movingdfbe9ad/ac5fd44into a follow-up PR would let the refactor land now.
Questions
- Merge order with #5863 is still open for a maintainer.
Not verified: I couldn't run the CPU tests here, so I couldn't check whether the dropped [256, 128, 384] case still passes. That FSDP reduces R params over TP is based on decoder_sharding.py:179. A maintainer still needs to review.
| torch.manual_seed(0) | ||
| device = torch.device("cpu") | ||
| seqlen, ratio, topk = 512, 4, 16 | ||
| seqlen, ratio, topk = 64, 4, 16 |
There was a problem hiding this comment.
With seqlen=64, n_cmp = 16 == topk. Every row then selects every causal compressed position, so the sorted-set comparison on line 64 can't catch a wrong ranking. A selection that returned any valid causal set would still pass. On main (512, n_cmp = 128), this test is the only one checking that lightning_indexer picks the same top-k as the dense formulation. Keep n_cmp > topk. Any seqlen > 64 does that, and 128 stays cheap.
| seqlen, ratio, topk = 64, 4, 16 | |
| seqlen, ratio, topk = 128, 4, 16 |
| if spmd.is_type_checking(): | ||
| # Geometry is token-indexed and identical on every TP rank. | ||
| metadata_layout = spmd.SpmdType( | ||
| {"dp": spmd.V, "cp": spmd.V, "tp": spmd.I}, | ||
| partition_spec=spmd.PartitionSpec(("dp", "cp")), | ||
| ) | ||
| spmd.assert_type(start_G, metadata_layout) | ||
| spmd.assert_type(first_G, metadata_layout) |
There was a problem hiding this comment.
This types shared metadata from inside a consumer. It runs once per compressor call: the main compressor, compressor_128, and the indexer's compressor, in every layer. Metadata already has a hook for this. annotate_input_spmd_types calls SpmdAnnotatedInput.annotate_spmd_types() once per step (distributed/spmd_types.py:198-230), and qwen3_8_flash_next/attention.py:247 overrides it for its geometry tensors. Override it on DeepSeekV4CompressedSparseAttentionMetadata instead. Call super(), then type group_start/group_first (and cu_seq_compressed if needed), using MeshAxisName rather than bare "dp"/"cp"/"tp" strings. The new TP test then calls metadata.annotate_spmd_types() inside activate_spmd, so it exercises the same path as the trainer.
| def invariant_activation_placement() -> SpmdType: | ||
| """Tokens sharded on DP/CP; every TP rank holds the same value and grad.""" | ||
| return SpmdType( | ||
| {DP: spmd.V, CP: spmd.V, TP: spmd.I}, | ||
| partition_spec=spmd.PartitionSpec((DP, CP), None), | ||
| ) |
There was a problem hiding this comment.
This is exactly dense_activation_placement(tp=spmd.I, cp=spmd.S(0)): {DP: V, CP: V, TP: I} with spec ((DP, CP), None). That is also residual_activation_placement(enable_sp=False). dsa_inner_attention_sharding_config already builds its replicated sibling that way two lines above. Use the existing helper and delete this one.
| state_tp: spmd.PerMeshAxisSpmdType = spmd.R, | ||
| ) -> "Compressor.Config": | ||
| state_sharding = ( | ||
| invariant_state_sharding_config("weight") | ||
| if state_tp is spmd.I | ||
| else replicated_state_sharding_config("weight") | ||
| ) |
There was a problem hiding this comment.
The is spmd.I branch silently maps any other value (e.g. spmd.S(0)) to R. The = spmd.R default is a second default on an internal helper (here and on compressor_sharding_config). Make state_tp required at all three call sites and build the placement directly. Then neither the branch nor invariant_state_sharding_config needs to exist for this:
state_sharding = ShardingConfig(
state_shardings={"weight": dense_param_placement(tp=state_tp)}
)| def _metadata(cu, seqlen, **kwargs): | ||
| """The sparse metadata for a packed or single-document layout.""" | ||
| if cu is None: | ||
| positions = torch.arange(seqlen) | ||
| else: | ||
| positions = torch.cat([torch.arange(n) for n in torch.diff(cu).tolist()]) | ||
| return CompressedSparseAttention.Config( | ||
| window_size=4, compress_ratio=4, softmax_scale=0.1, index_topk=2 | ||
| ).build_attention_metadata(positions) | ||
| ).build_attention_metadata(positions, **kwargs) |
There was a problem hiding this comment.
**kwargs lost its only caller when dfbe9ad removed the empty-pool case. No call site passes it now, so revert to main's helper.
| def _metadata(cu, seqlen, **kwargs): | |
| """The sparse metadata for a packed or single-document layout.""" | |
| if cu is None: | |
| positions = torch.arange(seqlen) | |
| else: | |
| positions = torch.cat([torch.arange(n) for n in torch.diff(cu).tolist()]) | |
| return CompressedSparseAttention.Config( | |
| window_size=4, compress_ratio=4, softmax_scale=0.1, index_topk=2 | |
| ).build_attention_metadata(positions) | |
| ).build_attention_metadata(positions, **kwargs) | |
| def _metadata(cu, seqlen): | |
| """The sparse metadata for a packed or single-document layout.""" | |
| if cu is None: | |
| positions = torch.arange(seqlen) | |
| else: | |
| positions = torch.cat([torch.arange(n) for n in torch.diff(cu).tolist()]) | |
| return CompressedSparseAttention.Config( | |
| window_size=4, compress_ratio=4, softmax_scale=0.1, index_topk=2 | |
| ).build_attention_metadata(positions) |
ac5fd44 to
4ddfcf6
Compare
|
Reset the branch to a single interface-only commit ( @claude review |
|
Claude finished @sdmyzlp's task in 2m 3s —— View job Verdict: Approve -- the reset to |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. With dfbe9ad/ac5fd44 dropped, every must-fix from the last review is moot. Head 4ddfcf6 is the interface-only refactor that was approved before. One small edit to the description remains.
What this PR does. Indexer now owns top-k selection through an InnerIndexer local-SPMD submodule and returns (topk_indices, topk_scores), both TP-replicated. CompressedSparseAttention takes those two tensors in place of idx_q/idx_k/idx_w. When the aux loss is inactive (eval, or indexer_loss_coeff=0), the indexer runs under no_grad and returns [T, 0] scores, skipping the rescoring gather and einsum.
Example.
# main
idx_q, idx_k, idx_w = self.indexer(x, qr, ...)
self.inner_attention(q, kv, cmp_k, idx_q, idx_k, idx_w, sink, ...) # Indexer.select inside
# this PR
topk_indices, topk_scores = self.indexer(x, qr, ..., topk=index_topk, return_scores=training and aux_loss)
self.inner_attention(q, kv, cmp_k, topk_indices, topk_scores, sink, ...)
# packed docs [4, 8], ratio 4, topk 3: width = min(3, max_k // 4) = 2, as on main (not T // 4 = 3)Earlier findings (review of dfbe9ad)
- TP numerics for the
Isharding, the duplicatedtopkfield, theseqlen=64test, the dropped[256, 128, 384]case, metadata typing in the compressor,invariant_activation_placement, and thestate_tpbranch: all moot, because that commit is no longer in the PR.seqlen=512and[256, 128, 384]are back attest_deepseek_v4_dsa.py:29,133. _metadata(**kwargs): it now has a caller (themax_context_length=12empty-pool case attest_deepseek_v4_indexer_loss.py:253), so keep it.
Must fix
- PR description: the "Numerics and performance" section no longer carries the FSDP2 + TP2 bitwise comparison against base. The 11-20 comment says that evidence was added, but the reset description dropped it. Add it back (
dp_shard=2, tp=2and the TP2 control, packed docs, aux loss on,index_topk=1024width check). Also say which revision it ran on. It predates the core-sharding revert and the squash, so either rerun it on4ddfcf6or explain why the result still applies: the boundary is the same(R, R)and typechecking is off.
Questions
- Merge order with #5863 (still open; it edits the same selection/loss path) needs a maintainer to confirm with that PR's author.
Details
- Callsites:
Indexer.selectand theidx_q/idx_k/idx_winner-attention signature are used only by DSv4 and its tests, and all of them are updated.qwen3_8_flash_nexthas its own indexer and is not affected. No README mentions the old API. return_scores(attention.py:457-460) uses the same condition_gather_attnuses to read the scores, so scores are never missing when the loss needs them.torch.set_grad_enabled(... and return_scores): with the loss off, the indexer params got no gradient on main either. Now their graph just isn't built.- Only
compress_ratio == 4layers build an indexer (flavors.py:248-268), so moving the call under that branch drops nothing for ratio-128 layers. @spmd.no_typecheck()used as a decorator has a precedent inmodels/common/rope.py:105.- The GPU attention test now passes synthetic gapped indices. Selection correctness is still covered against the dense top-k formulation by
test_indexer_select_matches_old_topk(n_cmp=128 > topk=16).
Not verified: a TP2 loss/grad_norm run at 4ddfcf6 itself (see item 1). This touches only DSv4 model code, but a maintainer still needs to review.
4ddfcf6 to
63f6a8e
Compare
|
Pushed a single interface-focused commit (
@claude review |
|
Claude finished @sdmyzlp's task in 1m 25s —— View job Verdict: Approve -- the numerics evidence is back in the description and |
There was a problem hiding this comment.
Verdict: Approve -- 63f6a8e fixes the last must-fix (the numerics evidence is back in the description, and the description says which revision it ran on). The topk source of truth is now a single field. One optional test cleanup remains.
What this PR does. Indexer owns top-k selection through an InnerIndexer local-SPMD submodule. InnerIndexer.Config holds ratio/topk, and the module returns (topk_indices, topk_scores), both TP-replicated. CompressedSparseAttention takes those two tensors in place of idx_q/idx_k/idx_w. When the aux loss is inactive, the indexer runs under no_grad and returns [T, 0] scores.
Example.
# main
idx_q, idx_k, idx_w = self.indexer(x, qr, ...)
self.inner_attention(q, kv, cmp_k, idx_q, idx_k, idx_w, sink, ...) # Indexer.select(topk=inner_attention.index_topk)
# this PR
topk_indices, topk_scores = self.indexer(x, qr, ..., return_scores=training and aux_loss) # topk from InnerIndexer.Config
self.inner_attention(q, kv, cmp_k, topk_indices, topk_scores, sink, ...)
# flops_per_token reads indexer.inner_indexer.topk, so an override of that field changes selection and MFU togetherEarlier findings
- Numerics evidence in the description: resolved. The FSDP2+TP2 and TP2-control numbers and the
index_topk=1024width check are back, labeled as collected one87dc0dff. The reason they still apply is stated: the(R, R)boundary is unchanged. - Duplicate
topk(raised againstdfbe9ad): resolved here.DSV4InnerAttention.Config.index_topkis gone. The flavors, the MTP block and the tests are all updated. No recipe or other model references the field: theindex_topkhits underexperiments/transformers_modeling_backendare HF config attributes, not this field. - Empty-pool guard removed:
k = min(self.topk, max_k // self.ratio)is the same as main'smin(topk, max_seqlen=max_k // ratio), so this restores main's behavior.
Should consider
tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_dsa.py:129-137-- a no-opreplace(csa.inner_attention)and a nestedreplacechain where a one-line in-place mutation works (inline).
Details
- Call order in
DeepSeekV4Attention.forwardis the same as on main: indexer, then compressor, then inner attention. The ratio-128 path buildscompressor_128only, as before. return_scores(attention.py:456-459) uses the same condition_gather_attnuses to read scores (attention.py:153), so scores are never missing when the loss needs them.assert self.indexer is not Noneinflops_per_token: onlycompress_ratio == 4layers get an indexer config, so this is an internal invariant.inner_indexer_sharding_configuses a 3-D spec foridx_qandreplicated_activation_placement()for the rest. That matches the R placementidx_q/idx_k/idx_whad at the inner-attention boundary on main.
Not verified: a TP2 loss/grad_norm run at 63f6a8e itself. The description acknowledges this, and the diff against the measured revision is config plumbing only. This touches only DSv4 model code, but a maintainer still needs to review.
| csa = attention_configs[4] | ||
| attention_configs[4] = replace( | ||
| csa, | ||
| inner_attention=replace(csa.inner_attention), | ||
| indexer=replace( | ||
| csa.indexer, | ||
| inner_indexer=replace(csa.indexer.inner_indexer, topk=96), | ||
| ), | ||
| ) |
There was a problem hiding this comment.
inner_attention=replace(csa.inner_attention) copies the config without changing anything; it is left over from when index_topk lived there. The nested replace chain isn't needed either: deepseek_v4_debugmodel() builds a fresh config, and main already mutated it in place. A one-line mutation does the same job. With it, the from dataclasses import replace import at line 11 has no other user and can be dropped too.
| csa = attention_configs[4] | |
| attention_configs[4] = replace( | |
| csa, | |
| inner_attention=replace(csa.inner_attention), | |
| indexer=replace( | |
| csa.indexer, | |
| inner_indexer=replace(csa.indexer.inner_indexer, topk=96), | |
| ), | |
| ) | |
| attention_configs[4].indexer.inner_indexer.topk = 96 |
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.Config owns the fixed selection parameters ratio/topk, so the forward call no longer passes them, and DSV4InnerAttention no longer carries a second index_topk field: flops_per_token reads the indexer's value. Selection still uses attention_metadata.max_k, preserving the per-document width for packed documents. When return_scores is False the indexer returns an empty [T, 0] score tensor so the inner-attention boundary always receives tensors. This commit is interface-only: SPMD typechecking, TP-invariant indexer placement, and MHC/HC sharding are follow-up PRs.
63f6a8e to
40c2599
Compare
|
Addressed the remaining should-consider in Verification: 36 passed, 3 CUDA skipped; pre-commit clean. @claude review |
|
Claude finished @sdmyzlp's task in 45s —— View job Verdict: Approve -- the last item is fixed in |
There was a problem hiding this comment.
Verdict: Approve -- 40c2599 resolves the last item. The packed-document test now sets topk with a one-line in-place mutation. Nothing new has come up.
What this PR does. Indexer owns top-k selection through an InnerIndexer local-SPMD submodule. InnerIndexer.Config holds ratio/topk and returns (topk_indices, topk_scores), both TP-replicated. CompressedSparseAttention takes those two tensors in place of idx_q/idx_k/idx_w. When the aux loss is inactive, the indexer runs under no_grad and returns [T, 0] scores.
Example.
# main
idx_q, idx_k, idx_w = self.indexer(x, qr, ...)
self.inner_attention(q, kv, cmp_k, idx_q, idx_k, idx_w, sink, ...) # Indexer.select inside
# this PR
topk_indices, topk_scores = self.indexer(x, qr, ..., return_scores=training and aux_loss)
self.inner_attention(q, kv, cmp_k, topk_indices, topk_scores, sink, ...)Earlier findings
test_deepseek_v4_dsa.py:128: resolved.attention_configs[4].indexer.inner_indexer.topk = 96replaces the no-op/nestedreplacechain, and thedataclasses.replaceimport is no longer added.
Questions
- Merge order with #5863, which edits the same selection/loss path, is still open. A maintainer should confirm it with that PR's author.
Details
- Only the test line changed since
63f6a8e. Everything else in the diff is the same as in the previous approved review. - There are no remaining references to
inner_attention.index_topkorIndexer.selectin the repo. Theindex_topk=hits left inflavors.pyare arguments to_make_v4_attn_config, which forwards them toInnerIndexer.Config.
Not verified: a TP2 loss/grad_norm run at the head commit itself. The description says this, and everything after the measured revision is config plumbing and test edits. This touches only DSv4 model code, but a maintainer still needs to review.
tianyu-l
left a comment
There was a problem hiding this comment.
feel free to merge when it's ready
pytorch#6216 replaced Indexer.select with the InnerIndexer module. KimiSparseAttention now holds an InnerIndexer (ratio 1, the K3.1 top-k) in place of index_topk. InnerIndexer has no parameters, so state dict keys and the HF mapping do not change.
Summary (human-written)
Transform the previous
Indexer.selectoperation to be a dedicated module insideclass Indexer, has following benefits:Indexermore self-contained, and simplify the forward signature ofinner_attention.topk_scores.Why
Indexer.selectused to be called byDeepSeekV4Attentionon the indexer's raw features, so the inner-attention module owned the selection call and itsreturn_scoresdecision. This PR moves selection behind the indexer boundary and changes the inner-attention contract to consume the selection result.What changed
One interface-focused commit:
compressor.py:InnerIndexerowns selection.InnerIndexer.Configstores the fixedratio/topk, soIndexer.forwardandInnerIndexer.forwardno longer pass them per call.attention.py:CompressedSparseAttention.forwardtakestopk_indices/topk_scores;DeepSeekV4Attentionno longer carries a separateindex_topk.flops_per_tokenreadsindexer.inner_indexer.topk, soindex_topkhas a single source of truth.flavors.py:_make_indexer_configreceivesindex_topkand buildsInnerIndexer.Config.sharding.py: the inner-attention kernel declarestopk_indices/topk_scores, andInnerIndexergets its own local-SPMD config.attention_metadata.max_k, so packed documents keep the per-document width. The empty-key-pool guard is removed; the pool is assumed non-empty.return_scores=Falsereturns[T, 0]scores so the inner-attention boundary always receives tensors.Out of scope (follow-up PRs)
SPMD typechecking and TP placement are deliberately not changed here:
spmd_typecheckingfor DeepSeek-V4 is still not green. The 3-D query partition spec, compressor metadata typing, HC sharding, and MoE/debug-router paths are follow-up work.idx_q/idx_k/idx_w,topk_indices/topk_scores, and the indexer parameters remainR. Moving them tospmd.Iand removing the1/TPaux-loss gradient compensation is a separate change.Numerics and performance
Refactor only; no intended numerics change. The H800 comparison below was collected on
e87dc0dff, an earlier revision of this same interface (base8592e69c3). The current commit keeps the same(R, R)indexer boundary and only movesratio/topkinto config and removes the duplicateindex_topk; a fresh H800 run on63f6a8e14is still the cleanest confirmation.FSDP2 + TP2 (
dp_shard=2, tp=2, ep=2) and the TP2 control (dp_shard=1), debugmodel with packed documents and the indexer aux loss on, seed 42, 10 deterministic steps:Base and this revision were bit-identical at every step. With
index_topk=1024, the width fix used 4.21 GiB vs 6.71 GiB pre-fix and all revisions stayed bit-identical.Testing
36 passed, 3 CUDA cases skipped. Pre-commit passes on the changed files.
Known issues / follow-ups
topk_indices/topk_scoresandInnerIndexerafter this lands.tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.pyinto the mirroredmodels/deepseek_v4/directory is a separate change.