You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Wrong JVP/gradient of jax.scipy.linalg.qr(..., pivoting=True) for wide matrices #42633
For a wide matrix (m < n), the derivative of the R factor returned by jax.scipy.linalg.qr(a, pivoting=True) (and lax.linalg.qr(..., pivoting=True)) is wrong. The trailing n - m columns of dR don't match finite differences, so jax.grad through R gives wrong results without any error.
importnumpyasnpimportjax, jax.numpyasjnpjax.config.update("jax_enable_x64", True)
rng=np.random.default_rng(0)
A=rng.standard_normal((3, 5)) # wide matrixdA=rng.standard_normal((3, 5))
f=lambdaa: jax.scipy.linalg.qr(a, pivoting=True)[1] # R factor_, jvp_r=jax.jvp(f, (A,), (dA,))
eps=1e-6fd_r= (f(A+eps*dA) -f(A-eps*dA)) / (2*eps)
print(np.abs(jvp_r-fd_r).max())
# ||R||_F^2 == ||A||_F^2, so the gradient must be 2 * Aloss=lambdaa: jnp.sum(jax.scipy.linalg.qr(a, pivoting=True)[1] **2)
print(jax.grad(loss)(A)[0])
print((2*A)[0])
Expected: the JVP matches finite differences (error ~1e-10, as it does for square/tall pivoted QR and for unpivoted wide QR), and the gradient equals 2 * A.
The Q tangent is correct; only R is affected. Same result with x64 off.
Versions: jax/jaxlib 0.12.0.1 (CPU) and current main (75ce266).
Cause
In qr_jvp_rule (jax/_src/lax/linalg.py) the wide case computes dR2 = dQ^H X2 + Q^H dX2 with x2 = x[..., :, m:]. With pivoting the factorization is Q R = X P, and dx is already permuted (dx = dx[..., p[0]]), but x is not, so X2 holds the wrong columns.
Activity