Skip to content

[Deepseek V4] Dsv4 sparse indexer loss - #4835

Merged
tianyu-l merged 6 commits into
pytorch:mainfrom
Matrix-Z97:dsv4-sparse-indexer-loss
Oct 12, 2026
Merged

tianyu-l merged 6 commits into
pytorch:mainfrom
Matrix-Z97:dsv4-sparse-indexer-loss

Conversation

@Matrix-Z97

@Matrix-Z97 Matrix-Z97 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add DeepSeek V4 sparse indexer auxiliary loss for CSA layers.

This change wires the community AuxLoss framework into DeepSeek V4 compressed sparse attention so the sparse indexer can be trained from the main attention distribution. The loss is implemented as SparseIndexerLoss under deepseek_v4/compressor.py and is configured only for compress_ratio == 4 CSA layers.

Changes

  • Add SparseIndexerLoss(AuxLoss) for indexer distillation.
  • Update Indexer.select(...) to return both:
    • topk_indices
    • differentiable topk_scores
  • Inject indexer loss through FlexAttention out_transform, using attention LSE as teacher normalization.
  • Keep teacher tensors detached while preserving gradient through indexer scores.
  • Register register_aux_loss_zero_hook in the DeepSeek V4 optimizer post-build hook.
  • Add unit coverage for loss value/gradient/metric accumulation, DSV4 config wiring, and Indexer.select(...).

Validation

  • python -m py_compile torchtitan/models/deepseek_v4/compressor.py torchtitan/models/deepseek_v4/attention.py tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py
  • 4-GPU smoke test with:
    • tp=2
    • ep=2
    • DeepSeek V4 spmd_types path
    • training completed successfully
  • Probe confirmed:
    • Indexer.select(...) returned topk_scores with requires_grad=True
    • SparseIndexerLoss.forward(...) received differentiable scores
    • aux loss accumulation was non-zero

Compared the DSV4 debug model using 4 GPUs with EP2+TP2 and 2 GPUs with EP2+TP1, both using:

  • SPMD backend and DP=2
  • Packed c4_test, context length 2048
  • 32768 nominal tokens per training step
  • Seed 42 and deterministic algorithms
  • No activation checkpointing

Initial parameters and all 20 steps of inputs were verified identical by hashes.

Whole-Model BF16 Comparison

Metric Step EP2+TP2 (4 GPUs) EP2+TP1 (2 GPUs) Absolute Difference
Main loss 1 8.125186920166016 8.125230789184570 4.3869e-5
Main loss 20 3.082187891006470 3.082170724868774 1.7166e-5
Indexer loss 1 0.011295149103 0.011287716217 7.4329e-6
Indexer loss 20 0.001989979297 0.001968421973 2.1557e-5
Gradient norm 1 3.866095066071 3.866033077240 6.1989e-5
Gradient norm 20 0.555801510811 0.557279169559 1.4777e-3

Notes

Local pytest collection is blocked by the local environment missing torch_remat; this is an environment dependency issue and matches the existing local setup behavior.

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

pytorch-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

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

@Matrix-Z97 Matrix-Z97 changed the title [feat] Dsv4 sparse indexer loss [Deepseek V4] Dsv4 sparse indexer loss Sep 22, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

Also, would it work well with optimizations in #4452?

@tianyu-l
tianyu-l requested a review from drisspg September 22, 2026 23:40
@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

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


Review: DeepSeek V4 sparse indexer loss

Overall: The design fits the existing framework: it hooks into out_transform to get the LSE and uses AuxLoss.inject with out as the carrier. The teacher inputs are detached, so the gradient only reaches the indexer. Before this PR, topk cut the indexer off from the graph, so its parameters got no gradient at all. This PR fixes that.

I checked the select rewrite: it picks the same entries as before. Valid scores keep their order, and masked slots still end up as -1. So the main-loss selection should be bit-identical. It would still be good to confirm that with a --debug.deterministic loss comparison.

There are two problems I'd fix before merging (TP and memory), plus some smaller items.


🔴 1. The result depends on the TP degree: gradient is scaled by tp and the metric isn't reduced over TP

