Skip to content

[dsv4] Encapsulate index selection behind InnerIndexer - #6216

Merged
sdmyzlp merged 1 commit into
pytorch:mainfrom
sdmyzlp:dsv4-inner-indexer
Nov 23, 2026
Merged

sdmyzlp merged 1 commit into
pytorch:mainfrom
sdmyzlp:dsv4-inner-indexer

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary (human-written)

Transform the previous Indexer.select operation to be a dedicated module inside class Indexer, has following benefits:

  1. Making Indexer more self-contained, and simplify the forward signature of inner_attention.
  2. Prepare for DeepSeek-V4.1, which reuse the output of Indexer across layers. And since the indexer loss (gradient) is linear w.r.t. teacher distribution, one can also leverage the autograd to accumulate the gradient for topk_scores.

Why

Indexer.select used to be called by DeepSeekV4Attention on the indexer's raw features, so the inner-attention module owned the selection call and its return_scores decision. This PR moves selection behind the indexer boundary and changes the inner-attention contract to consume the selection result.

# before
idx_q, idx_k, idx_w = self.indexer(x, qr, positions=..., attention_metadata=md)
cmp_topk, topk_scores = Indexer.select(idx_q, idx_k, idx_w, ..., attention_metadata=md)

# after
topk_indices, topk_scores = self.indexer(
    x, qr, positions=..., attention_metadata=md,
    return_scores=...,
)
self.inner_attention(q, kv, cmp_k, topk_indices, attn_sink, topk_scores=topk_scores)

What changed

One interface-focused commit:

  • compressor.py: InnerIndexer owns selection. InnerIndexer.Config stores the fixed ratio / topk, so Indexer.forward and InnerIndexer.forward no longer pass them per call.
  • attention.py: CompressedSparseAttention.forward takes topk_indices / topk_scores; DeepSeekV4Attention no longer carries a separate index_topk. flops_per_token reads indexer.inner_indexer.topk, so index_topk has a single source of truth.
  • flavors.py: _make_indexer_config receives index_topk and builds InnerIndexer.Config.
  • sharding.py: the inner-attention kernel declares topk_indices / topk_scores, and InnerIndexer gets its own local-SPMD config.
  • Selection width uses 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=False returns [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_typechecking for 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 remain R. Moving them to spmd.I and removing the 1/TP aux-loss gradient compensation is a separate change.
  • MHC/HC sharding is untouched; aligning it with the Norm SP/non-SP I/R split 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 (base 8592e69c3). The current commit keeps the same (R, R) indexer boundary and only moves ratio/topk into config and removes the duplicate index_topk; a fresh H800 run on 63f6a8e14 is 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:

Run step 1 loss / grad_norm step 10 loss / grad_norm
FSDP2 + TP2 8.125130653381348 / 3.866826057434082 3.6977646350860596 / 1.6038713455200195
TP2 control 8.079805374145508 / 4.087775230407715 3.6074934005737305 / 1.8479396104812622

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

python -m 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 \
  tests/unit_tests/cpu/recipes/test_deepseek_v4_dist_muon.py \
  tests/unit_tests/cpu/models/test_state_dict_adapter.py::DeepSeekV4StateDictAdapterTest

36 passed, 3 CUDA cases skipped. Pre-commit passes on the changed files.

Known issues / follow-ups

  • SPMD typechecking, TP-invariant indexer sharding, and MHC/HC sharding are follow-up PRs, as above.
  • [QSA] sparseindexerloss teacher #5863 can rebase onto topk_indices / topk_scores and InnerIndexer after this lands.
  • Moving tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py into the mirrored models/deepseek_v4/ directory is a separate change.

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

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

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

@sdmyzlp
sdmyzlp marked this pull request as draft November 19, 2026 03:30
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 2026
@sdmyzlp
sdmyzlp force-pushed the dsv4-inner-indexer branch 4 times, most recently from 28e2078 to 0412bbb Compare November 19, 2026 12:25
@sdmyzlp
sdmyzlp marked this pull request as ready for review November 19, 2026 14:08
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 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 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.

@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: 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

  1. torchtitan/models/deepseek_v4/compressor.py:260 -- max_seqlen=seqlen should be attention_metadata.max_k. Better: drop the parameter and read max_k inside InnerIndexer. As written, the selection grows wider with packed documents (see inline).
  2. Numerics proof is missing. idx_q / idx_k / idx_w used to enter the inner-attention local_map region as TP-replicated. Now topk_scores leaves a new local_map region 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 against main (scripts/loss_compare.py) on debugmodel with the indexer aux loss enabled and spmd_typechecking on, 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 asserting numel() == 0 (inline).
  • torchtitan/models/deepseek_v4/compressor.py:284-289 -- annotations dropped, and return_scores=True defaults 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 under tests/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))

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.

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.

