XLA - CPU thunk runtime: `jax.grad` through `lax.scan` is 60x slower when the carry holds many scalar leaves
I have been hitting this problem in pyhgf with all versions of JAX above
0.4.31, where sampling gets impossible because of the gradient slowdown. This is specific to cases where carry is a dictionary with many scalar leaves. The obvious workaround is to vectorise states, but this design is not always desirable. I would argue that identical HLO running 60× slower is a runtime regression on its own terms, and the removal of the opt-out is what turns it into something users cannot route around.
Summary
A lax.scan whose carry is many scalar pytree leaves compiles to a loop body of ~12k small instructions under reverse mode. Since jaxlib 0.4.32, where the thunk-based XLA:CPU runtime became the default, that program executes 60x slower than it did on 0.4.31.
The optimised HLO is identical with and without --xla_cpu_use_thunk_runtime=false on 0.4.32 (same sha256), and only the choice of runtime changes the time: 28.567 ms against 0.469 ms. The cost is therefore in execution, not in compilation.
The workaround is no longer available: the flag is honoured up to jax 0.6.2, raises XlaRuntimeError on 0.7.0 and 0.7.1, and is silently ignored from 0.7.2 onwards. On 0.11.1 the gradient is still ~35x slower than on 0.4.31.
Environment
| platform | macOS 26.5.2, arm64 (Apple Silicon) |
| python | 3.12.13 |
| backend | CPU (jax.default_backend() == "cpu") |
| versions tested | jax/jaxlib 0.4.31 through 0.11.1, installed in matching pairs |
Reproduction
Depends on jax only. Run it once plainly and once with XLA_FLAGS=--xla_cpu_use_thunk_runtime=false.
"""XLA:CPU: jax.grad through lax.scan with a many-scalar-leaf carry."""
import hashlib
import os
import time
import jax
import jax.numpy as jnp
N_LEAVES = int(os.environ.get("N_LEAVES", 60)) # scalar leaves in the scan carry
LENGTH = int(os.environ.get("LENGTH", 614)) # scan trip count
XS = jnp.sin(jnp.arange(LENGTH, dtype=jnp.float32) * 0.01)
def model(p):
"""A scan whose carry is N_LEAVES separate scalars."""
carry = {i: jnp.float32(0.1) for i in range(N_LEAVES)}
def step(carry, x):
new = {}
for i in range(N_LEAVES):
j = (i + 1) % N_LEAVES
a = carry[i] * 0.5 + carry[j] * 0.1 + p[i % 3] * 0.01 + x
b = jnp.exp(-jnp.abs(a) * 0.1)
new[i] = jnp.tanh(a * b)
return new, sum(new.values())
_, ys = jax.lax.scan(step, carry, XS)
return ys.sum()
def bench(fn, p, reps=20):
jax.block_until_ready(fn(p))
t0 = time.perf_counter()
for _ in range(reps):
out = fn(p)
jax.block_until_ready(out)
return (time.perf_counter() - t0) / reps * 1e3
p = jnp.array([0.3, -0.2, 0.1], dtype=jnp.float32)
f = jax.jit(model)
g = jax.jit(jax.grad(model))
fwd_text = f.lower(p).compile().as_text()
grad_text = g.lower(p).compile().as_text()
fwd_instr = sum(1 for line in fwd_text.splitlines() if " = " in line)
grad_instr = sum(1 for line in grad_text.splitlines() if " = " in line)
grad_hash = hashlib.sha256(grad_text.encode()).hexdigest()[:16]
print(f"jax {jax.__version__} leaves={N_LEAVES} length={LENGTH} "
f"XLA_FLAGS={os.environ.get('XLA_FLAGS', '(none)')}")
print(f" forward : {bench(f, p):8.3f} ms ({fwd_instr} instructions)")
print(f" gradient: {bench(g, p):8.3f} ms ({grad_instr} instructions)")
print(f" optimised-HLO sha256[:16] of the gradient: {grad_hash}")
Results
The regression at runtime
| jax/jaxlib | XLA_FLAGS |
forward | gradient | gradient HLO sha256[:16] |
|---|---|---|---|---|
| 0.4.31 | none | 0.299 ms | 0.478 ms | 194dc8b3a6051af9 |
| 0.4.32 | none | 2.182 ms | 28.567 ms | cbf951321b6b8b80 |
| 0.4.32 | --xla_cpu_use_thunk_runtime=false |
0.310 ms | 0.469 ms | cbf951321b6b8b80 |
| 0.11.1 | none | 4.263 ms | 16.744 ms | 75d7e0269edafa18 |
The two 0.4.32 rows carry the same optimised-HLO hash and differ 61x in runtime. Reverting to the pre-thunk runtime restores 0.4.31 performance exactly.
The workaround has been withdrawn
Same script, gradient time with and without the flag:
| jax/jaxlib | default | --xla_cpu_use_thunk_runtime=false |
flag status |
|---|---|---|---|
| 0.4.32 | 28.567 ms | 0.469 ms | honoured |
| 0.4.38 | 19.928 ms | 0.481 ms | honoured |
| 0.5.3 | 11.687 ms | 0.396 ms | honoured |
| 0.6.2 | 12.851 ms | 0.390 ms | honoured |
| 0.7.0 | 12.488 ms | XlaRuntimeError |
fatal |
| 0.7.1 | 54.551 ms | XlaRuntimeError |
fatal |
| 0.7.2 | 17.188 ms | 17.109 ms | ignored |
| 0.8.3 | 17.070 ms | 17.635 ms | ignored |
| 0.9.2 | 18.217 ms | 17.479 ms | ignored |
| 0.10.2 | 17.328 ms | 17.510 ms | ignored |
| 0.11.0 | 18.460 ms | 17.266 ms | ignored |
On 0.7.0 and 0.7.1 the flag is still parsed but the legacy path is gone, so passing it aborts execution:
jaxlib._jax.XlaRuntimeError: INTERNAL: CpuExecutable has no thunks.
From 0.7.2 the flag is accepted but does nothing, with no warning.
Request
Make the thunk runtime's per-operation overhead competitive with the legacy emitter for loop bodies containing many small operations, or expose a supported way to opt out. Since 0.7.2 there is no user-side workaround other than pinning jaxlib to 0.6.2 or older, and the affected programs are the natural output of reverse-mode differentiation through a scan over a structured state.
Independent reproduction on Windows x64 (CPU), plus three data points that may help scope this: how the cost scales, the status of the old opt-out on current releases, and what a user can do today.
Reproduction
jaxlib 0.11.1 + jax 0.11.2.dev0 (151feb1a67, main @ 2026-08-26), Windows 11 x64, CPython 3.13.1, CPU backend, reporter's script verbatim:
| forward | gradient |
|---|---|
| 5.8–6.5 ms (1,685 instructions) | 28.5–28.6 ms (11,667 instructions) |
Same qualitative picture as reported on macOS arm64: a ~12k-instruction loop body under reverse mode, bound at execution, not compilation. Optimised HLO hash 5693d198e4a292da matches across all runs below.
How the cost scales (gradient through the same scan, jaxlib 0.11.1):
| carry leaves (LENGTH=614) | gradient | grad-loop instructions |
|---|---|---|
| 4 | 2.4 ms | 859 |
| 16 | 5.5 ms | 3,175 |
| 32 | 16.3 ms | 6,263 |
| 60 | 31.2 ms | 11,667 |
| 80 | 43.6 ms | 15,527 |
| scan length (leaves=60) | gradient |
|---|---|
| 100 | 1.4 ms |
| 200 | 8.3 ms |
| 400 | 19.9 ms |
| 614 | 32.4 ms |
Both sweeps are close to linear, consistent with per-operation dispatch/execution overhead dominating: the cost tracks total instruction count in the loop body rather than a threshold effect, so this is not confined to pathological graphs — each extra scalar leaf adds its own slice of runtime to every call of the executable. Forward mode degrades too (0.2 ms → 7.8 ms across the same leaf sweep); the gradient hurts most because reverse mode multiplies the body out (~7× more instructions here).
Opt-out status on the current release: on jaxlib 0.11.1, --xla_cpu_use_thunk_runtime=false is accepted without warning and has zero effect — identical optimised-HLO hash, gradient 28.6 ms (default) vs 37.6 ms (flag set; within run-to-run noise, certainly no restoration). This extends the reporter's timeline to the current release on a second platform: last honoured on 0.6.2, fatal on 0.7.x, silently ignored ever since.
What users can do today: packing the carry into one array instead of N scalar leaves restores pre-regression-class performance on 0.11.1 with numerically equivalent results (max relative diff ~1e-7 over the full trajectory and its gradient):
| carry formulation | gradient | loop-body instructions |
|---|---|---|
| 60 scalar leaves (dict) | 31.1 ms | 11,667 |
one (60,) float32 array |
0.65 ms | 349 |
That's ~48× on this shape; the forward path benefits identically (5.2 ms → 0.11 ms). The reformulation uses jnp.roll for the ring-neighbour coupling and a gather for p[i % 3]. It is exactly the vectorised-state design the reporter notes isn't always desirable — but as an interim escape hatch it works on every affected release, and it may deserve a note in the docs/FAQ until the runtime side moves.
Agree with the request framing: either per-op overhead in the CPU thunk runtime must become competitive for many-op while bodies, or a supported opt-out needs to exist again. Happy to benchmark candidate fixes on this shape if useful.
Assistance disclosure: this comment and its measurement scripts were prepared with AI assistance; all numbers above were measured locally on the stated versions.
I also just encountered this issue. Increasing the following XLA option helps:
XLA_FLAGS="--xla_backend_extra_options=xla_cpu_small_while_loop_byte_threshold=16384"
If I understand it correctly, it increases the threshold of a compiler pass that decides whether to compile a while loop in a single kernel, which should be similar to the old non-thunk approach, or make "thunks" out of it, which are then evaluated in a potentially asynchronous DAG fashion, but which leads to a significant overhead. Default is 1 kiB, the 16 kiB above seems to be enough for your example above, but it might be necessary to increase it more depending on the loop. It represents the size of the estimated memory accessed per loop iteration.
There seems to be another performance regression between 0.11.0 and 0.11.1, but it seems to be unrelated to this issue. Edit: the performance regression between 0.11.0 and 0.11.1 seems to be already fixed: https://github.com/jax-ml/jax/issues/40101
@seantalts @penpornk
Following up on the threshold workaround already reported here, I opened a focused OpenXLA issue with a JAX-only float64 (3, 3) array-carry scan and no dot products.
On an M2 CPU with JAX/jaxlib 0.11.2, synchronized value_and_grad medians across three processes drop from 1.72 ms by default to 0.28 ms with --xla_backend_extra_options=xla_cpu_small_while_loop_byte_threshold=1218 (6.10×). Crossing 1217→1218 outlines the remaining while-loop as an xla_cpu_small_call; the inspected optimized-HLO bodies and numerical outputs agree.
The OpenXLA issue focuses on the sharp threshold boundary and the byte-based hoisting heuristic. I have not verified that the same threshold explains every case in this thread.
Looking into it, thanks! I'm glad you found a workaround for now. We'll try to tune this flag against our full benchmark suite and see if we can find a better default for everyone in the new code gen + thunks pipeline.
We've landed two fixes in XLA:CPU for this:
- https://github.com/openxla/xla/commit/106395652488e65783040e49592e35f942cc82d4 raises the default
xla_cpu_small_while_loop_byte_thresholdfrom1024to1000000000(after benchmarking across our full 80-module CPU HLO suite, where it improved geomean wall time by 10.4% with no compile-time regression). On the reproducer from this issue (registered as a benchmark in https://github.com/openxla/xla/commit/7060e3ab755bbe2c84339e40b5e8bc84e42d30b9), gradient execution time drops by 96.2% wall / 98.3% CPU (~28× speedup). - https://github.com/openxla/xla/commit/8ba88c0c8285d0a7b9f8c0fb55365ff6802471a9 configures
WhileThunkin the CPU thunk runtime to execute while-loop bodies with buffers <= 64 KiB sequentially instead of dispatching through the multi-threaded DAG executor on every iteration (~3.1× wall / ~8.2× CPU speedup even for non-hoisted loops).
These will be available in upcoming jaxlib nightly builds and the next release. Closing this issue — please feel free to reopen if you still see slowdowns!
Awsome! Thank you for fixing this.