attention.py:248 / compressor.py:264

  • q goes into the inner attention as tp=S(1) (sharding.py:73), and so does lse. So _teacher computes (...).sum(dim=1) / q_THK.size(1) using only the local heads, divided by the local head count.
  • Each TP rank therefore gets a different teacher p_TJ.
  • The student (idx_q/idx_k/idx_w, sharding.py:84-86) and the indexer weights (sharding.py:183-189) are tp=R. Their backward is Partial, so the per-rank gradients get summed over TP.
  • The gradient term -p · log_softmax(s) is linear in p. Summing it over TP ranks gives tp × the gradient you would get from the teacher averaged over all heads.
  • So the effective coeff grows with the TP degree. With tp=2 in your smoke test, the effective coefficient was 0.02.
  • If these gradients are not summed on some path, the problem is worse: the replicated indexer weights drift apart across TP ranks without any error.
  • The logged metric has the same issue. reduce_mesh="loss" reduces over dp+cp only, so each TP rank logs its own local-head value.

Suggested fix: divide by the global n_heads (pass it in SparseIndexerLoss.Config) instead of q_THK.size(1). Then the per-rank partial teachers add up to the global teacher, and the summed gradient is exact. For the metric, the xlogy(p, t) term isn't linear, so it needs an explicit TP reduction, or you could all-reduce p_TJ (small: T×J fp32, no grad) before computing the loss.

Please also add a test that checks tp=1 and tp=2 give the same indexer gradient (for example in the fake-pg suite). The CLAUDE.md rules ask for this for distributed changes.

Fix this →

🔴 2. Indexer.select now keeps a T×H_idx×N score tensor alive until backward

compressor.py:208-222

Before this PR, the sht scores tensor was dropped as soon as topk returned its indices. Now topk_scores is kept in the autograd graph, so the full einsum, relu and * idx_w intermediates are saved for backward.

For the 284B-A13B config (index_n_heads=64, ratio 4) at T=8192 per rank, that is 8192 × 64 × 2048 ≈ 1.07e9 elements. That's about 2 GiB in bf16 per saved tensor, several saved tensors per layer, across 21 CSA layers. It also grows as O(T²), even though only topk of the N columns ever get a gradient.

Suggested approach: do the selection under torch.no_grad() (and put back the in-place relu_). Then recompute the student scores only for the selected entries: gather idx_k[topk_indices] to get [T, J, D], then einsum("thd,tjd->thj"), relu, * w, and sum over h. That costs O(T·H·J) with a fixed J=index_topk, and it keeps the eval and no-loss paths exactly as cheap as before.

The second commit folded the scoring into select. I'd undo that and use a separate gather-based score(...) step.

Fix this →

🟡 3. The teacher needs a lot of temporary memory, and one step isn't in fp32 as the comment says

compressor.py:256-262

  • cmp_k_NK[topk_indices_TJ] builds a [T, J, head_dim=512] tensor. At T=8192 and J=512 that's about 4 GiB in bf16.
  • logits_THJ in fp32 adds about 1 GiB (with 64 heads per rank).
  • Nothing is saved for backward, but it's a large per-layer peak. Under FullAC/SAC the whole block is re-run in backward, so this cost is paid twice.
  • Consider chunking over T.
  • Precision: einsum(...).float() runs the matmul in bf16 and only casts the result. The comment says the computation is in fp32 to protect exp(comp_lse - lse), but these logits have already lost precision in bf16. Cast q/cmp_k to fp32 before the einsum, or pass dtype/accumulate in fp32.

🟡 4. The test compares the implementation to a copy of itself

test_deepseek_v4_indexer_loss.py:21-53 copies _teacher and _logged_kl line for line. That checks the plumbing but not the math.

It would be much stronger to build a small dense case and compare against it. Compute the full softmax over [swa | cmp | sink] by hand with the sink logit, sum the probabilities per head on the selected compressed entries, and take the lse from a real flex_attention(return_aux=AuxRequest(lse=True)) call. That checks two assumptions nothing currently tests: that flex returns the LSE in natural log (not log2), and that the sink and SWA entries are really in the denominator.

