mlx icon indicating copy to clipboard operation
mlx copied to clipboard

Add VJP for cumulative max and min scans

Open devin-lai opened this issue 6 months ago • 1 comments

Summary

  • Implement reverse-mode VJP for cummax and cummin instead of raising at gradient time.
  • Route cotangents to the latest running-extreme owner in scan order, including reverse and exclusive scans.
  • Add Python and C++ autograd tests covering max/min, forward/reverse scans, inclusive/exclusive modes, ties, and non-uniform cotangents.

Details

cummax and cummin are public forward ops, but mx.grad through them previously raised because cumulative min/max VJP was not implemented. This follows the existing Scan::vjp TODO: mark entries equal to the inclusive running extreme, scan over those indices to recover the owning input position, then accumulate cotangents with scatter_add_axis.

For ties, the VJP uses the latest occurrence in scan order. That convention matches the owner selected by PyTorch cummax/cummin backward in the cases cross-checked locally. Exclusive scans first shift cotangents by one step in the scan direction because the current element is excluded from its own output.

The implementation adds a small number of scan ops plus one scatter_add_axis only on the VJP path, which previously threw, so it does not regress existing differentiable workloads.

Tests

  • /Users/ldy/Library/Python/3.11/bin/pre-commit run --files mlx/primitives.cpp python/tests/test_autograd.py tests/autograd_tests.cpp
  • PYTHONPATH=python:python/tests python3.11 -m unittest python.tests.test_autograd
  • build_tests/tests/tests --test-case="test scan grads"
  • Local PyTorch cross-check: 24 VJP comparisons across cummax/cummin, axes, reverse, inclusive/exclusive, ties, and weighted cotangents.

devin-lai avatar May 28 '26 10:05 devin-lai

  • Local PyTorch cross-check: 24 VJP comparisons across cummax/cummin, axes, reverse, inclusive/exclusive, ties, and weighted cotangents.

If cross-check had been done locally I think it would be very useful to run them in the python tests.

Thanks!!! I moved the local cross-check into the python autograd tests. It now covers cummax/cummin over both axes, reverse/inclusive/exclusive combinations, tie cases, and weighted cotangents, the test skips if PyTorch is not available, consistent with the other PyTorch reference tests in the suite.

devin-lai avatar May 29 '26 02:05 devin-lai