[BUG] custom_function.jvp and .vmap are ignored when the body contains a Metal kernel
☑️ I understand it is strictly prohibited to use AI to write issues.
Describe the bug If the body of mx.custom_function calls mx.fast.metal_kernel, MLX applies the registered .vjp rule but ignores .jvp and .vmap. These two transforms extend into the body, reach the CustomKernel primitive, and fail without calling the custom rule.
To Reproduce
import mlx.core as mx
double = mx.fast.metal_kernel(
name="double_it",
input_names=["inp"],
output_names=["out"],
source="out[thread_position_in_grid.x] = inp[thread_position_in_grid.x] * 2.0f;",
)
def body(a):
(o,) = double(inputs=[a], grid=(a.size, 1, 1), threadgroup=(a.size, 1, 1),
output_shapes=[a.shape], output_dtypes=[a.dtype])
return o
@mx.custom_function
def f(a):
return body(a)
@f.vjp
def f_vjp(primals, cotangent, output):
return body(cotangent)
@f.jvp
def f_jvp(primals, tangents):
return body(tangents)
@f.vmap
def f_vmap(inputs, axes):
return body(inputs), axes
x = mx.ones((8,))
print("grad:", mx.grad(lambda a: mx.sum(f(a)))(x)) # works, uses f_vjp
print("vmap:", mx.vmap(f)(mx.ones((4, 8))).shape) # raises, f_vmap never called
print("jvp: ", mx.jvp(f, [x], [x])[1]) # raises, f_jvp never calledTraceback:
grad: array([2, 2, 2, ..., 2, 2, 2], dtype=float32)
Traceback (most recent call last):
File "/private/tmp/mlx-repros/b_issue.py", line 36, in <module>
print("vmap:", mx.vmap(f)(mx.ones((4, 8))).shape) # raises, f_vmap never called
^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: [Primitive::vmap] Not implemented for CustomKernel.If the line with vmap is removed, jvp fails similarly: [Primitive::jvp] Not implemented for CustomKernel.
Expected behavior The custom_function docstring states that the custom vjp, jvp, and vmap rules are used instead of the standard transformation. Accordingly, the following is expected:
mx.jvp returns the tangent of twos, via the registered .jvp rule; mx.vmap(f)(mx.ones((4, 8))) returns an array of shape (4, 8) via the registered .vmap rule.
In neither case should the transformation occur within the function body.
Desktop:
- OS Version: macOS 26.3 (build 25D125)
- Version 0.32.2
- Apple M4 (applegpu_g16g), arm64, Python 3.12.13.
Additional context The error only occurs when the body contains a primitive without its own jvp or vmap implementation.
Reproducer is written by Claude Opus and verified by me.
The cause is likely in mlx/transforms.cpp.
Source: ml-explore/mlx