Repository navigation
Phase 3: port Newton to the MLX backend - #271
Merged
neuromechanist merged 9 commits intoAug 23, 2026
Merged
neuromechanist merged 9 commits into
neuromechanist merged 9 commits into
Conversation
This was referenced Aug 23, 2026
neuromechanist
merged commit Aug 23, 2026
a8401fa
into
feature/issue-260-epic-mlx-parity
8 checks passed
This was referenced Aug 23, 2026
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.
This was referenced Aug 23, 2026
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.
Ports the Newton preconditioner to the MLX backend, closing the last of the three feature gaps between
AMICAMLXNGandAMICATorchNG(after convergence stops in #248 and component sharing in #263).AMICAMLXNGnow takesdo_newton/newt_start/newtrate/newt_rampwith 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 unguardedprod > 1positive-definiteness test, the same ramp tonewtrate(and tolrate_capon a fallback), the samemaxdecsratchet andnumdecsreset arms, and the samen_newton_fallbackscounter 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 scalarposdefflag, 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.evalpurity 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/kappamatch a float64AMICATorchNGtwin held at the identical state to 3.8e-07 / 3.6e-07 / 2.1e-07 relative, and one full Newton M-step movesAto 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 #24sample_paramsschedule (newt_start=50,newtrate=1.0,lrate=0.05,block_size=512), all finite, all stopping onmax_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.pyand.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 MLXkeep_bestif any fit exceeded 0.05; none came within measurement resolution of it, so no keep_best follow-up is warranted on this evidence, andkeep_beststays 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 ofA, andndtmpsum: identical in all three. Structurally, every curvature accumulator is gated onself.do_newton(so a natural-gradient fit does none of the work and_accumulate_blocks' generic key loop needs no change),newton_activeis False throughout, and the ramp falls through to thelrate_capbranch that was there before.Also fixes #267:
numpy_impl/core.pyfinalized the Newton curvature by dividing its(data_dim, num_models)accumulators bydgm[:, None]— a(num_models, 1)model mass, which broadcasts only whennum_models == 1. The issue reported it from ashare_compscollapse, but it needs no sharing at all: every multi-model NumPy Newton fit raisedValueError: operands could not be broadcast together with shapes (32,2) (2,1)on the first iteration Newton was active. Reproduced before the fix, corrected todgm[None, :](the torch backend'sdgm.unsqueeze(0)), and regression-tested for 1, 2 and 3 models inpamica/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.mdrecords both.Tests, all on real bundled sample EEG with no mocked curvature. Cross-backend (
pamica/tests/test_mlx_newton_cross_backend.py, placed outsidemlx_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, minprod - 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 ado_newton=Falsemodel 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 tonewtratewhile posdef, ramp tolrate_capon fallback,newtrateratcheting only atmaxdecsand only pastnewt_start, and thenumdecsreset atnewt_start, the last two replayed from each run's ownll_historyso they pin the semantics rather than a constant), the per-fit schedule reset, the pre-update-muordering (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.pyno longer expectsdo_newton=Trueto 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 themin_dllstop firing at iteration 326 on macOS-arm64, 412 on Linux-CUDA and 1076 on a GitHub runner. A hardcodednewt_startthat 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 whosenewt_startsits past the budget reports where the decreases actually land on the executing machine, andnewt_startis chosen from that. This is sound because the natural-gradient prefix is independent ofnewt_start— forit < newt_startevery 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: thenewtratetest was split into complementary halves (one run with a ratchet before the gate for suppression, one withnewt_start=0for admission) so neither depends on a single run producing cycles on both sides; and the fixture'snewtratewas 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. Thenumdecs-reset test picks itsnewt_startat a probe-observed partial fill, then scans for the smallest budget at which the reset and no-reset hypotheses predict differentlrate_capvalues 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 autois 484 passed, 15 skipped, 1 xfailed;ruff check,ruff format --checkandty checkare all clean with zero new diagnostics. The new slow test was run once locally and passes (5.4s), and the repo-wide-m slowrun is 6 passed, 3 skipped, 2 xfailed. CI does run these tests: the macOS Apple-Silicon job installs MLX and executesmlx_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_KEYSextension intest_mlx_backend.pycould not be a literal key extension, because the NumPy reference accumulatesdkappa/dlambdaalready summed over the mixture index withmu^2folded in while MLX (like PyTorch) folds it in at finalization — so the three keys are covered by a newtest_newton_stats_match_numpy_referencethat 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 theshare_comps× Newton interaction and the #267-class broadcast trap are both observable; (3) the sharing-interplay fit test uses the shippedcomp_threshdefault 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 thenan_paramsguard at some seeds in MLX and in float32AMICATorchNG, 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 acceptedposdefhost 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_directionimplies.Review response
All findings from the four-specialist review are addressed. Silent-failure (critical):
fit'snan_paramscheck now coversself.Wandself._logdet_W. They are derived fromAbymx.linalg.inv/slogdet, so a non-finite value can reach the caller whileAis still finite — and on the FINAL iteration nothing else catches it, since there is no next E-step to turn it into anan_llstop; the fit would returnstop_reason="max_iter"with a healthy-lookingfinal_ll_(computed from the previous iteration'sW) and a silently non-finite unmixing matrix._logdet_Wjoined the per-iterationmx.evallist so both reads stay sync-free, andnp.isfinite(W)assertions were added to the three e2e/stability tests.W-guard discrimination evidence (temporary local injection, not committed): injecting
infinto oneWentry on the final iteration givesNon-finite W at iter 3 ... stopping.→stop_reason='nan_params',final_ll_=nan; injecting-infinto_logdet_WgivesNon-finite logdet_W at iter 3→ same. In both states the pre-fixcheckeddict (A/mu/alpha/beta/rho/gm/c/ndtmpsum) was entirely finite, i.e. the old code would have returnedmax_iterwith a corruptW— the exact failure mode confirmed. One correction to the stated rationale: the near-singular-Aroute is not reachable in float32. DrivingAtoward singularity (column duplication at 1e-7…1e-15, or scalingAby 1e-30…1e-38) either leavesmax|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 singularA"raises" — was corrected to record the process-abort behavior.Tests added:
test_newton_inactive_is_bit_identical(the twin oftest_unscheduled_sharing_is_bit_identical:do_newton=Falsevsdo_newton=True, newt_start=10**6, exact equality onA/mu/gm,ll_historyand_ndtmpsum);test_newton_direction_matches_formula(controlled-input pin of the closed form and of MLX'smx.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"whilelrate > minlrate); andtest_newton_fit_is_stable_on_full_dataparametrized over 3 seeds.Comment/doc corrections: the
do_newtondocstring 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→:1323fordgm.unsqueeze(0)(the changelog bullet cites the call without a line number, so it needed no change). The stalecore.py:635-639population-covariance cross-reference now points attorch_impl/core.py:823-827. The per-platformmin_dllbreakdown (326 / 412 / 1076) is not indocs/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 totorch_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_modelsfor a multi-model fit), matching_newton_direction's own docstring, rather than grouping it with the single array-wide dead-model/rho-NaN canaries. Andtest_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_compsscenario: 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