@sdmyzlp

sdmyzlp commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Added the FSDP2 + TP2 verification to the PR description:

  • vs base 8592e69, loss and grad_norm are bit-identical at every step for FSDP2+TP2 (dp_shard=2, tp=2) and for the TP2 control (dp_shard=1), using the debugmodel with indexer aux loss and packed documents.
  • With index_topk=1024 to expose the width change, base, tip and pre-fix 0412bbb are all bit-identical; pre-fix used 6.71 GiB vs 4.21 GiB, confirming the fix restores the base selection width.
  • spmd_typechecking does not run on this branch or on main (pre-existing q partition-spec arity error and untyped compressor group geometry); the numerics ran with it off, and typing those paths is a follow-up.

Limitations are in the description: 4 ranks, no PP/CP, debugmodel only, equality check rather than convergence.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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. 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.py top-k width: resolved. InnerIndexer reads attention_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 8592e69c3 over 10 steps with packed docs and aux loss on. The index_topk=1024 run also confirms the width fix: 4.21 GiB at tip vs 6.71 GiB pre-fix. spmd_typechecking was off. I confirmed that the blocker is pre-existing on main: dsa_inner_attention_sharding_config gives the 3-D q a 2-entry partition spec from dense_activation_placement. The follow-up PR owns that.
  • (0, 0) placeholder: TODO added and the numel() assertion removed. The issue link is still missing (inline).
  • Annotations and the required return_scores: resolved.

Must fix

  1. torchtitan/models/deepseek_v4/compressor.py:329 -- add the spmd_types issue link to the TODO.
  2. tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_dsa.py:88 -- drop the assertion that just repeats the formula; the hard-coded 12 is the guard.

Should consider

  • torchtitan/models/deepseek_v4/attention.py:279 -- topk_scores is keyword-only, so its new input_shardings entry only feeds the boundary assert, never local_map's in_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,

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.

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))

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 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.

Suggested change
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;

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 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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@sdmyzlp please fix remaining comments

Comment thread torchtitan/models/base/sharding.py Outdated
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

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@sdmyzlp
sdmyzlp marked this pull request as draft November 21, 2026 09:25
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 21, 2026

@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: 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 scores

Earlier findings

  • @tianyu-l's question on base/sharding.py: addressed. The core change was reverted, so module.py, sharding.py and validation.py no longer appear in the diff, and the author explained why None failed in spmd_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-codes 12 and 0.
  • The topk_scores keyword-only typing note now has a comment at sharding.py:89.

Must fix

  1. torchtitan/models/deepseek_v4/compressor.py:325-333 -- scores are computed and then discarded in eval and in indexer_loss_coeff=0 training. 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 (required return_scores plus 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_scores in eval or with the loss disabled, or only topk_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.01 keeps 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 (same InnerIndexer boundary, (R, R) outputs) cover the training gradient path.
  • torch.set_grad_enabled(...) at attention.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 0 exists because scores are now always gathered from idx_k. Its shape depends only on T // 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.

Comment on lines +325 to +333
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

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 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 transient
  • logits_THK: THK = 1 GiB, plus about 1 GiB each for the relu and * w temporaries
  • 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:

  1. Skip it (my recommendation). Bring back a required return_scores: bool. When it is False, return an empty [T, 0] tensor. That needs no None round trip any more, because topk_scores is now a plain tensor argument that _gather_attn ignores when the loss is off. The idx_k.size(0) guard above may then only be needed on the scored path.
  2. 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.

@sdmyzlp

sdmyzlp commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 -- 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 main

Earlier findings

  • Always-computed scores (compressor.py): resolved. compressor.py:328-329 returns before compressed_gather_indices. The [T, 0] placeholder goes through (R, R) output shardings, so base/ needs no change. _gather_attn never reads it when aux_loss is inactive (attention.py:155). SlidingWindowAttention already passes [T, 0] tensors to gather_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 on compressed_gather_indices can 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=0 gives aux_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 on return_scores, and the test at line 277 checks exactly that. idx_k.size(0) is T // ratio, which is static under fixed-shape metadata.
  • All in-repo callers of the old Indexer.select and the old idx_q/idx_k/idx_w signature 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.

Comment on lines +264 to +276
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()

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.

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:

Suggested change
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))

