Skip to content

Guard MLX unmixing inversion against process abort - #293

Merged
neuromechanist merged 6 commits into
devfrom
feature/issue-274-inv-guard
Aug 23, 2026
Merged

neuromechanist merged 6 commits into
devfrom
feature/issue-274-inv-guard

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

MLX 0.32's CPU-stream mx.linalg.inv does not raise a catchable Python exception on a singular matrix.
LAPACK's LU failure aborts the whole process (libc++abi: ... [Inverse::eval_cpu] LU factorization failed), which no try/except around fit can catch.
_update_unmixing_matrices now condition-checks each per-model A[:, comp_list[:, h]] host-side, immediately before calling inv, and raises a catchable RuntimeError naming the model, iteration and condition number instead.
Found while verifying PR #271's W/_logdet_W finiteness guard; the upstream MLX report is being filed separately.

Threshold: empirically calibrated, not from float32 eps

The obvious starting point is float32's 1/eps precision-loss estimate (8.4e6 with np.finfo(float32).eps, or 1.7e7 under the textbook unit-roundoff convention).
That turned out to be far too conservative for this specific purpose and broke two existing tests on first attempt (test_multimodel_dead_model_keeps_prior_c and test_fallback_ramps_toward_lrate_cap_and_counts).
Isolated-subprocess bisection (each trial disposable, since a real LU failure aborts the process) showed the true abort onset is not a clean function of condition number: across 5 random near-duplicate-column 32x32 float32 matrices, the onset ranged from cond
9e8 to beyond cond
5e10, and matrices built by scaling one column toward (not to) zero never aborted even past cond
1e16, returning a huge but finite inverse instead.
Separately, an existing adversarial test (test_mlx_newton.py::test_fallback_ramps_toward_lrate_cap_and_counts, which repeatedly steps A from the same deliberately under-determined 256-sample block for 30 iterations) legitimately reaches cond~4.4e9 without ever hitting the abort — confirmed by sweeping the full pre-existing MLX test suite (118 tests) with the threshold set to infinity: 4.4e9 is the observed maximum.
_INV_COND_THRESHOLD is set to 1e12: 225x above that observed legitimate maximum, and far below where a genuinely singular A (the issue's literal example, a duplicated component column) actually lands — exact or near-exact duplicates measured cond1e15-1e17 on real fitted state.

Non-finite entries: fixed after review found a gap

np.linalg.cond's SVD raises LinAlgError on a matrix that already contains NaN/inf, a different failure than the one this guard targets, so non-finite entries need their own handling.
The first version of this PR skipped the condition check on ANY non-finite entry, reasoning that inv on a non-finite A propagates NaN into W (caught downstream by nan_params) rather than aborting — true for a matrix that is non-finite and otherwise nothing else.
A review pass caught the gap: a matrix that is BOTH non-finite in one unrelated entry AND structurally singular elsewhere — an exact duplicate column plus one stray NaN — still reaches the abort, because the duplicate-column singularity doesn't depend on what the unrelated NaN's true value would be.
Isolated-subprocess reproduction confirmed it: exit 134, libc++abi: ... LU factorization failed with error code 31.

The fix distinguishes two cases.
A matrix that is non-finite in EVERY entry — the actual, confirmed shape of a zero-responsibility ("dead") model's corruption, where dividing by dgm==0 propagates NaN/inf through the whole per-model direction matrix, not just one entry — carries no structural signal to check, so it's left to flow through to inv/nan_params exactly as before.
Any other non-finite pattern (a minority of entries, or none) has its non-finite entries replaced with 0.0 before computing the condition number.
0.0 matters: an extreme sentinel value was tried first and rejected, because it makes ANY non-finite entry read as "infinitely far" from the rest of the matrix by pure scale mismatch — a well-conditioned matrix with one stray NaN and a genuinely singular one both come back cond=inf, indistinguishable.
0.0 is at the same natural scale as A's near-unit-norm columns and does distinguish them: a well-conditioned real matrix with one injected NaN reads cond~35 after 0-fill; the same matrix with an exact duplicate column plus that same stray NaN reads cond~3.7e16.

This is not complete containment, and the code comments and docs now say so explicitly: no scalar condition number, sanitized or not, can guarantee catching every abort-capable matrix, since the observed LU-abort onset (cond9e8 to beyond cond5e10) sits below the 1e12 threshold — a believed-rare residual window remains.
A fully complete alternative (running inv itself in a disposable per-call subprocess) was considered and rejected as disproportionate: a subprocess spawn on the per-iteration hot path is a far larger, less predictable cost than one host-side np.linalg.cond call, for a defect this guard already makes rare.

Cost and bit-identity

Guard overhead: ~32 microseconds per model per _update_unmixing_matrices call (np.linalg.cond on a 32x32 float32 matrix already pulled to host for the pre-existing CPU-stream inv/slogdet call, so no new cross-stream handoff), ~0.28% of one single-model iteration on the bundled sample (~11.3 ms/it).
A 100-iteration full fit on the bundled sample, guarded vs. the pre-guard code (compared via git stash), is statistically indistinguishable in wall time (guarded 11.1-12.3 ms/it vs. baseline 10.9-14.0 ms/it across repeated trials, well within run-to-run noise) and produces byte-identical A and W arrays (np.array_equal true, reconfirmed after the non-finite fix).

Max condition number observed on the bundled sample across standard fits (single- and 2-model, with do_newton and share_comps): ~3.8, eleven orders of magnitude below the threshold.

Tests

pamica/tests/mlx_tests/test_mlx_inv_guard.py (8 tests, real fitted MLX state only, no synthetic/mock data):

  • a duplicated column on a real fitted A raises RuntimeError naming the model and iteration rather than aborting the process
  • the error message names the condition number and threshold
  • a near-singular (not bit-exact, not exactly zero) column also raises, proving the guard is a condition check rather than an exact-duplicate/isfinite check
  • the killer combination — a duplicated column plus one unrelated stray NaN, built on real warmed state — raises RuntimeError, not a process abort
  • the dead-model case — an A submatrix that is non-finite in every entry, reproduced via the established dgm[h]=0 manipulation — does not raise from the guard; inv returns NaN as before, and the resulting W is exactly what fit's nan_params check would catch on that same iteration
  • a 2-model fit correctly names model 1 when only its submatrix is singular
  • the guard is bit-identical to an unguarded inv/slogdet call on a healthy real fitted state
  • a standard 2-model fit completes unaffected

Gates: pytest pamica/tests/mlx_tests/ -q --no-cov is 87 passed; pytest -m "not slow" -n auto is 539 passed, 16 skipped, 1 xfailed; ruff check, ruff format --check and ty check are all clean with zero new diagnostics, repo-wide.

Docs

docs/guides/amica-differences.md and docs/changelog.md document the guard, the threshold rationale, the non-finite handling and its fix, and the explicit residual-containment caveat, plus the cost/bit-identity measurements above.

Closes #274

MLX's CPU-stream mx.linalg.inv aborts the whole process on a
singular matrix instead of raising. Condition-check each per-model
A submatrix host-side before inv and raise RuntimeError instead.

Closes #274
Singular and near-singular A on a real fitted model raise
RuntimeError instead of aborting; the guard is bit-identical to an
unguarded inv/slogdet call; a standard fit is unaffected.
Update amica-differences.md and the changelog for the issue #274
condition-number guard, with the measured overhead and threshold
rationale.
A non-finite entry combined with a real singularity elsewhere (e.g.
a duplicate column plus one stray NaN) was skipping the cond check
entirely and still reaching MLX's uncatchable abort. Only skip when
every entry is non-finite (the real dead-model corruption shape);
otherwise 0-fill non-finite entries before computing cond, so the
underlying singularity is still caught.
Duplicate column plus a stray NaN raises RuntimeError, not a
process abort. A purely non-finite dead-model A flows through to
inv/nan_params unraised, matching pre-guard behavior.
Carry the guard's own hedge into the docs: no scalar cond threshold
catches every abort-capable matrix, and a believed-rare window
remains. Document the 0-fill mechanism and the rejected
per-call-subprocess alternative.
@neuromechanist
neuromechanist force-pushed the feature/issue-274-inv-guard branch from a65afff to bd41cba Compare August 23, 2026 22:48
@neuromechanist
neuromechanist merged commit e7fda36 into dev Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-274-inv-guard branch August 23, 2026 23:04
@neuromechanist neuromechanist mentioned this pull request Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MLX linalg failure aborts the process instead of raising

1 participant