jax icon indicating copy to clipboard operation
jax copied to clipboard

CPU: jit returns a wrong matrix (~34 %) when a jacrev-derived matrix and its linalg.inv are computed in one jit (regression in 0.8.0, still in 0.12.0.1)

Open AndreasSchachner opened this issue 3 weeks ago • 5 comments

Description

Description

On CPU, a small complex128 matrix built with jax.grad and jax.jacrev comes out correct from jit(metric). Computing it together with jnp.linalg.inv in one jit returns a different and wrong matrix, about 34 % off, with no error or warning. The inverse is the correct inverse of that wrong matrix. Eager evaluation is correct. In the original, larger case it agrees with an independent 60-digit mpmath computation to 1e-16.

Reproducer

import jax
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np

@jax.jit
def F(idx, z):  # cubic monomial picked by dynamic indices, plus an (all-zero) quadratic term
    return -idx[3] * z[idx[0]] * z[idx[1]] * z[idx[2]] / 6. + jnp.dot(jnp.zeros((2, 2)) @ z, z) / 2.

dF = jax.grad(F, argnums=1, holomorphic=True)

def periods(idx, z):
    f, df = F(idx, z), dF(idx, z)
    return jnp.concatenate((jnp.array([2 * f - z @ df]), df, jnp.ones(1), z))

def K(idx, sigma, z, zc):
    return -jnp.log(-1j * periods(idx, zc) @ (sigma @ periods(idx, z)))

metric = jax.jacrev(jax.grad(K, argnums=2, holomorphic=True), argnums=3, holomorphic=True)

def metric_and_inverse(*args):
    g = metric(*args)
    return g, jnp.linalg.inv(g)

idx = jnp.array([0, 0, 1, 6], dtype=jnp.int32)
sigma = jnp.array([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],
                   [-1, 0, 0, 0, 0, 0], [0, -1, 0, 0, 0, 0], [0, 0, -1, 0, 0, 0]], dtype=jnp.int32)
z = jnp.array([0.3 + 1.5j, 0.03 + 1.5j])
args = (idx, sigma, z, z.conj())

with jax.disable_jit():
    g_eager = np.asarray(metric(*args))
g_alone = np.asarray(jax.jit(metric)(*args))
g_pair, g_inv = map(np.asarray, jax.jit(metric_and_inverse)(*args))
rel = lambda x, y: np.linalg.norm(x - y) / np.linalg.norm(y)
print("jax", jax.__version__)
print("jit(metric) vs eager:              ", rel(g_alone, g_eager))
print("jit(metric_and_inverse)[0] vs eager:", rel(g_pair, g_eager))
print("inverse identity |g_eager @ inv - 1|:", np.linalg.norm(g_eager @ g_inv - np.eye(2)))

Output, jax/jaxlib 0.12.0.1, macOS arm64 CPU:

jit(metric) vs eager:               8.202142425602991e-16
jit(metric_and_inverse)[0] vs eager: 0.33993463423951864
inverse identity |g_eager @ inv - 1|: 0.3400858170952206

With jax 0.7.2, all three are about 1e-15.

Versions (CPU, each run in a fresh process)

  • macOS 26.1 arm64:
    • Correct: 0.4.35, 0.7.2.
    • Wrong: 0.8.0, 0.8.1, 0.10.0, 0.10.1, 0.11.2, 0.12.0.1. The error is identical in each.
  • Linux (jax/jaxlib 0.11.0): this snippet gives jit(metric_and_inverse)[0] vs eager: 0.33993463423951864, the value it gives on macOS. The larger case it was cut from also fails there with the macOS value (0.367711; x86-64, Python 3.13), and --xla_cpu_use_fusion_emitters=false and --xla_disable_hlo_passes=algsimp both remove that error.
  • Not tested: GPU; macOS 0.10.2, 0.11.0, 0.11.1; Linux versions other than 0.11.0.

Observations (from the larger case this was cut from)

  • jnp.linalg.solve and jnp.linalg.cholesky in place of inv also corrupt the matrix. Returning g @ g instead does not.
  • The bug needs:
    • the inner jax.jit on F;
    • the indices passed as a dynamic argument (a hardcoded monomial works);
    • sigma passed as an argument (a constant works);
    • the all-zero quadratic term.
  • Flags that remove it (0.12.0.1): --xla_disable_hlo_passes=algsimp; --xla_backend_optimization_level=2, 1 or 0.
  • Legacy emitter: --xla_cpu_use_fusion_emitters=false also removes it, in every version tested that still has the flag (up to 0.11.0, on Linux). The flag no longer exists from 0.11.2.
  • Flags that don't: --xla_backend_extra_options=-disable-lsr. On 0.7.2, forcing --xla_cpu_use_fusion_emitters=true still gives the correct result.
  • Probably not the same bug as openxla/xla#49176 or #51048:
    • #49176's reproducer fails on every version listed here, including 0.4.35, and the legacy emitter doesn't fix it.
    • #51048's reproducer fails on 0.10.0 but passes on 0.12.0.1 here, and -disable-lsr fixes #51048 but not this.

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