🟡 5. Please explain why the loss is weighted by mass

SparseIndexerLoss weights each row by the raw mass p (not the normalized t), so rows dominated by SWA or the sink contribute little. DSA in V3.2 uses KL against the L1-normalized head-summed attention. If V4 changed this, please cite the source in the docstring. If it's your own choice, please show convergence evidence (for example a C4 run of indexer recall / main loss vs. the unweighted KL). CLAUDE.md asks for this for computation changes.

🟢 Smaller items

  • __init__.py:1032: _post_optimizer_build_fn is an exact copy of deepseek_v3/__init__.py:692. DSV4 already imports from deepseek_v3, so reuse that one, or move it to common code.
  • __init__.py:249: coeff=0.01 is hard-coded, with no way to set it from a flavor or config, and no way to turn the loss off without editing code. Consider making it a flavor parameter.
  • attention.py:248: cmp_k is not None can never be false here: CSA always builds cmp_k, and the missing-idx case already raises. Also, if the loss is configured but skipped for any reason, a warning should be emitted, per CLAUDE.md.
  • Activation checkpointing: under FullAC/SelectiveAC the metric is double-counted (a known AuxLoss limitation, documented in aux_loss.py). Worth noting in the PR, since DSV4 configs usually enable AC.
  • CP: the class docstring says cmp_k/idx_k should be all-gathered for global selection, but the sharding still declares cp=S(0). select builds its causal limits from local seqlen, so the teacher and student both only see the local shard. This problem predates the PR, but it means reduce_mesh="loss" is summing per-shard losses that are already approximate.
  • Tests: I couldn't run them here because the tool calls needed permission. As your notes say, collection also needs torch_remat.

Compatibility with #4452

I couldn't open #4452 in this run: gh and web fetch both need permission I don't have. So this part is based on the extension points documented in this PR's DSV4FlexInnerAttention docstring, not on the other PR's code. The risk depends on what #4452 changes:

  • Replacing _build_block_mask only (e.g. a faster mask or varlen kernel): compatible. The loss only needs out and lse from the same softmax.
  • Overriding forward / _forward_impl with a fused sparse kernel (SMLA/CSA): the loss would be dropped with no warning. It is only wired up through FlexInnerAttention.forward(out_transform=...) inside _forward_impl. To make both work, the fused kernel has to return the LSE, and the loss has to be triggered from a small shared helper (e.g. self._maybe_inject_indexer_loss(out, lse, q, cmp_k, cmp_topk, topk_scores)) that any backend can call, instead of from the flex call site.
  • Fused top-k or indexer kernel (index-only output): this conflicts with the new (indices, scores) return type of Indexer.select. The gather-and-recompute design from item 2 separates the two steps: a fused kernel can do the no-grad selection, and the small gathered rescoring gives the student scores. I'd recommend that design anyway because of the memory issue.
  • CP all-gather of cmp_k/idx_k: compatible, and it would make the teacher correct under CP. The teacher gathers from whatever cmp_k it gets, so a global cmp_k is handled correctly.

If you share the key change in #4452 (kernel swap vs. mask or indexer optimization), I can give a precise answer.

@drisspg

drisspg commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

I am about to put up a pr to update our impls to attn-gym, can we wait till after this change to land this?

@tianyu-l

tianyu-l commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@Matrix-Z97 could you update this PR? I believe driss change is merged

@Matrix-Z97
Matrix-Z97 force-pushed the dsv4-sparse-indexer-loss branch from f53d760 to b5b60d1 Compare October 8, 2026 06:30
@tianyu-l

tianyu-l commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@claude review the latest change

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of the latest change (rebased onto the attn-gym gather_attn / lightning_indexer backend)

  • Read the rebased diff
  • Check whether the earlier review items were addressed
  • Check for new issues after the attn-gym update
  • Post review

Overall: This revision is a real improvement. The memory problem in Indexer.select is fixed. Selection now runs under torch.no_grad() through lightning_indexer, and the student logits are recomputed only for the selected entries, so the cost is O(T·H·K·D) instead of O(T·H·N). The test now compares against a reference instead of a copy of private methods, and padded documents are handled through cu_seqlens. The rebase also answers the #4452 / attn-gym question: the loss no longer depends on flex out_transform. It sits next to gather_attn and rebuilds the softmax denominator itself.

