Skip to content

Fix DSA indexer LoRA-training crash: stop gradients through sparse-attention top-k indices - #1452

Merged
michalk8 merged 4 commits into
ml-explore:mainfrom
trevorgordon981:fix/dsa-indexer-stopgrad-vjp
Sep 9, 2026
Merged

michalk8 merged 4 commits into
ml-explore:mainfrom
trevorgordon981:fix/dsa-indexer-stopgrad-vjp

Conversation

@trevorgordon981

Copy link
Copy Markdown
Contributor

What

LoRA fine-tuning of DSA sparse-attention models (deepseek_v32, and glm_moe_dsa which subclasses it) crashes deterministically in the backward pass:

ValueError: [scatter_axis] Cannot calculate VJP with respect to indices.

Fixes #1449. Companion core issue: ml-explore/mlx#3787.

Root cause

The DSA Indexer only activates when the key length exceeds index_topk (2048); below that it returns None and training works fine. Once a batch crosses that width, the indexer computes topk_indices via mx.argpartition over scores that derive from trainable projections (wq_b, wk, weights_proj, and the shared q_a_proj — all typical LoRA targets). Those integer indices then feed mx.put_along_axis (training/prefill path) and mx.take_along_axis (decode path) in the attention. Because the indices lie on the autodiff path, autograd requests a VJP with respect to the scatter's index argument, and ScatterAxis::vjp throws instead of returning a zero cotangent (ml-explore/mlx#3787).

This explains the reproduction in #1449 exactly: the crash lands on the first batch whose sequence width crosses 2048 — the same step every run under a fixed seed — and is unaffected by which LoRA keys are trained, the learning rate, or excluding switch_mlp. (My original report blamed the MoE routing scatter; that was wrong — the MoE gate's scatter is already protected by mx.stop_gradient on group_idx. The unprotected site is the indexer.)

Fix

mx.stop_gradient on the top-k indices at two sites:

  1. Producer — wrap the Indexer.__call__ return. Integer top-k indices are a non-differentiable selection, so this is semantically exact: the forward pass is bit-identical, and inference never differentiates so serving is unaffected.
  2. Consumer — re-assert the barrier where topk_indices is consumed in DeepseekV32Attention.__call__. This is defensive: if the indices ever reach the attention through a traced boundary (e.g. as a checkpointed function input under grad_checkpoint in a variant that passes indices between layers), a producer-side barrier is not visible to the re-traced graph and the crash returns. It is a no-op when the indices come straight from the producer, as here.

A zero-cotangent fix in core MLX (ml-explore/mlx#3787) would also resolve the throw, but the model-side barrier is exact regardless, avoids computing gradients that are discarded, and unblocks training today.

Validation

  • Applied the same two barriers to an mlx-lm 0.31.3 install and ran mlx_lm.lora on GLM-5.2 (4-bit, glm_moe_dsa) with grad_checkpoint: true, max_seq_length: 4096 on real data: previously crashed at the first >2048-token batch, now trains cleanly (30-iteration smoke run, healthy loss descent).
  • python -m py_compile and black --check pass on the changed file.

… crash

Training a LoRA on deepseek_v32 / glm_moe_dsa crashes in the backward pass
with 'ValueError: [scatter_axis] Cannot calculate VJP with respect to
indices' whenever a batch is longer than index_topk (2048). The indexer's
argpartition output derives from trainable projections, so autograd asks
the consuming put_along_axis/take_along_axis for an indices VJP, which MLX
does not define. Integer top-k indices carry no gradient, so stopping
gradients on them is exact: forward is unchanged and inference is
unaffected.
@michalk8
michalk8 self-requested a review September 9, 2026 15:07

@michalk8 michalk8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@michalk8
michalk8 merged commit 889da35 into ml-explore:main Sep 9, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] LoRA fine-tuning of quantized GLM-5.2 (glm_moe_dsa) MoE crashes in backward: [scatter_axis] Cannot calculate VJP with respect to indices

3 participants