Support Ring Attention with DeepSeek DSA Sparse Indexer - #4767
Conversation
There was a problem hiding this comment.
Code Review
This pull request enables support for sparse indexer masks within the TPU Tokamax ring attention kernel, integrating indexer loss logging and auxiliary loss calculations into the training loop. The review feedback highlights a few critical runtime issues: a mismatch in the evaluation metric dictionary key for logging indexer loss, an incorrect keyword argument (_shape instead of shape) when instantiating FullMask, and a potential ValueError when concatenating zero-dimensional arrays in the loss calculation when scan_layers=False.
b4b7cde to
5624dfa
Compare
5624dfa to
d7881bd
Compare
d7881bd to
e6d4985
Compare
e6d4985 to
cb52048
Compare
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
🤖 Hi @zcjhao, I've received your request, and I'm working on it now! You can track my progress in the logs for more details. |
There was a problem hiding this comment.
This Pull Request introduces end-to-end integration for the DeepSeek Sparse Attention (DSA) Indexer under Tokamax Ring Context Parallelism during training and evaluation. The design correctly implements dynamic per-ring-step slicing and rotation of indexer masks in both forward and backward passes, and addresses Flax NNX auxiliary loss harvesting by defining a dedicated indexer_losses variable.
🔍 General Feedback
- Excellent Architectural Alignment: Defining
class indexer_losses(nnx.Variable)to bypass scanned layer intermediate filters is a brilliant and clean solution that integrates perfectly with upstream patterns like MTP losses. - Robust Integration Testing: The additions of parameterized equivalence tests comparing distributed Ring Context Parallel MLA+Indexer outputs/gradients against single-device dot-product baselines are outstanding and provide high assurance of numerical correctness.
- Clear Documentation: The inclusion of ASCII forward and backward data flow diagrams in the PR description is extremely helpful for understanding the complex grid scheduling and transposition logic.
9bcec0e to
6d6e862
Compare
|
🤖 Hi @zcjhao, I've received your request, and I'm working on it now! You can track my progress in the logs for more details. |
There was a problem hiding this comment.
📋 Review Summary
This pull request introduces end-to-end support for DeepSeek Sparse Attention (DSA) Indexer with Tokamax Ring Context Parallelism during training. The implementation includes crucial enhancements such as dynamic per-ring-step mask extraction, transposition for backward pass schedule alignment, and utilizing a custom Flax NNX Variable class to prevent auxiliary loss pruning in scanned JAX loops.
🔍 General Feedback
-
High Quality Architecture: The design choices are exceptional, particularly the transposition of blocks for
$dK/dV$ backward-pass alignment and utilizing a customnnx.Variableclass to elegant bypass scan filters. - Robust and Comprehensive Testing: The PR is extremely well-tested with parameterized forward/backward gradient equivalence tests and unit tests covering dynamic mask batch-vectorization.
- Backwards Compatibility: Modifications are backwards-compatible and preserve original behavior when the sparse indexer or Tokamax ring context parallelism is not enabled.
| max_logging.debug("\nNo Indexer loss found. Defaulting to 0.0.") | ||
|
|
||
| # get MoE load balance loss | ||
| moe_lb_loss = 0.0 |
There was a problem hiding this comment.
| moe_lb_loss = 0.0 | |
| max_logging.debug("No Indexer loss found. Defaulting to 0.0.") |
RissyRan
left a comment
There was a problem hiding this comment.
LGTM at high level! One question about indexer loss. When onboarded, we were testing Linen instead of NNX. Could you have a run with old version to see if your new changes align with previous runs? Thanks!
enable_nnx: false
pure_nnx_decoder: false
pure_nnx: false
|
cc @huytransformer helps take a review on kernel part |
6d6e862 to
b2b601d
Compare
- Add dynamic per-ring-step indexer mask slicing and injection to Tokamax Splash Attention forward and backward loops. - Fix backward dK/dV transposition (is_dkv=True) with .swapaxes(0, 1) to match hardware KV-major grid scheduling, resolving TPU network collective deadlocks. - Implement indexer_losses(nnx.Variable) subclass to cleanly bypass Flax NNX layer scan Intermediate filtering with zero blast radius. - Update train.py loss_fn to pop indexer_losses, harvest per-layer auxiliary KL losses, and inject them into the scalar optimization objective for backward gradient flow.
b2b601d to
df06e14
Compare
Description
This PR adds end-to-end support for DeepSeek Sparse Attention (DSA) Indexer with Tokamax Ring Context Parallelism during training. Previously,
use_indexer=Truewas prohibited with Ring Attention due to a lack of dynamic per-ring-step mask extraction.Problems Solved & Key Design Choices:
indexer_maskinto per-step KV-shard blocks(ring_axis_idx - step) % ring_axis_sizeand tiles them into hardware blocks(block_q, block_kv).(q_blocks, kv_blocks), whereas the backward(kv_blocks, q_blocks). We apply.swapaxes(0, 1)and. swapaxes(-1, -2)whenis_dkv=True, aligning the mask blocks with the hardware execution schedule.Forward Flow: From Global Mask to TPU Register Tile
Backward Flow: From Saved Mask to Transposed Gradient Tiles
Isolated Flax NNX Auxiliary Loss:
_apply_layers_sequentiallyfilters scanned layer states viannx.filter_state(..., nnx.Not((nnx.RngState, nnx.Intermediate))). Subclassingnnx.Intermediatecausedjax.lax.scanto prune the loss variable during execution, resulting inindexer_loss: 0.000and broken backward gradients.class indexer_losses(nnx.Variable):which inherits directly fromnnx.Variablerather thannnx Intermediate. This allows the variable to pass throughjax.lax.scanunharmed without modifying core decoder scanning logic.Loss Harvesting & Objective Injection:
train.py'sloss_fn,indexer_lossesis popped before generic intermediates (mirroring the upstream MTP loss pattern).loss += indexer_loss), restoring full automatic differentiation VJP gradient flow to indexer Query/Key projection weights (wq_b,wkv_b).Tests
Image
HLO
configs_value_test.py:test_tpu_tokamax_ring_config_validation_accepts_indexerto verify that pyconfig.initialize accepts the combination of MLA, Sparse Indexer, and Tokamax Ring Attention.test_tpu_tokamax_ring_config_validation_rejects_unsupported_configs.tokamax_ring_attention_test.pytest_call_ring_attention_threads_indexer_mask_without_segment_ids: Tests batch vectorization and threading of dynamic indexer_mask without segmentation IDs.test_call_ring_attention_threads_indexer_mask_with_segment_ids: Tests batch vectorization and threading of dynamic indexer_mask with segmentation IDs.attention_test.py:test_tpu_flash_attention_ring_context_parallel_with_indexer: Parameterized forward equivalence test (load_balance=True/False) verifying that MLA + Indexer under Tokamax Ring Attention matches single-device generic dot-product MLA + Indexer.test_tpu_flash_attention_ring_context_parallel_grad_with_indexer: Parameterized backward gradient equivalence test (load_balance=True/False) verifying that backward input gradients and auxiliary indexer_losses match bit-for-bit with is_dkv=True transposition.test_indexer_losses_harvested_and_injected_into_losstotrain_nnx_test.py: simulates multi-layer transformer intermediate loss and calculates expected_indexer_loss.deepseek32_vs_reference_test.py(we werify MaxText Dot Product Baseline matches Official PyTorch version, and our previous tests show that Ring Attention version matches Dot product baseline. Because Ring Attention = Dot Product Baseline and Dot Product Baseline = PyTorch Reference, this shows that distributed Ring Attention with Indexer matches the reference implementation):Checklist
Before submitting this PR, please make sure (put X in square brackets):
gemini-reviewlabel.