@sdmyzlp

sdmyzlp commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Rebased onto latest main (a75b09a7d) and squashed the six review iterations into one commit (4ddfcf697).

Cleanup in the squashed revision:

  • Kept the caller-level grad control, matching Qwen3.8 Flash-Next QSA: DeepSeekV4Attention wraps the indexer call in torch.set_grad_enabled(torch.is_grad_enabled() and return_scores), so the no-loss path builds no indexer graph; Indexer.forward only projects and selects.
  • topk_scores is positional in CompressedSparseAttention.forward, so the sharding entry is part of the local-region input contract.
  • Tests now use shape checks instead of patching compressed_gather_indices; eval path uses a forward hook.

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).

@sdmyzlp

sdmyzlp commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Updated the branch with two commits:

  • dfbe9adb9 stores ratio/topk in InnerIndexer.Config, makes the indexer projections/features/selection outputs TP-invariant (spmd.I), fixes the 3-D attention query partition spec, and removes the manual 1/TP aux-loss gradient compensation.
  • ac5fd4456 adds a fake-PG TP=2 test that builds one CSA layer, parallelizes it, and runs the forward with spmd_typechecking=True. It covers the indexer boundary, the 3-D query placement, and the compressor metadata geometry.

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

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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: 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/topk into InnerIndexer.Config.
  • It retypes the indexer's params, inputs and outputs from R to I on TP (identical value and gradient on every rank). With that, it deletes the 1/TP scaling of the aux-loss gradient.
  • It fixes the 3-D q partition 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_indices mock 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

  1. TP numerics for the new I sharding (see above). No inline line: the change is spread over sharding.py, flavors.py and the deleted compressor.py scaling.
  2. flavors.py:195 -- topk is now set in InnerIndexer.Config and in DSV4InnerAttention.Config.index_topk, which only flops reads. An override of the latter silently doesn't change selection (inline).
  3. test_deepseek_v4_dsa.py:30 -- seqlen=64 makes n_cmp == topk, so the top-k equivalence test no longer tests ranking (inline).
  4. 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 a DeepSeekV4CompressedSparseAttentionMetadata.annotate_spmd_types() override, not once per compressor call in every layer (inline).
  • sharding.py:158-163 -- invariant_activation_placement duplicates dense_activation_placement(tp=spmd.I, cp=spmd.S(0)) (inline).
  • flavors.py:136-142 -- the state_tp default and the is spmd.I branch can go away (inline).
  • test_deepseek_v4_indexer_loss.py:50-58 -- **kwargs is now unused (inline).
  • Scope: 4ddfcf6 is validated and approved, while dfbe9ad is a separate concern (TP gradient typing) with its own numerics debt. Moving dfbe9ad/ac5fd44 into 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

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.

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.

Suggested change
seqlen, ratio, topk = 64, 4, 16
seqlen, ratio, topk = 128, 4, 16

Comment on lines +171 to +178
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)

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 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.

Comment on lines +158 to +163
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),
)

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 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.

Comment on lines +136 to +142
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")
)

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.

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)}
)

Comment on lines +50 to +58
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)

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.

**kwargs lost its only caller when dfbe9ad removed the empty-pool case. No call site passes it now, so revert to main's helper.

Suggested change
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)

@sdmyzlp

sdmyzlp commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Reset the branch to a single interface-only commit (4ddfcf697). This PR now contains only the InnerIndexer interface change; SPMD typechecking, TP-invariant indexer sharding, and MHC/HC sharding are explicitly deferred to follow-up PRs in the description.

@claude review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @sdmyzlp's task in 2m 3s —— View job


