Repository navigation
Guard MLX unmixing inversion against process abort - #293
Merged
Merged
Conversation
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
force-pushed
the
feature/issue-274-inv-guard
branch
from
August 23, 2026 22:48
a65afff to
bd41cba
Compare
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
MLX 0.32's CPU-stream
mx.linalg.invdoes 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 notry/exceptaroundfitcan catch._update_unmixing_matricesnow condition-checks each per-modelA[:, comp_list[:, h]]host-side, immediately before callinginv, and raises a catchableRuntimeErrornaming the model, iteration and condition number instead.Found while verifying PR #271's
W/_logdet_Wfiniteness 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 (1e16, returning a huge but finite inverse instead.8.4e6 with5e10, and matrices built by scaling one column toward (not to) zero never aborted even past condnp.finfo(float32).eps, or1.7e7 under the textbook unit-roundoff convention).9e8 to beyond condThat 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_candtest_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
Separately, an existing adversarial test (
test_mlx_newton.py::test_fallback_ramps_toward_lrate_cap_and_counts, which repeatedly stepsAfrom 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_THRESHOLDis set to 1e12:225x above that observed legitimate maximum, and far below where a genuinely singular1e15-1e17 on real fitted state.A(the issue's literal example, a duplicated component column) actually lands — exact or near-exact duplicates measured condNon-finite entries: fixed after review found a gap
np.linalg.cond's SVD raisesLinAlgErroron 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
invon a non-finiteApropagates NaN intoW(caught downstream bynan_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==0propagates 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 toinv/nan_paramsexactly as before.Any other non-finite pattern (a minority of entries, or none) has its non-finite entries replaced with
0.0before computing the condition number.0.0matters: 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 backcond=inf, indistinguishable.0.0is at the same natural scale asA's near-unit-norm columns and does distinguish them: a well-conditioned real matrix with one injected NaN readscond~35after 0-fill; the same matrix with an exact duplicate column plus that same stray NaN readscond~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 (cond
9e8 to beyond cond5e10) sits below the 1e12 threshold — a believed-rare residual window remains.A fully complete alternative (running
invitself 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-sidenp.linalg.condcall, for a defect this guard already makes rare.Cost and bit-identity
Guard overhead: ~32 microseconds per model per
_update_unmixing_matricescall (np.linalg.condon a 32x32 float32 matrix already pulled to host for the pre-existing CPU-streaminv/slogdetcall, 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-identicalAandWarrays (np.array_equaltrue, reconfirmed after the non-finite fix).Max condition number observed on the bundled sample across standard fits (single- and 2-model, with
do_newtonandshare_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):AraisesRuntimeErrornaming the model and iteration rather than aborting the processisfinitecheckRuntimeError, not a process abortAsubmatrix that is non-finite in every entry, reproduced via the establisheddgm[h]=0manipulation — does not raise from the guard;invreturns NaN as before, and the resultingWis exactly whatfit'snan_paramscheck would catch on that same iterationinv/slogdetcall on a healthy real fitted stateGates:
pytest pamica/tests/mlx_tests/ -q --no-covis 87 passed;pytest -m "not slow" -n autois 539 passed, 16 skipped, 1 xfailed;ruff check,ruff format --checkandty checkare all clean with zero new diagnostics, repo-wide.Docs
docs/guides/amica-differences.mdanddocs/changelog.mddocument 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