That new design brings its own risk (item 2), and the TP scaling problem from the last review is still there.

Earlier item Status
🔴 1. TP-dependent gradient / metric Not addressed
🔴 2. T×H×N score graph kept alive ✅ Fixed (gather and recompute)
🟡 3. Teacher temporary memory and bf16 einsum Partly. Now worse on memory: the window gather was added
🟡 4. Test is a copy of the implementation Partly. The reference still mirrors _teacher line for line
🟡 5. Why weight by mass Not addressed
🟢 coeff=0.01 hard-coded Not addressed

🔴 1. The gradient still scales with the TP degree (still open)

compressor.py _teacher, last line: ... .sum(dim=1) / q_THD.size(1)

Inside the CSA inner attention, q is tp=S(1) (sharding.py:70), and so is attn_sink (sharding.py:29). So each TP rank builds its teacher p_TK from its local heads, divided by the local head count. The student inputs idx_q/idx_k/idx_w are tp=R (sharding.py:81-83), so their gradients are summed over TP. The loss is linear in p, so the summed gradient is tp × the gradient for the head-averaged teacher. In effect, coeff becomes 0.01 * tp.

The logged metric has the same problem, and it is worse there: xlogy(p, t) is not linear, and reduce_mesh="loss" doesn't reduce over TP.

Suggested fix: divide by the global n_heads (add it to SparseIndexerLoss.Config and set it in _make_v4_attn_config). Then the per-rank partial teachers add up exactly to the global teacher. An all-reduce of p_TK over TP before computing t_TK and the metric fixes both problems at once, and it's cheap (T×K fp32, no grad). Please add a check that tp=1 and tp=2 give the same indexer gradient (fake-pg would work, since this PR already has ciflow/fake-pg).

Fix this →

🔴 2. The teacher's softmax denominator is rebuilt by hand, and nothing checks it against gather_attn

compressor.py _window_logits / _teacher

mass_TH = exp(cmp_lse - logsumexp([window_lse, cmp_lse, sink])) is only correct if three things match gather_attn exactly:

  • Window semantics: keys t-W+1 .. t, inclusive of the query, with exactly W entries.
  • Sink semantics: the sink is a logit in the denominator only, not scaled by softmax_scale.
  • Overlap: the SWA keys and compressed keys don't overlap or get deduplicated.

If any of these is off by one (for example, the window is W+1 wide or excludes self), the loss trains toward the wrong target, and nothing will warn you. The test can't catch it, because _reference_teacher uses the same formula.

The cheapest strong check: in the test, rebuild the attention output from the teacher's per-head probabilities (softmax([swa | cmp | sink]) · V) and assert_close it against gather_attn(..., impl="reference") on the same inputs, including a packed cu_seqlens case. If gather_attn can return its LSE, use that LSE directly in the loss. That also removes the duplicated window and denominator work (see item 3).

🟡 3. The teacher needs a lot of temporary memory and computes logits in bf16

The new _window_logits builds swa_k_TD[key_TW] → [T, W, 512], on top of the existing cmp_k_SD[gather] → [T, K, 512]. At T=8192, W=128, K=512 that is about 1 GiB + 4 GiB in bf16, plus [T, H_local, W+K] fp32 logits, on each of the 21 CSA layers. Under FullAC the whole thing runs again in backward.

Neither einsum can use einsum("thd,tkd->thk") as a matmul without first materializing the gathered keys. Consider chunking over T, or using gather_attn's LSE as in item 2.

einsum(...).float() still runs the matmul in bf16 and only casts the result. Cast the inputs to fp32 (or chunk and then cast) if the precision of exp(cmp_lse - full_lse) matters.

🟡 4. Padded tokens add to raw_sum but are excluded from the denominator

aux_loss_denominator is the routed-token count, which excludes padding (collators.py:113, built from padding_mask). SparseIndexerLoss sums over all T, including padding positions. Padding blocks get their own cu_seqlens segment, so their teacher is finite and non-zero. The result: the loss scale depends on how much padding there is, and the indexer is trained on padding attention.