Verdict: Approve -- the reset to 4ddfcf6 makes every earlier must-fix moot; one item remains: put the TP2 numerics evidence back in the description. See the 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 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 I sharding, the duplicated topk field, the seqlen=64 test, the dropped [256, 128, 384] case, metadata typing in the compressor, invariant_activation_placement, and the state_tp branch: all moot, because that commit is no longer in the PR. seqlen=512 and [256, 128, 384] are back at test_deepseek_v4_dsa.py:29,133.
  • _metadata(**kwargs): it now has a caller (the max_context_length=12 empty-pool case at test_deepseek_v4_indexer_loss.py:253), so keep it.

Must fix

  1. 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=2 and the TP2 control, packed docs, aux loss on, index_topk=1024 width check). Also say which revision it ran on. It predates the core-sharding revert and the squash, so either rerun it on 4ddfcf6 or 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.select and the idx_q/idx_k/idx_w inner-attention signature are used only by DSv4 and its tests, and all of them are updated. qwen3_8_flash_next has its own indexer and is not affected. No README mentions the old API.
  • return_scores (attention.py:457-460) uses the same condition _gather_attn uses 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 == 4 layers 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 in models/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.

@sdmyzlp

sdmyzlp commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed a single interface-focused commit (63f6a8e14) addressing the open review items:

  • InnerIndexer.Config now owns ratio / topk; the duplicate DSV4InnerAttention.Config.index_topk is removed and flops_per_token reads the indexer value.
  • Removed the empty-key-pool guard and its test case.
  • PR description now includes the FSDP2 + TP2 / TP2-control bitwise numbers and the index_topk=1024 width comparison, with the revision they were collected on.
  • SPMD typechecking, TP-invariant indexer sharding, and MHC/HC sharding remain explicitly out of scope for follow-up PRs.

@claude review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @sdmyzlp's task in 1m 25s —— View job


Verdict: Approve -- the numerics evidence is back in the description and topk now lives in one config field; one optional test cleanup remains. See the 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 -- 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 together

Earlier findings

  • Numerics evidence in the description: resolved. The FSDP2+TP2 and TP2-control numbers and the index_topk=1024 width check are back, labeled as collected on e87dc0dff. The reason they still apply is stated: the (R, R) boundary is unchanged.
  • Duplicate topk (raised against dfbe9ad): resolved here. DSV4InnerAttention.Config.index_topk is gone. The flavors, the MTP block and the tests are all updated. No recipe or other model references the field: the index_topk hits under experiments/transformers_modeling_backend are HF config attributes, not this field.
  • Empty-pool guard removed: k = min(self.topk, max_k // self.ratio) is the same as main's min(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-op replace(csa.inner_attention) and a nested replace chain where a one-line in-place mutation works (inline).
Details
  • Call order in DeepSeekV4Attention.forward is the same as on main: indexer, then compressor, then inner attention. The ratio-128 path builds compressor_128 only, as before.
  • return_scores (attention.py:456-459) uses the same condition _gather_attn uses to read scores (attention.py:153), so scores are never missing when the loss needs them.
  • assert self.indexer is not None in flops_per_token: only compress_ratio == 4 layers get an indexer config, so this is an internal invariant.
  • inner_indexer_sharding_config uses a 3-D spec for idx_q and replicated_activation_placement() for the rest. That matches the R placement idx_q/idx_k/idx_w had 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.

Comment on lines +129 to +137
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),
),
)

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.

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.

Suggested change
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

@sdmyzlp
sdmyzlp marked this pull request as ready for review November 23, 2026 00:03
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 23, 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.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.
@sdmyzlp

sdmyzlp commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the remaining should-consider in 40c25992e: the packed-document test now sets inner_indexer.topk = 96 in place instead of the no-op/nested replace chain.

Verification: 36 passed, 3 CUDA skipped; pre-commit clean.

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @sdmyzlp's task in 45s —— View job


Verdict: Approve -- the last item is fixed in 40c2599 (the test now sets topk in place), and nothing new came up. See the 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 -- 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 = 96 replaces the no-op/nested replace chain, and the dataclasses.replace import 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_topk or Indexer.select in the repo. The index_topk= hits left in flavors.py are arguments to _make_v4_attn_config, which forwards them to InnerIndexer.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 tianyu-l 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.

feel free to merge when it's ready

@sdmyzlp
sdmyzlp merged commit 692c9bb into pytorch:main Nov 23, 2026
15 checks passed
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 23, 2026
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.
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