Add Indexer Loss [Deepseek v4] - #5033
Open
octatrifan wants to merge 16 commits into
Open
Conversation
- Implement DeepSeek-V4 CSA Indexer KL divergence loss distillation against dense attention representations - Support memory-efficient head-chunking scan via mla_qk_head_chunk_size - Add NaN shielding (valid_tokens_mask) for pre-block queries prior to block 0 completion - Initialize dedicated DeepSeekV4RotaryEmbedding in DeepseekV4Indexer for index_head_dim - Update MaxTextConfig validators to allow use_indexer with AttentionType.COMPRESSED - Add comprehensive unit tests for CSA indexer loss computation, KL boundary condition, gradient isolation, head-chunking parity, and sparse mode
…double scaling, enforce causal block masking on teacher, revert RoPE rewrite, and isolate loss gating
…ent packing for CSA indexer - Ensure attention forward pass is dense over all blocks during dense warm-up stage (indexer_sparse_training=False) - Incorporate segment/packing mask with causal block mask in teacher_mask and valid_tokens_mask - Prevent redundant duplicate causal mask application on student indexer_score - Enforce strict teacher causality ensuring 0.0 probability mass on all future blocks when position_ids is set - Add unit tests for teacher causality/packing and dense warm-up forward pass
…gorous 2-segment packed test cases - Replace all-zero forward mask with dense causal block mask during dense warm-up stage in CompressedAttention - Verify that for query token t=4, block 0 is unmasked (0.0) and block 1 is masked (-1e9) - Add test_teacher_causality_and_packing_on_loss_function calling calculate_csa_indexer_loss on a 2-segment packed document sequence - Verify loss is 0.0 on matching ground truth and penalizes future/cross-document score leakage (> 0.1)
…inst top-k=1 sparse mode
…mpile smoke test - Update types.py: derive CSA rate from compress_ratios, clarify block bounds validation - Set use_indexer: true on deepseek4-tiny.yml and deepseek4-284b.yml - Refactor calculate_csa_indexer_loss: rename causal_mask to segment_mask, replace literal -1e9/-100.0 with DEFAULT_MASK_VALUE, line-for-line structure alignment with MLA - Add test_csa_indexer_loss_jit_compile smoke test and verify 8/8 unit tests pass on TPU VM
There was a problem hiding this comment.
Code Review
This pull request implements the indexer KL divergence loss for Compressed Sparse Attention (CSA) in DeepSeek-V4. It updates model configurations and validation logic to support the indexer with compressed attention, modifies the indexer and compressor layers to return scores, and introduces the calculate_csa_indexer_loss method to compute the KL divergence loss. Additionally, it adds a comprehensive suite of unit tests to verify the loss computation, gradient flow, and mask behavior. There are no review comments to address, so I have no feedback to provide.
octatrifan
force-pushed
the
octatrifan-dsv4-indexer-loss
branch
from
August 27, 2026 21:00
ef954b3 to
4123d22
Compare
…tests - Decouple mask selection from indexer loss calculation in CompressedAttention; scale=0 and sparse=False stays dense causal without indexer loss - Add get_compressed_mask helper to CompressedAttention and assert mask tensor values across block boundaries in unit tests - Extend gradient detachment test to assert input grads are 0.0 under both sparse and dense modes - Update types.py docstrings to reference MLA or Compressed Attention for use_indexer
octatrifan
force-pushed
the
octatrifan-dsv4-indexer-loss
branch
from
August 27, 2026 23:04
741f351 to
8209361
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
octatrifan
marked this pull request as ready for review
August 28, 2026 21:44
octatrifan
requested review from
NuojCheng,
RissyRan,
aireenmei,
bvandermoon,
gagika,
gobbleturk,
huytransformer,
igorts-git,
jiangjy1982,
parambole,
richjames0,
shralex,
shuningjin and
xibinliu
as code owners
August 28, 2026 21:44
octatrifan
requested review from
A9isha,
SurbhiJainUSC,
abhinavclemson,
darisoy,
dipannita08,
hengtaoguo,
khatwanimohit and
vipannalla
as code owners
August 28, 2026 21:44
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Adds Indexer KL divergence distillation loss for DeepSeek-V4 Compressed Sparse Attention (CSA), enabling two-stage training (Dense Warm-up and Sparse Pre-training) on TPUs.
Reference PRs (for DSV3.2):
In DeepSeek-V3.2 (MLA),$m=4$ tokens share a single key vector. This change implements
calculate_indexer_lossdistills dense per-token attention into token-level indexer scores. DeepSeek-V4 uses block-compressed key-values wherecalculate_csa_indexer_lossto compute KL divergence between the student's block-level predictions and the teacher's compressed attention distribution.Key Changes
attention_compressed.py:calculate_csa_indexer_losswith block causal masking and document boundary support.jax.lax.stop_gradientto teacher projections and indexer inputs to isolate indexer gradients.mla_qk_head_chunk_size) to prevent HBM OOM during teacher attention.indexer_loss_scaling_factor > 0.0 and not indexer_sparse_training; defaults to sparse CSA otherwise.train.py:indexer_loss_scaling_factor > 0.0 and not indexer_sparse_training, aligning with existingdecoders.pylogic across both 3.2 and 4.types.py:indexer_topk <= max_target_length // 4.deepseek4-tiny.yml,deepseek4-284b.yml):use_indexer: true.tests/unit/deepseek_v4_indexer_loss_test.py):BUGS: b/548036332
Tests
1. Unit Tests
Ran on TPU VM (v5p8):
10/10 passed in 39.89s.
2. Dense Indexer Warm-up Mode (100 steps,
HuggingFaceFW/fineweb-edu)Repro command:
Verified
lm_loss = 0.000across all 100 steps; non-indexer weights frozen viatrainable_parameters_mask=['.*indexer.*'](matching DeepSeek-V3.2); indexer KL loss stable at ~0.00295. Step time: 2.08s (~11,800 tokens/s/device).Full log
Full log for attention=flash
3. Sparse Pre-training Mode (100 steps,
HuggingFaceFW/fineweb-edu)Repro command:
python3 src/maxtext/trainers/pre_train/train.py src/maxtext/configs/base.yml \ model_name=deepseek4-tiny run_name=dsv4_sparse_100step steps=100 \ use_indexer=True indexer_loss_scaling_factor=0.1 indexer_sparse_training=True \ dataset_type=hf hf_path='HuggingFaceFW/fineweb-edu' tokenizer_path=deepseek-ai/DeepSeek-V3.2 \ base_output_directory=/tmp/maxtext_outputVerified monotonic loss descent: Total loss dropped 12.297 -> 11.869 (
lm_loss: 12.279 -> 11.854,indexer_loss: 0.01678 -> 0.01493). Step time: 2.27s (~10,825 tokens/s/device). Checkpoint step 99 serialized and finalized.Full log
Full log for attention=flash
Checklist
Before submitting this PR, please make sure (put X in square brackets):
gemini-reviewlabel.