Pass padding_mask down (the block already has it) and mask those rows out of slot_valid_TK.

🟡 5. Please explain why the loss is weighted by mass (still open)

weighted = xlogy(p, t) - p * log s is a KL weighted by the raw compressed mass. DSA in V3.2 uses an unweighted KL against the L1-normalized, head-summed attention. Please cite the V4 source in the docstring, or show convergence evidence (CLAUDE.md asks for this for computation changes).

🟢 Smaller items

  • compressor.py _global_compressed_indices: hard-codes compressed_cu_seqlens(cu_seqlens, 4). It's correct today only because the loss is attached when ratio == 4. It also duplicates the doc-offset logic in Indexer.select, so searchsorted runs three times per layer (select, global indices, window). Consider returning global gather indices from select, or sharing one helper that takes ratio.
  • Indexer.select: always builds the differentiable topk_scores (gather + einsum with grad), even in eval and when aux_loss is None. Gate it, or move scoring into a separate method that only the loss path calls. That keeps select index-only for fused-kernel backends.
  • SparseIndexerLoss.forward: logits_TK.masked_fill(~row_valid_T…, 0.0) is redundant. _logged_kl immediately applies masked_fill(~slot_valid_TK, -inf) and then fills fully invalid rows with 0.
  • attention.py:136: RuntimeError when the denominator is missing matches moe.py:301, so that's fine. But the topk_scores_TK is not None guard is always true on the CSA path, so that check can go.
  • flavors.py:240: coeff=0.01 is still hard-coded, with no flavor or config knob to tune it or turn the loss off.
  • AC: under FullAC the metric over-counts 2x (a documented AuxLoss limitation). Please mention this in the PR, because DSV4 recipes usually enable AC.
  • CP: the indexer and teacher still only see the local cp=S(0) shard. This predates the PR, but reduce_mesh="loss" then sums per-shard approximate losses.
  • Validation: please add a --debug.deterministic loss comparison showing that the main loss is unchanged by select's new no_grad + rescoring path, plus a short convergence run with the aux loss on.

I didn't run the tests in this job. Collection needs torch_remat / attn_gym, and the shell commands needed for that required permission I don't have.

@Matrix-Z97
Matrix-Z97 force-pushed the dsv4-sparse-indexer-loss branch from 7eeb43b to f017fc9 Compare October 9, 2026 02:53
@tianyu-l

tianyu-l commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

@claude please review again

@claude

claude Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Re-review: DeepSeek V4 sparse indexer loss

  • Read the latest diff (b5b60d1, f017fc9)
  • Check whether the earlier review items were addressed
  • Look for new issues
  • Post review

Overall: Most of the earlier review is addressed. The two remaining problems are both cheap to fix:

  • The new TP-equivalence test never runs in CI.
  • The default objective is the mass-weighted variant, which has no convergence evidence yet.

I would merge once those two are handled and a loss comparison is attached.

Earlier item Status
🔴 TP-dependent gradient / metric ✅ Fixed. p_TK is divided by the global num_heads and all-reduced over TP, so every rank has the global teacher and the metric matches across ranks. The student gradient is scaled by 1/tp, so summing the tp=R (→ Partial) gradients over TP gives the right total. This matches how cmp_k / idx_* gradients are already reduced.
🔴 Softmax denominator rebuilt by hand ✅ Fixed. The loss now uses gather_attn(..., return_aux=AuxRequest(lse=True)). The CPU test checks both out and lse against a separate dense reference that enumerates every key, covering window, sink, and packed cu_seqlens. That was the check I asked for.
🟡 Teacher memory / bf16 einsum ✅ Fixed. The teacher is computed in chunks over T, with fp32 inputs and autocast off. The window gather is gone.
🟡 Padding counted in raw_sum ✅ Fixed. padding_mask_T masks both the teacher and the student slots. Its placement (token_id_placement(), TP=R) matches what the decoder passes in.
🟡 Why weight by mass Partly. The docstring now cites V3.2 and says mass weighting is an implementation choice. But it is still the default (see 2).
🟢 coeff hard-coded / no way to turn it off ✅ Fixed. build_model_config(indexer_loss_coeff=..., indexer_loss_mass_weighted=..., indexer_loss_chunk_size=...) sets these, and coeff=0 turns the loss off.
🟢 Scores always built ✅ Fixed. return_scores=self.training and self.aux_loss is not None, and a test covers it.
🟢 Duplicated searchsorted / doc offsets ✅ Fixed. The logic is shared in compressed_gather_indices.
AC metric over-count, CP local-only Still open. Both predate this PR, but they should be noted in the PR description.

