Skip to content

Phase 3: port Newton to the MLX backend - #271

Merged
neuromechanist merged 9 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-264-phase3-mlx-newton
Aug 23, 2026
Merged

neuromechanist merged 9 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-264-phase3-mlx-newton

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Ports the Newton preconditioner to the MLX backend, closing the last of the three feature gaps between AMICAMLXNG and AMICATorchNG (after convergence stops in #248 and component sharing in #263). AMICAMLXNG now takes do_newton/newt_start/newtrate/newt_ramp with the PyTorch backend's names, defaults and semantics: the same curvature accumulators riding the existing E-step locals (no extra pass over the data), the same finalization against the model mass, the same closed-form per-source-pair 2x2 solve behind the same unguarded prod > 1 positive-definiteness test, the same ramp to newtrate (and to lrate_cap on a fallback), the same maxdecs ratchet and numdecs reset arms, and the same n_newton_fallbacks counter with Fortran's verbatim warning. The direction needs no linear algebra, so it stays on the GPU stream; the only new host sync is the scalar posdef flag, which has to reach Python because it selects the ramp target and drives the fallback counter, and it joins the small per-iteration syncs the M-step already makes. While there, the stale comment claiming one-mx.eval purity seven lines above an existing sync was corrected to describe what the backend actually does.

The float32 question was pre-registered as a three-way go/no-go rather than assumed (Apple GPUs have no FP64, and MLX's CPU stream would have offered a float64-curvature middle path). Outcome: GO on float32, all four criteria passing with two to three orders of margin. G1 (formula): the finalized sigma2/lambda/kappa match a float64 AMICATorchNG twin held at the identical state to 3.8e-07 / 3.6e-07 / 2.1e-07 relative, and one full Newton M-step moves A to within 9.8e-08 (early state) and 2.4e-07 (warmed 55 iterations) — bar was 1e-4. G2 (stability): six full-recording 150-iteration fits, three seeds each at the default schedule and at the #24 sample_params schedule (newt_start=50, newtrate=1.0, lrate=0.05, block_size=512), all finite, all stopping on max_iter, zero Newton fallbacks. G3 (quality): at a matched 100-iteration budget MLX float32 reaches -3.41149 against float64 PyTorch Newton's -3.41149 (default) and -3.41097 against -3.41096 (sample_params) — five significant digits, versus a 0.05 bar. G4 (conditioning): min(prod - 1) over accepted pairs stayed in 1.978-2.128 across every Newton iteration of those six fits, indistinguishable from the float64 reference measurement of 2.09 in .context/issue-145/, and three orders above the 1e-3 bar. The gate script and full evidence are committed at .context/issue-264/gate.py and .context/issue-264/newton_findings.md.

G5 (overshoot exposure, a measurement rather than a bar): max(ll_history) - final_ll_ came back at exactly 0.000e+00 on all six fits — the likelihood is monotone under Newton on this data, so the final iterate is the best iterate. The decided policy was to file a follow-up issue for MLX keep_best if any fit exceeded 0.05; none came within measurement resolution of it, so no keep_best follow-up is warranted on this evidence, and keep_best stays out of scope for the epic.

Newton-off behavior is bit-identical, not merely equivalent. Three configurations (single-model, 2-model, 2-model with share_comps) were fitted for 40 iterations on 8192 real samples before and after the core change and compared on the full likelihood trajectory, the raw bytes of A, and ndtmpsum: identical in all three. Structurally, every curvature accumulator is gated on self.do_newton (so a natural-gradient fit does none of the work and _accumulate_blocks' generic key loop needs no change), newton_active is False throughout, and the ramp falls through to the lrate_cap branch that was there before.

Also fixes #267: numpy_impl/core.py finalized the Newton curvature by dividing its (data_dim, num_models) accumulators by dgm[:, None] — a (num_models, 1) model mass, which broadcasts only when num_models == 1. The issue reported it from a share_comps collapse, but it needs no sharing at all: every multi-model NumPy Newton fit raised ValueError: operands could not be broadcast together with shapes (32,2) (2,1) on the first iteration Newton was active. Reproduced before the fix, corrected to dgm[None, :] (the torch backend's dgm.unsqueeze(0)), and regression-tested for 1, 2 and 3 models in pamica/tests/test_numpy_newton_multimodel.py. The MLX port carries the same trap on the opposite axis, since its layout is model-major; .context/issue-264/newton_findings.md records both.

Tests, all on real bundled sample EEG with no mocked curvature. Cross-backend (pamica/tests/test_mlx_newton_cross_backend.py, placed outside mlx_tests/ per .rules/backend_parity.md): curvature vs the float64 twin at an early and a warmed state; a warmed Newton M-step on the positive-definite path (reached naturally after 55 iterations, margin 2.27); the early-block fallback path (reached by a genuinely under-determined 256-sample block, min prod - 1 = -0.96 across 344 of 992 pairs) where both backends reject, both count one fallback, and the MLX fallback step is bit-identical to a do_newton=False model stepped from the same state; two-model Newton with and without a forced shared column; and a slow matched-budget LL gate. MLX-local (pamica/tests/mlx_tests/test_mlx_newton.py): full-data stability, the four schedule arms (ramp to newtrate while posdef, ramp to lrate_cap on fallback, newtrate ratcheting only at maxdecs and only past newt_start, and the numdecs reset at newt_start, the last two replayed from each run's own ll_history so they pin the semantics rather than a constant), the per-fit schedule reset, the pre-update-mu ordering (a pass-through spy on the real method, the torch precedent), multi-model shapes through the real M-step, and the sharing interplay. test_mlx_backend.py no longer expects do_newton=True to raise and gained a Newton-curvature comparison against the validated float64 NumPy reference.

The two learning-rate ratchet tests were reworked after the first CI run: they needed likelihood decreases to fall on particular sides of newt_start, and when a fit decreases is BLAS- and hardware-dependent — the same effect this repo already documents for the min_dll stop firing at iteration 326 on macOS-arm64, 412 on Linux-CUDA and 1076 on a GitHub runner. A hardcoded newt_start that straddled the cadence on the development machine went vacuous on the CI Apple-Silicon runner, tripping the test's own non-vacuity guard. They are now data-driven: a probe fit whose newt_start sits past the budget reports where the decreases actually land on the executing machine, and newt_start is chosen from that. This is sound because the natural-gradient prefix is independent of newt_start — for it < newt_start every branch that reads it is false on both sides, so the two runs are bit-identical there. Two further changes made the guards hold rather than merely be checked: the newtrate test was split into complementary halves (one run with a ratchet before the gate for suppression, one with newt_start=0 for admission) so neither depends on a single run producing cycles on both sides; and the fixture's newtrate was raised from 1.0 to 2.0, because at 1.0 the post-switch-on trajectory was monotone on larger sample counts and left the cadence nothing to fire on. The numdecs-reset test picks its newt_start at a probe-observed partial fill, then scans for the smallest budget at which the reset and no-reset hypotheses predict different lrate_cap values and re-runs there (sound because the loop is causal). The final configuration was verified over 4 seeds × 2 block sizes × 3 sample counts — a deliberately harsher stand-in for cross-machine variation — with all 16 variants satisfying every assertion and non-vacuity guard. No assertion was weakened or removed.

Gates: the targeted suite (mlx_tests/ + both MLX cross-backend files + the numpy Newton regression) is 67 passed; the full suite at -m "not slow" -n auto is 484 passed, 15 skipped, 1 xfailed; ruff check, ruff format --check and ty check are all clean with zero new diagnostics. The new slow test was run once locally and passes (5.4s), and the repo-wide -m slow run is 6 passed, 3 skipped, 2 xfailed. CI does run these tests: the macOS Apple-Silicon job installs MLX and executes mlx_tests/ plus the MLX cross-backend files, so the port is guarded there like any other backend; only the ubuntu jobs skip them. What stays local is the gate sweep itself, a multi-minute measurement rather than a test, so .context/issue-264/ is the record for the float32 decision.

Deviations from the approved plan, all additive: (1) the plan's _STAT_KEYS extension in test_mlx_backend.py could not be a literal key extension, because the NumPy reference accumulates dkappa/dlambda already summed over the mixture index with mu^2 folded in while MLX (like PyTorch) folds it in at finalization — so the three keys are covered by a new test_newton_stats_match_numpy_reference that compares at the finalized level, which is also where the broadcast under test lives; (2) added a two-model cross-backend M-step test, parametrized on a forced shared column, beyond the plan's list, because that is where the share_comps × Newton interaction and the #267-class broadcast trap are both observable; (3) the sharing-interplay fit test uses the shipped comp_thresh default rather than a loose 0.9 — at 0.9 nearly every cross-model pair merges, the two models collapse onto one another, and Newton can drive a component to zero curvature; that regime aborts on the nan_params guard at some seeds in MLX and in float32 AMICATorchNG, so it is documented in the findings as a property of the near-total-merge regime rather than pinned as a test. Note also that the accepted posdef host sync is one scalar read per model per Newton iteration (one per iteration for the default single-model case), which is what the plan's own code specification for _newton_direction implies.

Review response

All findings from the four-specialist review are addressed. Silent-failure (critical): fit's nan_params check now covers self.W and self._logdet_W. They are derived from A by mx.linalg.inv/slogdet, so a non-finite value can reach the caller while A is still finite — and on the FINAL iteration nothing else catches it, since there is no next E-step to turn it into a nan_ll stop; the fit would return stop_reason="max_iter" with a healthy-looking final_ll_ (computed from the previous iteration's W) and a silently non-finite unmixing matrix. _logdet_W joined the per-iteration mx.eval list so both reads stay sync-free, and np.isfinite(W) assertions were added to the three e2e/stability tests.

W-guard discrimination evidence (temporary local injection, not committed): injecting inf into one W entry on the final iteration gives Non-finite W at iter 3 ... stopping. → stop_reason='nan_params', final_ll_=nan; injecting -inf into _logdet_W gives Non-finite logdet_W at iter 3 → same. In both states the pre-fix checked dict (A/mu/alpha/beta/rho/gm/c/ndtmpsum) was entirely finite, i.e. the old code would have returned max_iter with a corrupt W — the exact failure mode confirmed. One correction to the stated rationale: the near-singular-A route is not reachable in float32. Driving A toward singularity (column duplication at 1e-7…1e-15, or scaling A by 1e-30…1e-38) either leaves max|W| finite at ~1e8–1e30 or makes MLX's LAPACK abort the process first (libc++abi: ... [Inverse::eval_cpu] LU factorization failed), which is not a catchable Python exception. The guard is therefore documented as defense-in-depth rather than a route known to be reachable, and _update_unmixing_matrices' docstring — which claimed a singular A "raises" — was corrected to record the process-abort behavior.

Tests added: test_newton_inactive_is_bit_identical (the twin of test_unscheduled_sharing_is_bit_identical: do_newton=False vs do_newton=True, newt_start=10**6, exact equality on A/mu/gm, ll_history and _ndtmpsum); test_newton_direction_matches_formula (controlled-input pin of the closed form and of MLX's mx.eye(dtype=bool) posdef reduction, which differs from torch's boolean-mask version, with one posdef-True and one posdef-False call); test_grad_norm_floor_fires_under_newton (the #207 scenario, unreachable on MLX before this PR — newt_start=2, newtrate=3.0, use_min_dll=False, min_nd=1.0 → stop_reason == "grad_norm_floor" while lrate > minlrate); and test_newton_fit_is_stable_on_full_data parametrized over 3 seeds.

Comment/doc corrections: the do_newton docstring cited amica15.f90:1817-1832, which is the mu/beta/rho update block — corrected to :1718-1741 (the 2x2 solve and posdef guard) and :1803-1816 (ramp/fallback), both verified against the Fortran source. torch_impl/core.py:1324 → :1323 for dgm.unsqueeze(0) (the changelog bullet cites the call without a line number, so it needed no change). The stale core.py:635-639 population-covariance cross-reference now points at torch_impl/core.py:823-827. The per-platform min_dll breakdown (326 / 412 / 1076) is not in docs/guides/validation.md, which records only the aggregate 326-1076 range — both the findings doc and the test module docstring now cite the aggregate from validation.md and attribute the breakdown to torch_tests/test_ng_convergence.py:682-683. The module docstring now states that the posdef sync is one read per MODEL per Newton iteration (n_models for a multi-model fit), matching _newton_direction's own docstring, rather than grouping it with the single array-wide dead-model/rho-NaN canaries. And test_mlx_convergence_stops.py's "no Newton (MLX has none)" is reworded to say the comparison deliberately isolates the natural-gradient path.

Rejected, with reasons. (a) Newton-activation/ratchet log lines and per-model fallback granularity: the current logging is verified identical to torch and Fortran, so changing it is a cross-backend design decision and out of this phase's scope. (b) The slow-marked G3 quality test being excluded from the default CI run: this matches the repo's existing convention for slow parity tests. (c) An e2e test of #267's original share_comps scenario: the fix is a broadcast-axis correction that is scenario-independent, so the minimal multi-model repro is the correct regression surface. Separately, the lead is filing follow-up issues for the pre-existing 3-model-Newton and Newton-with-rank-reduced-data coverage gaps, which affect all backends and are not this PR's debt.

Closes #264

Closes #267

Part of epic #260

@neuromechanist
neuromechanist merged commit a8401fa into feature/issue-260-epic-mlx-parity Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-264-phase3-mlx-newton branch August 23, 2026 10:59
neuromechanist added a commit that referenced this pull request Aug 23, 2026
The do_newton=False comment was stale: it described a shape crash
that was issue #267 itself, fixed in PR #271 (dgm[None, :]) and
already regression-tested up to 3 models. Turning Newton on here
(newt_start=3) closes the numpy leg of the rank-reduction x sharing x
Newton three-way gap noted in PR #284 -- a share pass collapses 7
components on the rank-16 sphere and the fit still completes finite
and converged.
neuromechanist added a commit that referenced this pull request Aug 23, 2026
* Add 3-model Newton coverage test for MLX backend

Closes the #272 gap: MLX Newton tests only ran n_models<=2, which
cannot distinguish a correct per-model curvature index from a
transposition error that happens to line up for exactly two models.

* Extend numpy 3-model Newton test with stop/param checks

The #267 regression test already covered num_models up to 3 but only
asserted curvature shape/finiteness. Add the non-degenerate stop and
full-parameter finiteness checks that the torch/MLX #272 tests carry,
verifying the numpy 3-model Newton path to the same depth.

* Add 3-model Newton coverage test for torch backend

The existing test_newton_multimodel_finite_and_shaped stops at
n_models=2, which cannot distinguish a correct per-model curvature
index from a transposition error that happens to line up for exactly
two models (issue #272).

* Add 3-model cross-backend Newton curvature comparison

Extends the existing 2-model MLX-vs-float64-torch curvature/M-step
comparison to a third model. Cheap: _warm_model/_torch_twin already
parametrize on n_models, so this closes the #272 cross-backend gap
with only the argument changed.

* Add rank-reduced Newton coverage test for MLX backend

All existing MLX Newton tests fit full-rank 32-channel data. Cover the
#221/#223 Maxwell-filtered MEG route: real EEG projected onto a
rank-20 subspace, fitted with automatic rank detection and Newton on
(issue #273).

* Add rank-reduced Newton coverage test for numpy backend

Real EEG projected onto a rank-20 subspace, fitted with automatic rank
detection and do_newton on -- the #221 MEG route, untested on the
numpy Newton path until now (issue #273). Passes: self.data_dim sizes
the curvature and the 2x2 direction loop alike, so the reduced rank
did not need a fix.

* Add rank-reduced Newton coverage test for torch backend

No test in this module sets do_newton, and rank reduction changes
n_channels/n_comps and the sphere shape mid-preprocess, which the
Newton curvature arrays and closed-form direction inherit
(issue #273, the #221/#223 MEG route).

* Add sharing x Newton x pdf-family test for MLX backend

The three features (share_comps, do_newton, a non-default pdftype)
only have pairwise coverage: sharing x Newton, Newton x families, and
sharing x switcher each live in separate tests. Pin the composition
directly with a fixed-family (pdftype=2) and an adaptive-switcher
(pdftype=1) variant (issue #277).

* Add sharing x Newton x pdf-family test for torch backend

The torch equivalent of the MLX three-way test: share_comps=True,
do_newton=True, and a non-default pdftype together had only pairwise
coverage until now (issue #277).

* Enable Newton in the rank-reduced numpy sharing test

The do_newton=False comment was stale: it described a shape crash
that was issue #267 itself, fixed in PR #271 (dgm[None, :]) and
already regression-tested up to 3 models. Turning Newton on here
(newt_start=3) closes the numpy leg of the rank-reduction x sharing x
Newton three-way gap noted in PR #284 -- a share pass collapses 7
components on the rank-16 sphere and the fit still completes finite
and converged.

* Review fixes: full param check, shared degenerate-reasons tuple

test_newton_three_model_finite_and_shaped now checks the full
A/W/mu/alpha/beta/rho/gm/c finiteness loop the numpy/MLX #272 tests
already carry, instead of only c and A. Both hardcoded
("nan_ll", "singular_ll") tuples in this file (the one this PR added
and the pre-existing one in test_multimodel_rejection_keeps_bias_c_finite)
now reference AMICATorchNG._DEGENERATE_STOP_REASONS instead of
duplicating the literal.

* Match numpy/MLX depth in rank-reduced Newton test

test_rank_reduced_newton_fit_completes checked only A and the
unmixing matrix. Add the full W/mu/alpha/beta/rho/gm/c finiteness
loop so the torch #273 test carries the same depth as its numpy and
MLX counterparts.

* Match 2-model sibling depth in 3-model cross-backend test

test_three_model_newton_curvature_matches_float64_twin was missing
the n_newton_fallbacks parity check and the _ndtmpsum agreement
(rel=1e-4) that its 2-model sibling
(test_multimodel_newton_mstep_matches_float64_twin) already carries.

* Move MLX three-way tests out of the Newton chaos zone

comp_thresh=0.9 + seed=42 sits in the near-total-collapse regime
.context/issue-264/newton_findings.md documents as trajectory chaos
(26-31 of 32 cross-model pairs merging on a 2-model fit, seed- and
config-dependent nan_params on MLX). Moved both three-way tests to
the doc's verified stable zone, comp_thresh=0.99/seed=3 (the same
seed test_low_rank_projected_data_share_fit_completes uses). Verified
locally that merges still fire well short of the chaos threshold: 11
of 32 pairs for the fixed-family variant, 8 of 32 for the adaptive
switcher, so the comp_used guard stays non-vacuous.

* Move torch three-way tests out of the Newton chaos zone

Same fix as the MLX three-way tests: comp_thresh=0.9/seed=42 sits in
the near-total-collapse regime .context/issue-264/newton_findings.md
documents as trajectory chaos. Moved to the doc's verified stable
zone, comp_thresh=0.99/seed=3. Verified locally: 11 of 32 pairs merge
for the fixed-family variant, 8 of 32 for the adaptive switcher.
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.

1 participant