Repository navigation
[Deepseek V4] Dsv4 sparse indexer loss - #4835
Conversation
|
|
|
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 I checked the 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
|
|
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? |
|
@Matrix-Z97 could you update this PR? I believe driss change is merged |
f53d760 to
b5b60d1
Compare
|
@claude review the latest change |
|
Claude finished @tianyu-l's task in 3m 12s —— View job Review of the latest change (rebased onto the attn-gym
|
| 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).
🔴 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 exactlyWentries. - 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-codescompressed_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 inIndexer.select, sosearchsortedruns three times per layer (select, global indices, window). Consider returning global gather indices fromselect, or sharing one helper that takesratio.Indexer.select: always builds the differentiabletopk_scores(gather + einsum with grad), even in eval and whenaux_loss is None. Gate it, or move scoring into a separate method that only the loss path calls. That keepsselectindex-only for fused-kernel backends.SparseIndexerLoss.forward:logits_TK.masked_fill(~row_valid_T…, 0.0)is redundant._logged_klimmediately appliesmasked_fill(~slot_valid_TK, -inf)and then fills fully invalid rows with 0.attention.py:136:RuntimeErrorwhen the denominator is missing matchesmoe.py:301, so that's fine. But thetopk_scores_TK is not Noneguard is always true on the CSA path, so that check can go.flavors.py:240:coeff=0.01is still hard-coded, with no flavor or config knob to tune it or turn the loss off.- AC: under
FullACthe metric over-counts 2x (a documentedAuxLosslimitation). 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, butreduce_mesh="loss"then sums per-shard approximate losses. - Validation: please add a
--debug.deterministicloss comparison showing that the main loss is unchanged byselect's newno_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.
7eeb43b to
f017fc9
Compare
|
@claude please review again |
|
Claude finished @tianyu-l's task in 3m 43s —— View job Re-review: DeepSeek V4 sparse indexer loss
Overall: Most of the earlier review is addressed. The two remaining problems are both cheap to fix:
I would merge once those two are handled and a loss comparison is attached.
🔴 1. The TP-equivalence GPU test is skipped in CI
So the one test that checks the TP fix never runs. Add There is also a smaller gap. The test runs the inner module without its 🟡 2. The default objective differs from the paper and has no evidence
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:
The PR description also still has no 🟡 3. The student rescoring keeps about 2 GiB per CSA layer alive for backward
The teacher is now chunked, but the student is not:
This is much better than the original O(T·H·N), and AC hides most of it. Still, a small custom 🟢 Smaller items
I didn't run any tests in this job, because |
|
@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. |
|
@claude are we good to go? |
|
Claude finished @tianyu-l's task in 44s —— View job Yes, good to go once CI is green
Both items left open in the last review are now handled.
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 Optional, not blocking
I didn't run the tests myself in this job. The verdict comes from reading the diff and from the CI status. |
|
@Matrix-Z97 please fix test failures (could wait until current round finishes before next push so all errors are exposed) |
|
@Matrix-Z97 sorry need another rebase |
1b383b8 to
0d00347
Compare
Summary
Add DeepSeek V4 sparse indexer auxiliary loss for CSA layers.
This change wires the community
AuxLossframework into DeepSeek V4 compressed sparse attention so the sparse indexer can be trained from the main attention distribution. The loss is implemented asSparseIndexerLossunderdeepseek_v4/compressor.pyand is configured only forcompress_ratio == 4CSA layers.Changes
SparseIndexerLoss(AuxLoss)for indexer distillation.Indexer.select(...)to return both:topk_indicestopk_scoresout_transform, using attention LSE as teacher normalization.register_aux_loss_zero_hookin the DeepSeek V4 optimizer post-build hook.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.pytp=2ep=2spmd_typespathIndexer.select(...)returnedtopk_scoreswithrequires_grad=TrueSparseIndexerLoss.forward(...)received differentiable scoresCompared the DSV4 debug model using 4 GPUs with EP2+TP2 and 2 GPUs with EP2+TP1, both using:
c4_test, context length 2048Initial parameters and all 20 steps of inputs were verified identical by hashes.
Whole-Model BF16 Comparison
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.