🔴 1. The TP-equivalence GPU test is skipped in CI

tests/unit_tests/gpu/test_deepseek_v4_indexer_loss.py:22

unit_test_gpu.yaml runs pytest tests/unit_tests/gpu -m "not multi_gpu" on the single-GPU runner and -m multi_gpu on the multi-GPU runner. This test has no multi_gpu marker, so:

  • On the single-GPU lane, skipUnless(device_count() >= 2) skips it.
  • The multi-GPU lane never selects it.

So the one test that checks the TP fix never runs. Add pytestmark = pytest.mark.multi_gpu, as test_mxfp8_fsdp.py and test_fsdp_moe_sharding.py do.

There is also a smaller gap. The test runs the inner module without its ShardingConfig, and it does dist.all_reduce(tensor.grad) itself to stand in for the TP gradient sum. So it checks the loss math, not that the real model sums the idx_* gradients over TP. A tp=1 vs tp=2 loss/grad_norm comparison on the debug model (fake-pg, or scripts/loss_compare.py) would cover the actual wiring.

Fix this →

🟡 2. The default objective differs from the paper and has no evidence

compressor.py SparseIndexerLoss.Config.mass_weighted: bool = True, and flavors.py indexer_loss_mass_weighted: bool = True

The docstring now says mass weighting is "not a claim about the paper's objective". Even so, every DSV4 run gets it by default.

Under CLAUDE.md, a computation change needs convergence evidence. Either:

  • default to False (the V3.2 normalized KL), or
  • attach a C4 run comparing the two (main loss plus indexer recall / KL) to justify True.

The PR description also still has no --debug.deterministic loss comparison. That comparison should show the main loss is bit-identical before and after with indexer_loss_coeff=0, which checks the new no_grad selection and return_aux path. A second, short convergence run with the loss on would also help.

🟡 3. The student rescoring keeps about 2 GiB per CSA layer alive for backward

compressor.py Indexer.select, the return_scores branch

The teacher is now chunked, but the student is not:

  • selected_TKD = idx_k[gather_indices_TK] ([T, K, D_idx]) and the [T, H_idx, K] relu/mul intermediates are all saved for backward.
  • For the 284B config at T=8192 (H_idx=64, D_idx=128, K=512), that is about 1 GiB for the gathered keys plus about 0.5 to 1 GiB of logits intermediates, per CSA layer, in bf16.
  • With 21 CSA layers and no AC, that adds tens of GiB.

This is much better than the original O(T·H·N), and AC hides most of it. Still, a small custom autograd.Function would avoid saving the gathered [T, K, D] tensor. It would save idx_q, idx_k, idx_w and the indices, then re-gather in backward. Chunking the rescoring over T would also work. Fine as a follow-up TODO.

🟢 Smaller items

  • compressor.py _teacher: use MeshAxisName.TP instead of the string "tp" in spmd_mesh_size / spmd_mesh_group, to match the rest of the DSV4 code.
  • compressor.py _teacher: the head-count check raises ValueError. But num_heads comes from n_heads in _make_v4_attn_config, so a mismatch means a programmer error. CLAUDE.md says to use assert for that.
  • Indexer.select(..., return_scores: bool = True): the default builds the autograd graph. The only caller passes the flag explicitly, so a default of False (or making the argument required) would keep a future caller from paying this cost by accident.
  • flavors.py build_model_config: indexer_loss_chunk_size <= 0 is checked here and again in SparseIndexerLoss.Config.__post_init__, which dataclasses.replace re-runs. The coeff=0.01 default is also set in two places (_make_v4_attn_config and the build_model_config default). Keep one of each.
  • SparseIndexerLoss.forward: returning early on numel() == 0 is safe under TP, because every rank has the same shape and so they all skip the all-reduce together.

