`jnp.linalg.det` is numerically unstable for 2x2 and 3x3 inputs: wrong sign / large relative error, and spurious `inf`
Description
On some 2x2 and 3x3 inputs jnp.linalg.det returns a determinant with the
wrong sign and a relative error of several hundred percent, or returns inf /
nan where the true determinant is well inside the dtype's range. numpy,
torch and JAX's own jnp.linalg.slogdet are all correct on the same inputs —
and so is jnp.linalg.det itself, once the offending matrix is embedded in a
4x4.
That last part is the tell: jax.numpy.linalg.det special-cases 2x2 and 3x3
inputs with a closed-form (Sarrus/cofactor) expansion instead of dispatching to
LU (https://github.com/jax-ml/jax/blob/main/jax/_src/numpy/linalg.py#L787-L792).
Minimal reproducer
import numpy as np
import jax.numpy as jnp
A = np.array([[41932.215, 41927.867, 41927.867],
[41927.867, 41932.215, 41927.867],
[41927.867, 41927.867, 41932.215]], dtype=np.float32)
ref = np.linalg.det(A.astype(np.float64))
print("cond : %.3e max|a|**3/|det| : %.2e"
% (np.linalg.cond(A.astype(np.float64)), np.abs(A).max() ** 3.0 / abs(ref)))
print("float64 reference det :", ref)
print("numpy float32 det :", np.linalg.det(A))
print("jax float32 det :", jnp.linalg.det(jnp.asarray(A)))
sign, logabsdet = jnp.linalg.slogdet(jnp.asarray(A))
print("jax float32 slogdet:", float(sign) * np.exp(np.float64(logabsdet)))
A4 = np.eye(4, dtype=np.float32); A4[:3, :3] = A
print("jax det, A inside a 4x4:", jnp.linalg.det(jnp.asarray(A4)))
Actual output
cond : 2.893e+04 max|a|**3/|det| : 3.10e+07
float64 reference det : 2377658.2651614198
numpy float32 det : 2377658.2
jax float32 det : -11429116.0 <-- wrong sign, 580% rel. error
jax float32 slogdet: 2377108.831911185
jax det, A inside a 4x4: 2377108.8
This is not a float32 artifact — the same structure in float64 with off-diagonal
a - 1e-3 (cond = 1.3e8) gives 0.12670822560883288 against an exact
0.12579664213596525, where numpy and slogdet stay correct to 9 digits — and
the expansion can overflow to inf (or to nan, once terms of opposite sign
overflow together) while the determinant itself is comfortably representable:
float32 [[c,d,d],[d,c,d],[d,d,c]] with c = 1e13, d = c - 2e6 has
det ~ 1.32e26 but returns inf.
Note that the 2x2 / 3x3 paths also bypass the custom_jvp defined on _det,
so derivatives are taken through the Sarrus expression and inherit the same
cancellation.
System info (python version, jaxlib version, accelerator, etc.)
jax: 0.11.1.dev20260810
jaxlib: 0.11.1.dev20260810
numpy: 2.2.6
python: 3.12.13 | packaged by conda-forge | (main, Mar 5 2026, 16:50:00) [GCC 14.3.0]
device info: cpu-1, 1 local devices"
process_count: 1
platform: uname_result(system='Linux', node='xx', release='6.8.0-134-generic', version='#134-Ubuntu SMP PREEMPT_DYNAMIC Fri Jun 26 18:43:11 UTC 2026', machine='x86_64')
JAX_ENABLE_X64=1
I think we can fix this by just using a closed form expansion of LU decomposition with row pivoting.