Skip to content

BUG: check for non-finite input before calling gesdd/gelsd and handle it in np.cond - #32593

Merged
mattip merged 6 commits into
numpy:mainfrom
ikrommyd:check-all-finite-before-gesdd
Sep 17, 2026
Merged

mattip merged 6 commits into
numpy:mainfrom
ikrommyd:check-all-finite-before-gesdd

Conversation

@ikrommyd

@ikrommyd ikrommyd commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

PR summary

Closes gh-32591
Closes gh-18914

np.linalg.svd never returns on some LAPACK implementations when the input contains inf: dgesdd rescales by BIGNUM/inf = 0, which turns the inf into NaN, and dbdsqr then loops forever (Reference-LAPACK lapack#1409). The gesdd and gelsd wrappers now check for non-finite input and raise LinAlgError, as they already did for NaN. The check costs ≤ 1% of the SVD.

np.linalg.cond promises inf/nan for such input (gh-10571), so it now calls the svd gufunc directly with errors ignored, like its inv branch. This also makes NaN input give nan for every p regardless of the LAPACK version, which fixes gh-18914, and un-xfails TestCond.test_nan.

AI Disclosure

An AI model has reviewed the changes and also figured out that np.cond actually handles the undocumented nuclear norm.

@ikrommyd

ikrommyd commented Sep 11, 2026 •

Copy link
Copy Markdown
Member Author

Another way would be to do this in python like eig and eigvals do with the _assert_finite helper. Let me know if you wanna go that route instead.

Signed-off-by: Iason Krommydas <[email protected]>
@ikrommyd

Copy link
Copy Markdown
Member Author

cc @seberg and @mattip :)

@ikrommyd
ikrommyd marked this pull request as ready for review September 11, 2026 15:34

@seberg seberg left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, looks all fine to me, just a link out might be nice. Two small comments I don't actually care about:

  1. I suspect this bug was just around for-ever. Don't mind a release note, but also don't particularly need it. (I think the the one computer I tried had a strange build with lapack-lite.)
  2. I trust that this is really unmeasurably faster than anything (because the algorithms below always do multiple iterations).

