Skip to content

gpt_oss: stop_gradient on top-k indices so LoRA backward works (fixes #1814) - #1843

Merged
michalk8 merged 2 commits into
ml-explore:mainfrom
dellapolla-lab:fix/gpt-oss-topk-stop-gradient
Sep 4, 2026
Merged

michalk8 merged 2 commits into
ml-explore:mainfrom
dellapolla-lab:fix/gpt-oss-topk-stop-gradient

Conversation

@dellapolla-lab

Copy link
Copy Markdown
Contributor

Fixes #1814.

Problem

LoRA / any backward pass through gpt_oss fails in mlx_topk:

ValueError: [gather_axis] Cannot calculate VJP with respect to indices. Use stop_gradient on indices to stop gradients from being computed.

mlx_topk feeds the indices returned by mx.argpartition straight into mx.take_along_axis; in the backward pass MLX then tries to differentiate with respect to those integer indices.

Fix

Wrap the top-k indices in mx.stop_gradient, exactly as qwen3_moe.py does since #1787 (inds = mx.stop_gradient(inds) after the argpartition), and as the open PR #1238 does for gemma4. Gradient still flows through the router via the softmax over the selected values (expert_weights); the discrete expert selection has no gradient by construction, so this changes no numerics of the forward pass or of the weights that do get gradients.

Verification

Minimal model built from mlx_lm/models/gpt_oss.py (2 layers, 8 local experts, 2 experts per token, hidden 32, vocab 64, no weights downloaded), nn.value_and_grad(model, loss) on a 6-token batch, mlx 0.32.2 / mlx-lm 0.31.3, macOS arm64:

result
main (6651d2e) ValueError: [gather_axis] Cannot calculate VJP with respect to indices…
this branch forward + backward complete, loss 4.2426

Inference path is unchanged (mx.stop_gradient is a no-op in the forward pass).

🤖 Generated with Claude Code

@michalk8
michalk8 self-requested a review September 4, 2026 18:41
@michalk8

michalk8 commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

LGTM, thanks @dellapolla-lab. And for future contributions, please consult the CONTRIBUTING.md.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] LoRA training of gpt-oss crashes in backward: [gather_axis] Cannot calculate VJP with respect to indices (mlx_topk lacks stop_gradient)

3 participants