Skip to content

Fix grads through gather, scatter and strided slice ops - #85

Merged
MarcosAsh merged 2 commits into
mainfrom
op-index-grads
Oct 8, 2026
Merged

MarcosAsh merged 2 commits into
mainfrom
op-index-grads

Conversation

@MarcosAsh

Copy link
Copy Markdown
Collaborator

Grads through sort, top_k, quantile, sparsemax and take_along_axis with argsort indices raised "Cannot calculate VJP with respect to indices". mlx raises whenever a gather's indices are in the grad graph, so argmax, argmin, argsort, argpartition and top_k now return their indices through mx.stop_gradient, same as mlx does inside its own sort vjp. take, take_along_axis, scatter and scatter_update do it too, for indices computed from x by comparisons like the sparsemax k, which jax doesn't differentiate either. This also drops the argsort plus gather workaround in sort, quantile and sparsemax from #20. On 0.32 that path is exactly what raises, and mx.sort's own vjp has been right since 0.32.0.

associative_scan grads were wrong too. mlx's strided slice vjp spreads the grad when the slice only has one element, so those slices are now plain ones. That one is an mlx bug I'll send upstream. Checked against jax with compile on and off on linux and Metal, all the sort, top_k, quantile, sparsemax, take and scan cases match now. The keras ops suites pass.

@hertschuh hertschuh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks!

@MarcosAsh
MarcosAsh merged commit 6b9e6e4 into main Oct 8, 2026
10 checks passed
@hertschuh
hertschuh deleted the op-index-grads branch October 8, 2026 18:50
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.

2 participants