One curiosity (I suspect it's fine): Can we also get in trouble for almost infinite results here, due to overflows in later calculation?

Comment thread numpy/linalg/umath_linalg.cpp Resolved
Comment thread numpy/linalg/umath_linalg.cpp Resolved
@seberg seberg added the 09 - Backport-Candidate PRs tagged should be backported label Sep 13, 2026
Signed-off-by: Iason Krommydas <[email protected]>
@ikrommyd

Copy link
Copy Markdown
Member Author

One curiosity (I suspect it's fine): Can we also get in trouble for almost infinite results here, due to overflows in later calculation?

Things like this work on my machines:

rng = np.random.default_rng(1234)
a = rng.random((6, 6))
scale = 2.0 ** 1000
s = np.linalg.svd(a * scale, compute_uv=False)
np.testing.assert_allclose(s, np.linalg.svd(a, compute_uv=False) * scale, rtol=1e-12)

@ikrommyd

Copy link
Copy Markdown
Member Author

@seberg should be good to merge right?

@ngoldbaum ngoldbaum left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some regressions on cond introduced by this PR:

import numpy as np

print(np.__version__)
A = np.ones((3, 3))
A[0, 1] = np.inf
for p in [None, 2, -2, 1, -1, 'fro', np.inf, -np.inf]:
    try:
        print(f"cond(A, {p!r}) = {np.linalg.cond(A, p)}")
    except np.linalg.LinAlgError as e:
        print(f"cond(A, {p!r}) raised LinAlgError: {e}")

The first inputs raise LinAlgError on this PR and return inf on main. Was that intended? If not, I think you need to work around it in cond.

Also note that returning inf there is intentional, see #10571.

Comment thread numpy/linalg/umath_linalg.cpp Resolved
@ngoldbaum

Copy link
Copy Markdown
Member

@ikrommyd I can push a commit that addresses my review if you'd like

@mattip

mattip commented Sep 16, 2026

Copy link
Copy Markdown
Member

That check is very very cheap to make compared to the actual computation.

Any idea how cheap? It is another pass across the array, which should be much faster than the actual calculation, but it might be nice to measure.

@ikrommyd

Copy link
Copy Markdown
Member Author

@ikrommyd I can push a commit that addresses my review if you'd like

Whoops I missed the notification that this PR had more comments. Will fix them.

@ikrommyd

ikrommyd commented Sep 16, 2026 •

Copy link
Copy Markdown
Member Author

That check is very very cheap to make compared to the actual computation.

Any idea how cheap? It is another pass across the array, which should be much faster than the actual calculation, but it might be nice to measure.

Less than 1% of the total SVD runtime on both my Ryzen 7 7800X3D Linux machine and my M4 Max macOS machine.

@ikrommyd

Copy link
Copy Markdown
Member Author

There are some regressions on cond introduced by this PR:

import numpy as np

print(np.__version__)
A = np.ones((3, 3))
A[0, 1] = np.inf
for p in [None, 2, -2, 1, -1, 'fro', np.inf, -np.inf]:
    try:
        print(f"cond(A, {p!r}) = {np.linalg.cond(A, p)}")
    except np.linalg.LinAlgError as e:
        print(f"cond(A, {p!r}) raised LinAlgError: {e}")

The first inputs raise LinAlgError on this PR and return inf on main. Was that intended? If not, I think you need to work around it in cond.

Also note that returning inf there is intentional, see #10571.

I need to think about this a bit. I believe we're getting into the territory of #18914 here and that those are closely related.

@ikrommyd ikrommyd changed the title BUG: check that all elements are finite before calling gesdd to prevent hangs or garbage results BUG: check for non-finite input before calling gesdd/gelsd and handle it in np.cond Sep 16, 2026
@ikrommyd

ikrommyd commented Sep 16, 2026 •

Copy link
Copy Markdown
Member Author

@ngoldbaum - please check the last commit and let me know what you think. I've updated the title and PR description too. I am relying on the new check in c++ in SVD to not run the LAPACK routine here regarding cond but can also move the check into python with something like isfinite(x).all() if youd'd prefer that but that would be a pass over the data in python and also cost more. I just followed the existing pattern where the branch that calls inv does with errstate(all='ignore') as well.

I'm also sneaking in a 1 line docstring fix here which is that np.cond was not saying the nuclear norm is an option in its docstring.

@ngoldbaum ngoldbaum left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO the release notes are too long and overly detailed. Claude likes to do that.

What about this instead (as a single combined improvement note):

* Fixed hangs in `numpy.linalg.svd` and `numpy.linalg.lstsq` for inputs containing infinite inputs for recent versions of some LAPACK implementations. 
* `numpy.linalg.cond` handles non-finite inputs more consistently.

Comment thread numpy/linalg/_linalg.py
x : (..., M, N) array_like
The matrix whose condition number is sought.
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
p : {None, 1, -1, 2, -2, inf, -inf, 'fro', 'nuc'}, optional

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I double-checked and this docstring change is just documenting behavior that already exists. This is not adding a new feature.

@ikrommyd

Copy link
Copy Markdown
Member Author

IMO the release notes are too long and overly detailed. Claude likes to do that.

What about this instead (as a single combined improvement note):

* Fixed hangs in `numpy.linalg.svd` and `numpy.linalg.lstsq` for inputs containing infinite inputs for recent versions of some LAPACK implementations. 
* `numpy.linalg.cond` handles non-finite inputs more consistently.

Did a slightly modified version of that because I also wanted to state that even in the case where there was no hang, SVD will now not return garbage results and raise instead.

@ikrommyd

Copy link
Copy Markdown
Member Author

I don't know if this is good to backport or not...technically it's a bugfix and is making behavior more consistent but at the same time we're changing behavior for the non-physical cases like raising.

@charris

charris commented Sep 16, 2026

Copy link
Copy Markdown
Member

I think it would be fine to backport. OTOH, the next release isn't that far off.

@ngoldbaum

Copy link
Copy Markdown
Member

but at the same time we're changing behavior for the non-physical cases like raising.

IMO it's worth it to help users hitting hangs...

@mattip
mattip merged commit c889997 into numpy:main Sep 17, 2026
91 checks passed
@mattip

mattip commented Sep 17, 2026

Copy link
Copy Markdown
Member

Thanks @ikrommyd

@ikrommyd
ikrommyd deleted the check-all-finite-before-gesdd branch September 17, 2026 16:06
@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: np.linalg.svd hangs forever on a square >=3x3 matrix containing 'inf' TestCond.test_nan test failure for latest OpenBLAS

5 participants