Skip to content

Wrong JVP/gradient of jax.scipy.linalg.qr(..., pivoting=True) for wide matrices #42633

Open

Description

@bhaskargurram-ai

Description

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.

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

rng = np.random.default_rng(0)
A = rng.standard_normal((3, 5))     # wide matrix
dA = rng.standard_normal((3, 5))

f = lambda a: jax.scipy.linalg.qr(a, pivoting=True)[1]   # R factor
_, jvp_r = jax.jvp(f, (A,), (dA,))
eps = 1e-6
fd_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 * A
loss = lambda a: jnp.sum(jax.scipy.linalg.qr(a, pivoting=True)[1] ** 2)
print(jax.grad(loss)(A)[0])
print((2 * A)[0])

Output:

0.7589119622584999
[ 0.25146044 -0.26420973  0.89923762  0.20980023 -0.91253656]
[ 0.25146044 -0.26420973  1.2808453   0.20980023 -1.07133875]

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions