Skip to content

Use the supplied gradient in custom_gradient and add a test suite - #47

Open
MarcosAsh wants to merge 3 commits into
mainfrom
custom-gradient
Open

Use the supplied gradient in custom_gradient and add a test suite#47
MarcosAsh wants to merge 3 commits into
mainfrom
custom-gradient

Conversation

@MarcosAsh

Copy link
Copy Markdown
Collaborator

Description

custom_gradient threw the supplied gradient away. It called the decorated function, discarded the second return value and only warned, so keras.ops.custom_gradient returned autodiff of the forward pass rather than the gradient the caller wrote. This wires the gradient into mx.custom_function's vjp. One wrinkle worth knowing: mlx hands the vjp a bare array for a single primal and a tuple for several, so the primals need normalising before they go back to the decorated function.

The two in tree users were both getting the wrong answer. fake_quant_with_min_max_vars now gets its straight through estimator, gradient 1 inside the range and 0 outside, where before it differentiated the rounding. einsum_dense's int8 path is the other one.

Nothing upstream covers this. keras/src/ops/core_test.py::test_custom_gradient is gated on the backend being tensorflow, jax or torch, and the two other tests that reach custom_gradient are gated the same way, so this adds the first tests in this repo along with a CI step to run them. keras/src/ops/core_test.py, keras/src/quantizers/ and keras/src/layers/core/einsum_dense_test.py give 430 passed and 0 failed.

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.

1 participant