jax icon indicating copy to clipboard operation
jax copied to clipboard

`jnp.linalg.svd` gradients return `nan` for intermediate overflow

Open shadow-orange41 opened this issue 3 months ago • 2 comments

Description

jnp.linalg.svd derivatives form (σ_i + σ_j)(σ_i − σ_j) as in _svd_jvp_rule in jax/_src/lax/linalg.py, however, the product is still σ²-sized, so they return nan for matrices whose scale is outside ±sqrt(finfo.max).

Minimal reproducible example

import jax
import jax.numpy as jnp

f = lambda A: jnp.sum(jnp.linalg.svd(A, compute_uv=False))  
amax = lambda x: jnp.max(jnp.abs(x))

A = jnp.asarray([[4., 1., 0.],
                 [1., 3., 1.],
                 [0., 1., 2.]], dtype=jnp.float32)

print(amax(jax.hessian(f)(A * 1e-20)))    # nan           (should be 2.0707e+19)

Output:

nan

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

shadow-orange41 avatar Aug 25 '26 06:08 shadow-orange41

{"body": "## Reproduced on current main, plus a sharper characterization and a working prototype fix\n\nConfirmed end-to-end on main (8c191b842df0, CPU backend): the reporter's snippet returns nan.\n\n### Two distinct failure regimes (measured thresholds)\n\nThe rule builds s_diffs = (s_dim + _T(s_dim)) * (s_dim - _T(s_dim)) (jax/_src/lax/linalg.py around L2353) and then F = 1 / (s_diffs + eye) - eye. Everything is decided by whether sigma^2 stays inside the dtype range (boundaries match sqrt(finfo)):\n\n| A scaled by | dtype | sigma^2 | result of hessian(sum(sigma)) |\n|---|---|---|---|\n| 1e-18 .. 1e-19 | fp32 | >= min normal | correct (2.07e17 .. 2.07e18) |\n| 1e-20 (reporter's repro) | fp32 | flushed to 0 (FTZ) | nan (F_ij = 1/0 = inf, then inf * 0) |\n| 1e15 .. 1e18 | fp32 | <= max | correct |\n| >= 1e19..1e20 | fp32 | overflows to inf | silently 0.0 \u2014 F_ij = 1/inf = 0, wrong-but-finite (arguably worse than nan) |\n| both extremes | fp64 | in range | correct (upstream fp64 handles 1e-20 and 1e20 fine) |\n\nSo the issue's own repro exercises the underflow regime; the title's "overflow" regime actually produces quiet zeros, not nan. Both trace to the same line forming sigma^2.\n\n### Prototype fix: never form sigma^2\n\nFold the sigma weights into the numerator before dividing, mirroring dSS + _H(dSS) / SdS + _H(SdS):\n\npython\n# F_ij * (s_j*dS_ij + s_i*conj(dS_ji)) = ((s_j*dS_ij + s_i*conj(dS_ji)) / (s_i+s_j)) / (s_i-s_j)\nadd = s_dim + _T(s_dim)\nsub = s_dim - _T(s_dim)\nmask = sub == 0 # preserves upstream repeated-sigma masking\nsafe = jnp.where(mask, jnp.ones_like(sub), sub)\nst = lambda z: z.astype(A.dtype) # keep complex promotion strict-safe\nnum_U = st(s_dim) * dS + st(_T(s_dim)) * _H(dS)\nFU = jnp.where(mask, jnp.zeros_like(num_U), (num_U / st(add)) / st(safe))\n# analogously num_V = st(_T(s_dim)) * dS + st(s_dim) * _H(dS)\n\n\nEvery intermediate is bounded by O(|dS|); nothing squares sigma.\n\n### Verification (all local, CPU)\n\n- Equivalence: patched vs upstream JVP outputs (dU, dV) over 50 random orthogonal/diagonal square cases (n=2..5) + rectangular 4x3: max abs diff 7.1e-15 / 4.4e-16 (fp64).\n- Official suite: tests/linalg_test.py -k \"Svd or svd\" with the patched rule monkeypatched into ad.primitive_jvps[svd_p]: 39 passed, 2 skipped \u2014 identical to the unpatched baseline run (covers complex dtypes, rectangular shapes, grad/JVP-of-VJP paths).\n- Reporter case: fp32 jax.hessian at 1e-20 scale now returns 2.070707e+19 (correct; was nan). fp64 unchanged/correct at both extremes.\n- Repeated-sigma semantics: mask on sub == 0 reproduces upstream's s_diffs == 0 masking exactly (diff 0 on a repeated-eigenvalue case).\n- Residual limitation (not fixed): fp32 overflow-direction (A*1e20) still yields 0.0 after the patch; fp64 is exact there. Fixing that regime likely needs an explicit rescaling strategy, which I'd leave to maintainer judgment.\n\nAnalysis and prototype prepared with AI assistance (disclosed per the contribution policy); all numbers above were produced by local runs against main. Happy to open a PR with the folded rule + boundary regression tests (both sqrt(finfo.max) and FTZ sides) if maintainers want this approach."}

CAOShurong avatar Aug 26 '26 01:08 CAOShurong

@CAOShurong JAX's AI usage policy forbids using an agent to interact with developers on issues and pull requests. Please refrain from this in the future.

jakevdp avatar Aug 26 '26 17:08 jakevdp