Skip to content

Commit

Permalink
Translate LAPACK exception codes to an actionable error message.
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick Thompson authored and NAThompson committed Jan 26, 2025
1 parent 0cea88b commit da591af
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
16 changes: 10 additions & 6 deletions mlx/backend/common/cholesky.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,17 @@ void cholesky_impl(const array& a, array& factor, bool upper) {
/* lda = */ &N,
/* info = */ &info);

// TODO: We do nothing when the matrix is not positive semi-definite
// because throwing an error would result in a crash. If we figure out how
// to catch errors from the implementation we should throw.
if (info < 0) {
if (info != 0) {
std::stringstream msg;
msg << "[cholesky] Cholesky decomposition failed with error code "
<< info;
msg << "[cholesky] ";
// https://www.netlib.org/lapack/explore-html/d0/d18/group__ppsv_gab87078282c6c31853cfed4829976c0d9.html
if (info > 0) {
msg << "The leading principal minor of order " << info
<< " of the matrix is not positive, so the factorization could not be completed.";
} else {
msg << "The " << -info
<< " slot argument to the LAPACK Cholesky decomposition is invalid.";
}
throw std::runtime_error(msg.str());
}

Expand Down
4 changes: 4 additions & 0 deletions tests/linalg_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,10 @@ TEST_CASE("test matrix cholesky") {
CHECK_THROWS(linalg::cholesky(
array({1, 2, 3, 4, 5, 6}, {2, 3}), /* upper = */ false, Device::cpu));

// Non-positive semi-definite throws.
CHECK_THROWS(linalg::cholesky(
array({1, 2}, {2, 1}), /* upper = */ false, Device::cpu));

const auto prng_key = random::key(220398);
const auto sqrtA = random::normal({5, 5}, prng_key);
const auto A = matmul(sqrtA, transpose(sqrtA));
Expand Down

0 comments on commit da591af

Please sign in to comment.