jax:    0.12.0.1
jaxlib: 0.12.0.1
numpy:  2.5.4
python: 3.13.13 | packaged by Anaconda, Inc. | (main, Apr 14 2026, 06:14:06) [Clang 20.1.8 ]
device info: cpu-1, 1 local devices
platform: Darwin 25.1.0, arm64 (Apple silicon)

AndreasSchachner avatar Nov 13 '26 16:11 AndreasSchachner

I reproduced this on Linux x86-64 with jax/jaxlib 0.12.0.1. The matrix can be corrupted even when the compiled function has no solve, inverse, or other LAPACK consumer. Appending this to the reproducer isolates the layout change:

from jax.experimental.layout import Layout, with_layout_constraint

reference = np.diag([2.0 / 9, 1.0 / 9])
for order in [(0, 1), (1, 0)]:
    layout = Layout(major_to_minor=order)

    @jax.jit
    def constrained_metric(*args):
        return with_layout_constraint(metric(*args), layout)

    print(order, rel(np.asarray(constrained_metric(*args)), reference))

I get 1.40e-16 for the row-major constraint and 0.339934634239519 for the column-major constraint. Setting only the output format via out_shardings, instead of applying the internal constraint, leaves both matrix-only cases correct here.

The reference is independent of eager execution: for the supplied indices, F(z) = -z0**2 * z1 and the period pairing is p(w).T @ sigma @ p(z) = -(z0-w0)**2 * (z1-w1). The mixed derivative at the supplied inputs is exactly diag(2/9, 1/9).

Codex assisted with the controls and derivation.

resonance-null avatar Nov 15 '26 19:11 resonance-null

I narrowed the CPU pass control to the first algsimp invocation in post_scatter_expansion_simplification (the occurrence index is zero-based). On Linux x86-64, with JAX and jaxlib 0.12.0.1, run the issue's original reproducer in a fresh process:

JAX_PLATFORMS=cpu python repro.py
JAX_PLATFORMS=cpu XLA_FLAGS=--xla_disable_hlo_passes=post_scatter_expansion_simplification/algsimp:0 python repro.py
CPU case Default Disable only that invocation
Original jit(metric_and_inverse) matrix error vs. eager 0.33993463423951864 8.200953623158079e-16
Original inverse residual against the eager matrix 0.34008581709522057 1.0491348862491398e-15
Matrix-only internal column-major case from the preceding comment, vs. the analytic diagonal 0.339934634239519 1.40339021992424e-16

For the matrix-only case, skipping scoped occurrences :1, :2, or :3 individually preserves the discrepancy, as does skipping those three together. The row-major control stays at 1.40339021992424e-16. This locates a pass invocation that changes the outcome on this build. The specific rewrite and the downstream mechanism are still open.

AI assistance (Codex) was used to run and compare the compiler controls.

resonance-null avatar Nov 15 '26 19:11 resonance-null

checked this against the latest pre-release from the nightly index on Linux x86-64 (CPU), running the original reproducer in a fresh process for each layout:

jax / jaxlib | (1, 0) | (0, 1) -- | -- | -- 0.12.0.1 | 0.3399 | 1.4e-16 0.12.1rc1 | 1.4e-16 | 1.4e-16

So it looks fixed in 0.12.1rc1. It may be worth closing once 0.12.1 is released, or adding the reproducer as a regression test.

Shakhtar-Sankur avatar Nov 18 '26 13:11 Shakhtar-Sankur

Thanks for checking the release candidate. I ran the same layout controls on Linux x86-64 CPU with stable jax==0.12.1 and jaxlib==0.12.1. Both layouts were within 1.4e-16 relative error of the analytic matrix. The original jitted matrix-and-inverse case also agrees, with a relative matrix error of 1.4e-16 and an inverse identity residual of 2.7e-16 against the analytic matrix.

This confirms your result on the stable CPU release. Codex assisted with the verification.

resonance-null avatar Nov 18 '26 17:11 resonance-null

I had Gemini look into this. The conclusion is that while it is indeed fixed in JAX 0.12.1 (just released), that was because an XLA change just happened to mask the underlying root cause. The real root issue is https://github.com/llvm/llvm-project/issues/243963

Closing because this miscompile is fixed at XLA head, even if it's for somewhat coincidental reasons.

hawkinsp avatar Nov 18 '26 18:11 hawkinsp