jax icon indicating copy to clipboard operation
jax copied to clipboard

`vmap` over a `lax.scan` whose carry is a hijax type fails

Open bheijden opened this issue 4 months ago • 1 comments

Description

jax.grad through a scan with a hijax carry works. Wrapping the same function in jax.vmap fails.

from dataclasses import dataclass

import jax
import jax.numpy as jnp
from jax.experimental.hijax import (
    HiType, MappingSpec, ShapedArray, VJPHiPrimitive, register_hitype,
    transpose_jvp, vjp_fwd_from_jvp)


@dataclass(frozen=True)
class BoxSpec(MappingSpec):
    pass


@dataclass(frozen=True)
class Box:
    a: jax.Array


@dataclass(frozen=True)
class BoxTy(HiType):
    shape: tuple

    def lo_ty(self):             return [ShapedArray(self.shape, jnp.dtype('float32'))]
    def lower_val(self, b):      return [b.a]
    def raise_val(self, a):      return Box(a)
    def to_tangent_aval(self):   return ShapedArray(self.shape, jnp.dtype('float32'))
    def leading_axis_spec(self): return BoxSpec()
    def str_short(self, short_dtypes=False, **_): return f"box{list(self.shape)}"

    def dec_rank(self, size, spec): return BoxTy(self.shape[1:])
    def inc_rank(self, size, spec): return BoxTy((size, *self.shape))


register_hitype(Box, lambda b: BoxTy(b.a.shape))


class Wrap(VJPHiPrimitive):
    def __init__(self, aval):
        self.in_avals, self.out_aval, self.params = (aval,), BoxTy(aval.shape), {}
        super().__init__()

    def expand(self, a):              return Box(a)
    def jvp(self, primals, tangents): return self(*primals), tangents[0]
    vjp_fwd, vjp_bwd_retval = vjp_fwd_from_jvp, transpose_jvp

    def batch(self, axis_data, args, dims):
        (a,), (d,) = args, dims
        return (self(a), None) if d is None else (wrap(jnp.moveaxis(a, d, 0)), BoxSpec())


class Unwrap(VJPHiPrimitive):
    def __init__(self, aval):
        self.in_avals = (aval,)
        self.out_aval = ShapedArray(aval.shape, jnp.dtype('float32'))
        self.params = {}
        super().__init__()

    def expand(self, b):              return b.a
    def jvp(self, primals, tangents): return self(*primals), tangents[0]
    vjp_fwd, vjp_bwd_retval = vjp_fwd_from_jvp, transpose_jvp

    def batch(self, axis_data, args, dims):
        (b,), (d,) = args, dims
        return (unwrap(b), None) if d is None else (unwrap(b), 0)


wrap   = lambda a: Wrap(jax.typeof(a))(a)
unwrap = lambda b: Unwrap(jax.typeof(b))(b)


def f(k):
    """A scan whose CARRY is a hijax value. `k` is an ordinary scalar."""
    box = wrap(jnp.arange(3, dtype='float32') * k)
    out = jax.lax.scan(lambda c, _: (wrap(unwrap(c) * 2.0), None), box, None, length=2)[0]
    return jnp.sum(unwrap(out) ** 2)


ks = jnp.linspace(1., 2., 4, dtype='float32')

print(jax.grad(f)(jnp.float32(1.5)))   # 240.0 -- one gradient, no vmap: fine
print(jax.vmap(f)(ks))                 # TracerArrayConversionError

(On a jax without #39702, add mat = property(lambda self: ShapedArray((1,), jnp.dtype('float32')).mat) to BoxTy first, to get past #39700.)

Expected: jax.vmap(f)(ks) returns the same as the serial jnp.stack([f(k) for k in ks]), which is

[ 80.      142.2222  222.22226 320.     ]

Actual:

TracerArrayConversionError: The numpy.ndarray conversion method __array__() was called on
traced array with shape box[4, 3]
The error occurred while tracing the function <lambda> ... for scan.

Note the mapped argument is an ordinary array — the hijax value is internal to f — so no spec-valued in_axes is involved.

The same root, reached without ever writing a hijax carry

grad can create the condition. Below the scan carry is a plain array and the hijax value is only an intermediate, so the forward path is fine — but reverse mode keeps that intermediate as a residual of the linearized scan, so the transposed scan's carry contains a hijax value. Replacing f in the snippet above with:

def g(k):
    """The carry is an ORDINARY array; the hijax value is only an intermediate."""
    box = wrap(jnp.arange(3, dtype='float32'))

    def step(u, _):
        inner = wrap(unwrap(box) + u)          # hijax value created INSIDE the body
        return u + 0.1 * k * unwrap(inner), None

    u, _ = jax.lax.scan(step, jnp.zeros(3, dtype='float32'), None, length=3)
    return jnp.sum(u ** 2)


print(jax.vmap(g)(ks))                 # [0.5478051 1.0383292 1.7285024 2.6499202]  fine
print(jax.grad(g)(jnp.float32(1.5)))   # 2.0665715                                  fine
print(jax.vmap(jax.grad(g))(ks))       # StoreException: Store empty

Expected [1.2015301 1.7559783 2.4008489 3.1449602] (the serial jnp.stack([jax.grad(g)(k) for k in ks])); actual jax._src.linear_util.StoreException: Store empty — a different symptom from the first case, same cause.

This is the shape most code hits in practice: a solver whose scan carries a plain state vector and rebuilds typed values inside the body works forwards and per-instance, and only breaks when the gradient is batched.

_scan_batching_rule assigns the carry batch dims as integers regardless of aval type (loops.py:1214 in 0.11.0):

carry_bdims = [0 if b else None for b in carry_batched]
ys_bdims    = [1 if b else None for b in ys_batched]

Workaround: override the scan batcher and batching.matchaxis so both consult aval.leading_axis_spec() for hijax avals. Overriding only one of the two is not enough. With both, the snippet prints 240.0 and [80. 142.2222 222.22226 320.].

This is in the same file as #39700 / #39702, one function down — that fix guarded .mat in _scan_abstract_eval for non-ShapedArray avals; this is the same assumption in the batching rule. Checked: applying #39702 locally does not fix this — with that patch applied and the mat workaround removed, the snippet above still raises.

System info (python version, jaxlib version, accelerator, etc.)

jax:    0.11.0
jaxlib: 0.11.0
numpy:  2.4.6
python: 3.12.11 (main, Sep 18 2025, 19:47:19) [Clang 20.1.4 ]
device info: NVIDIA GeForce RTX 4090 Laptop GPU-1, 1 local devices"
process_count: 1
platform: uname_result(system='Linux', node='bas-ThinkPad-P1-Gen-6', release='6.17.0-35-generic', version='#35~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue May 26 19:30:42 UTC 2', machine='x86_64')

$ nvidia-smi
NVIDIA-SMI 580.159.03   Driver Version: 580.159.03   CUDA Version: 13.0
NVIDIA GeForce RTX 4090 Laptop GPU

bheijden avatar Aug 04 '26 17:08 bheijden

Hi @dougalm I took a look at this and now have a fix that passes both the direct vmap(scan(...)) case and the vmap(grad(...)) residual case, also added with additional regression tests for this.

I’m planning to open a PR once the broader tests finish. Since the issue is assigned to you, if you’ve already been working on a fix, I’m also happy to defer to yours :)

edluyuan avatar Aug 28 '26 16:08 edluyuan