I didn't run any tests in this job, because pytest needs a permission I don't have.

@tianyu-l

tianyu-l commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

@Matrix-Z97 thank you

Would you like to address two remaining minor issues, or should we merge as is

@Matrix-Z97

Copy link
Copy Markdown
Contributor Author

@Matrix-Z97 thank you

Would you like to address two remaining minor issues, or should we merge as is

Thanks for the review! I’ve changed the default to unweighted KL while retaining mass weighting as an explicit opt-in, with CPU tests covering both configuration paths.
I’ve also removed the standalone TP-equivalence GPU test. For validation of the actual model wiring, I completed a whole-model EP2+TP1 vs. EP2+TP2 comparison using identical initial weights and inputs.
The numerical comparison is summarized above. I believe the PR is ready to merge now. Thanks again!

@tianyu-l

tianyu-l commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

@claude are we good to go?

@claude

claude Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 44s —— View job


Yes, good to go once CI is green

  • Read the latest commits (5bd24fc, 70ce247)
  • Check CI status
  • Post verdict

Both items left open in the last review are now handled.

Item Status
🟡 Default objective had no evidence behind it ✅ Fixed. SparseIndexerLoss.Config.mass_weighted and build_model_config(indexer_loss_mass_weighted=...) both default to False now, which is the V3.2-style normalized KL. Mass weighting is still available but you have to turn it on. The docstring now says so. A new CPU test, test_configuration_defaults_to_unweighted_kl, checks the default for every CSA layer of the debug model. The tuning test now covers the True path, and the loss-value test already ran both settings.
🔴 TP-equivalence GPU test skipped in CI ✅ Fixed by deleting the test. The PR description now has a whole-model EP2+TP2 vs. EP2+TP1 comparison instead. It used identical initial weights and identical inputs (checked by hash), with seed 42, deterministic mode, and 20 steps. That covers more than the standalone test did, because it runs the real model, including its sharding config and the TP gradient sum on idx_*. The differences are small: about 1e-5 on main loss and indexer loss, and a grad_norm drift of about 0.3% by step 20. That is what you'd expect from bf16 with a different TP reduction order, so it confirms the TP fix (num_heads global divisor plus the all-reduce of p_TK).

CI: Lint, CPU Unit Test and GPU Unit Tests are all still queued or running for the latest push. I'd wait for them to pass. The CPU run is the first one in CI to collect the new tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py, which locally needed torch_remat / attn_gym.

Optional, not blocking

  • Main-loss bit-identity check: this hasn't been run yet. It compares main against this branch with indexer_loss_coeff=0 under debug.deterministic, and should show the main loss is unchanged by the new no_grad selection and return_aux path. The code reads as equivalent, so this is a cheap extra check rather than a blocker.
  • Things to add to the PR description:
    • Under FullAC/SAC the indexer-loss metric is counted twice. This is a known AuxLoss limitation.
    • Under CP, the indexer and teacher only see the local shard. This predates the PR.
  • Follow-up TODO: the student rescoring saves the gathered [T, K, D_idx] keys for backward. Chunking it or using a custom autograd.Function would cut that memory when AC is off.

I didn't run the tests myself in this job. The verdict comes from reading the diff and from the CI status.

@tianyu-l

tianyu-l commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

@Matrix-Z97 please fix test failures (could wait until current round finishes before next push so all errors are exposed)

@tianyu-l

Copy link
Copy Markdown
Contributor

@Matrix-Z97 sorry need another rebase

@Matrix-Z97
Matrix-Z97 force-pushed the dsv4-sparse-indexer-loss branch from 1b383b8 to 0d00347 Compare October 12, 2026 02:05
@tianyu-l
tianyu-l merged commit fc6ed2d into pytorch:main Oct 12, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Oct 12, 2026
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 ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants