Repository navigation
Phase 3: MLX rejection, LLt, export, MIR - #311
Merged
neuromechanist merged 16 commits intoSep 1, 2026
Merged
neuromechanist merged 16 commits into
neuromechanist merged 16 commits into
Conversation
Port issue #157's per-block E-step stash (AMICATorchNG) so the LLt export never needs a second forward pass. _get_block_updates emits logV/ll_samples per block, _accumulate_blocks(stash_llt=True) scatters them into _llt_logv/_llt_ll as part of the same lazy graph, and _fit_once materializes them into _llt_lht/_llt_lt after any keep_best restore (which now rolls the stash back with the params). Fixes three test doubles that override _accumulate_blocks to accept the new stash_llt kwarg.
Port issue #123's AMICATorchNG good_idx mechanism: constructor gains do_reject/rejsig/rejstart/rejint/maxrej with torch's names, defaults and validation; _fit_once shrinks good_idx on the reject schedule and restricts the E-step to it; keep_best's track_best now also excludes do_reject. Design decision: the rejection statistic is read FROM the LLt stash (_llt_ll indexed by good_idx) instead of a second forward pass, the NumPy backend's design -- pre-empting AMICATorchNG's open follow-up (#298) to drop its own extra _sample_ll pass. numrej/good_idx persist additively in state_dict's extra (extra.get fallback), the one place phase-1's require-all-extra-keys check is relaxed, documented at both call sites.
Port issue #141's per-model posterior accessors (AMICATorchNG core.py:3041-3132): score arbitrary data through the stored sphere/mean/W via the existing block-wise _forward, returning (n_models, n_samples) Lht, plus the column-softmax model_probability.
Thin adapter over numpy_impl.load.write_amicaout, matching AMICATorchNG.write_amica_output (issue #92): converts mx arrays to numpy, transposes W from MLX's (n_models, n, n) to write_amicaout's (nw, nw, num_models) contract, applies the keep_best LL-truncation so the written LL trajectory ends at the returned iterate, and passes Lht/Lt from the materialized LLt stash (warn-and-omit for a from_state_dict/load model). Verified against a float64 torch twin built from identical fitted parameters: W/A/LL/LLt/comp_list agree to float32 precision (~3e-7) or exactly.
Port issue #137's MIR/PMI accessors (AMICATorchNG core.py:2929-3036) delegating to pamica.metrics: mir() composes get_unmixing_matrix(model_idx) @ sphere, pmi() runs pairwise_mi on transform(). Ports the #300 fitted-geometry PCA guard (sphere.shape[0] != sphere.shape[1]) rather than a config-only check, since this backend has no explicit pcakeep/pcadb parameter. fit(X, mir_step=...) appends (iteration, mir_nats, variance) waypoints to mir_history_ on the given schedule, excluded from the keep_best snapshot and from state_dict (a true trajectory, not a fitted parameter).
Six new mlx_tests files covering the phase's five deliverables plus the fit-path no-op check, and the one new cross-backend file .rules/backend_parity.md calls for: - test_mlx_llt_stash.py: the Lt.sum()/(n_good*nw) == final_ll_ invariant, keep_best stash rollback, LLt omission with no E-step. - test_mlx_reject.py: good_idx schedule, maxrej cap, none/all-rejected edges, keep_best inactive warning, state_dict/save-load round trip and additive-fallback loading of pre-Phase-3 payloads. - test_mlx_export.py: write_amica_output -> loadmodout round trip, do_reject zero-sentinel, from_state_dict LLt omission, no extra forward pass, and a byte-level comparison against a float64 torch twin's export. - test_mlx_scoring.py: model_loglik/model_probability against the E-step's own forward pass and the one-M-step-behind stash. - test_mlx_mir.py: mir/pmi composition, mir_step schedule, the failed- waypoint NaN guard, the #300 PCA-reduction guard on a real rank-reduced fit, and mir_history_'s keep_best/state_dict exclusions. - test_mlx_fit_noop.py: a default fit (do_reject off, mir_step 0) is bit-identical, same process, to the epic tip before this phase (loaded live via git show as a sibling module). - test_mlx_reject_cross_backend.py: MLX and PyTorch reject the SAME sample set from identical config (evidence for the stash-based rejection-statistic design decision), plus mir() numeric agreement against a torch twin.
Update the MLX backend module/package docstrings, docs/api/mlx-backend.md, AGENTS.md, docs/guides/amica-differences.md (backend table, do_reject/LLt/ MIR sections, a new #298 rejection-statistic design-decision section) and .rules/backend_parity.md to reflect that outlier rejection, the LLt stash, the EEGLAB export, and MIR/PMI are now implemented on MLX, closing epic #278. Adds the Unreleased changelog entry.
git show 2e04006 fails with "bad object" in CI's depth-1 checkout, erroring all three no-op tests. Fetch the one commit needed first (tolerating failure), and skip loudly naming the shallow-clone cause if the object is still unreachable, instead of letting git show raise.
_choose_pdfs(X_t) passed the full sphered dataset instead of X_use (the do_reject-restricted good set AMICATorchNG passes), so under pdftype=1 + do_reject the kurtosis-based family decision silently saw the outliers do_reject had already excluded. Fixed to pass X_use. Regression test in test_mlx_reject_cross_backend.py: a pdftype=1, do_reject=True fit's per-source pdtype decision now matches a float64 torch twin bit-for-bit (confirmed to mismatch 1/32 before the fix, 0/32 after).
write_amica_output had no refusal guard on either backend: a degenerate (non-finite-LL) or force-corrupted model could be written silently. state_dict() already refuses via a two-layer guard (degenerate stop_reason, then a defense-in-depth isfinite sweep over the param arrays); add the identical guard to AMICATorchNG.write_amica_output and AMICAMLXNG.write_amica_output. The AMICA wrapper's usability gate only protects callers going through it, so a caller using either backend class directly had no gate at all -- and neither backend has one now missing. This also neutralizes the stale-NaN-stash path: a failed final iteration's LLt stash (from before a nan_params/nan_ll break) can no longer reach disk, since the write is refused before the stash is ever read. Tests: direct-marker degenerate refusal + force-corrupted-param defense-in-depth, one pair per backend (torch: test_ng_backend.py; MLX: test_mlx_export.py, NaN-injection recipe matching test_mlx_persistence.py's existing state_dict test).
Two interaction regression tests (PR #311 review), both verified to hold before being pinned: - do_reject x n_restarts: with the winning seed forced to NOT be the last restart (SEEDS=[54,50,42], test_mlx_restarts.py's existing winner-first fixture), good_idx/numrej/A match a solo fit from the winning seed bit-for-bit -- the restore path (_apply_restart_state) is what a last-restart winner would leave untested. - do_reject x share_comps: comp_thresh=0.9 (test_mlx_sharing.py's real-data recipe for a genuine, non-forced merge) combined with a do_reject schedule that also fires in the same fit. Asserts finite params, the merged comp_list/comp_used surviving, and good_idx shrunk alongside it.
PR #311 review: no behavior change. The mir_step docstring's "cannot be known before _preprocess" framing was misleading -- the sphere's shape IS knowable right after _preprocess runs, a few lines later. The real reason there is no upfront gate for automatic mineig/mineig_rel reduction is torch-parity: AMICATorchNG's own upfront gate only ever covers an explicit pcakeep/pcadb request (issue #300's deliberate scope), never the automatic case, which both backends only catch downstream, per-waypoint, inside mir()'s own #300 geometry guard. Reworded the docstring and added a clarifying section to amica-differences.md. Adds the missing test: fit(mir_step=N) on rank-reduced real data (SVD projection) completes normally, with every waypoint recorded as a warned (iter, NaN, NaN) entry.
MLX checked share_comps before do_reject when reporting why keep_best is inactive; AMICATorchNG checks do_reject first (torch_impl/core.py:2425). When both flags are on the two backends must report the same reason for the same configuration. Swapped to match, and pinned with a test where both are enabled simultaneously.
PR #311 review: parametrize the single-model-only byte comparison to also cover n_models=2, and add an explicit per-model W diff (reshape the raw file back to write_amicaout's own (nw, nw, num_models) contract and compare model 0 and model 1 slices separately) so a per-model swap or a wrong axis in the (n_models, n, n) -> (n, n, num_models) transpose shows up as a named model index, not just "W differs somewhere" in the aggregate flat-byte check. Confirmed non-vacuous: the two models' W differ by ~0.16 in this fit.
PR #311 review: test_mlx_reject.py and test_numpy_reject.py already use a lighter variant of the sanctioned error-injection pattern -- calling _reject_outliers directly on a hand-built ll_vec, rather than a subclass, to reach the all-rejected branch a real fit can never organically trigger. Acknowledge it explicitly alongside the subclass form.
Amends the Phase 3 Unreleased entry to note the degenerate/non-finite refusal guard added to write_amica_output on both backends (PR #311 review, item 3).
neuromechanist
merged commit Sep 1, 2026
a189c73
into
feature/issue-278-epic-mlx-parity
8 checks passed
This was referenced Sep 1, 2026
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
Closes #289. Part of epic #278 (final phase; closes the epic's MLX-parity work once merged).
Ports the five remaining
AMICATorchNG-only capabilities to the MLX backend (AMICAMLXNG):_get_block_updatesemits per-blocklogV/ll_samples;_accumulate_blocks(stash_llt=True)scatters them into_llt_logv/_llt_llas part of the same lazy MLX graph (never a second forward pass);_fit_oncematerializes them into_llt_lht/_llt_ltafter anykeep_bestrestore, and_snapshot_params/_restore_paramsnow roll the stash back with the parameters.do_reject(issue numpy_impl: do_reject outlier rejection is non-functional (data_mask never initialized/consumed) #123'sgood_idxmechanism): same constructor names/defaults/validation asAMICATorchNG(rejsig=3.0,rejstart=2,rejint=3,maxrej=1).track_bestnow also excludesdo_reject.numrej/good_idxpersist additively instate_dict()'sextra(the one place phase-1's require-all-extra-keys check is relaxed, viaextra.get()fallback).model_loglik/model_probability(issue Phase 2: multi-model exposure for MNE users #141): score arbitrary data through the stored sphere/mean/W via the existing block-wise_forward.write_amica_output(issue Drop-in EEGLAB AMICA replacement: equivalent output, no extra interpretation #92): thin adapter overnumpy_impl.load.write_amicaout, transposing MLX'sWfrom(n_models, n, n)to the writer's(nw, nw, num_models)contract, applying thekeep_bestLL-truncation, and passingLht/Ltfrom the materialized stash (warn-and-omit for afrom_state_dict/loadmodel).mir/pmi(issue Phase 5: wire MIR/PMI into the AMICA API #137) delegating topamica.metrics, plusfit(mir_step=...)waypoints intomir_history_(excluded from both thekeep_bestsnapshot andstate_dict), and the Derive mir PCA guard from fitted geometry #300 fitted-geometry PCA guard (sphere.shape[0] != sphere.shape[1]).Design decision worth flagging explicitly
do_reject's rejection statistic is read from the LLt stash (_llt_llindexed bygood_idx) rather than a second forward pass over the good set. This is the NumPy backend's existing design (_last_ll_samples, itself read from its own stash) — and it pre-emptsAMICATorchNG's own open follow-up, issue #298, which tracks removing torch's redundant_sample_llforward pass. The two statistics are mathematically identical (both are the E-step's own per-samplelogsumexp), so this is a WORK divergence, not a numeric one: MLX simply never had the redundant pass to begin with. Verified directly —test_mlx_reject_cross_backend.py::test_reject_same_sample_set_across_backendsfits MLX and PyTorch from identical seed/data/config and confirms they reject the exact same sample indices (measured identical at rejsig in {2.0, 2.5, 3.0}, single- and 2-model; the shipped test uses rejsig=2.0 for a clear margin, not a borderline threshold). Documented indocs/guides/amica-differences.md's new "MLX's rejection statistic reads the LLt stash" section.W-layout note
MLX's
Wis(n_models, n, n)(model-major);write_amicaout's contract (read from its actual signature/docstring, not guessed) is(nw, nw, num_models)— the same layoutAMICATorchNG'sWalready has. The adapter therefore doesnp.array(self.W).transpose(1, 2, 0).Review fixes (round 2)
Three PR reviews came back with a consolidated fix list; all addressed here, same worktree, atomic commits:
Blocking:
test_mlx_fit_noop.py'sgit show 2e04006failed with "bad object" in CI's depth-1 checkout. Fixed:git fetch origin 2e04006 --depth 1first (tolerating failure), thenpytest.skipwith a loud shallow-clone-naming reason if the object is still unreachable, instead of lettinggit showraise._choose_pdfs(X_t)passed the FULL sphered dataset instead ofX_use(the do_reject-restricted good setAMICATorchNGpasses), so underpdftype=1 + do_rejectthe kurtosis-based family decision silently saw outliers do_reject had already excluded. Fixed to passX_use. Confirmed to actually matter: reproduced a 1/32 per-sourcepdtypemismatch against a float64 torch twin before the fix, 0/32 after; regression test pins the fixed behavior.write_amica_outputhad no refusal guard on EITHER backend — a non-finite/degenerate model could be written to disk silently. TheAMICAwrapper's usability gate only protects callers going through it; a caller usingAMICATorchNG/AMICAMLXNGdirectly had no gate at all. Added the same two-layer guardstate_dict()already has (degeneratestop_reasonrefusal, then a defense-in-depth isfinite sweep over the parameter arrays, namedRuntimeError) to both backends'write_amica_output, with a refusal + a defense-in-depth test per backend. This also neutralizes the stale-NaN-stash path: a failed final iteration's stash can no longer reach disk, since the write is refused before the stash is ever read.Important tests (all newly added, all verified to hold before being pinned):
4.
do_reject×n_restarts: with the winning seed forced to NOT be the last restart (reusingtest_mlx_restarts.py'sSEEDS=[54,50,42]winner-first fixture),good_idx/numrej/Amatch a solo fit from the winning seed bit-for-bit.5.
do_reject×share_compswith a GENUINE merge (real-datacomp_thresh=0.9recipe, not a forced/synthetic column): fit completes with finite params, the mergedcomp_list/comp_usedsurvives, andgood_idxhas shrunk alongside it.6.
mir_step× auto rank reduction: no behavior change — confirmed torch itself never gates auto-detected reduction upfront either (only explicitpcakeep/pcadb, issue #300's deliberate scope), so MLX's warn+NaN-waypoint behavior already matched. Fixed the docstring's misleading "cannot be known before_preprocess" justification (the sphere shape IS knowable right after_preprocessruns; the real reason is torch-parity, not timing), added a clarifyingamica-differences.mdsection, and added the missing test (fit(mir_step=N)on rank-reduced real data completes with a warned, all-NaNmir_history_).Small:
7.
keep_best-inactive reason precedence now matches torch exactly ("do_reject" if self.do_reject else "share_comps") — MLX checkedshare_compsfirst; pinned with a test where both flags are on simultaneously.8. Extended the torch-twin export byte comparison to
n_models=2, with an explicit per-modelW[:,:,0]/W[:,:,1]diff (reshaped from the raw on-disk file back towrite_amicaout's own contract) — pins the(n_models,n,n) -> (n,n,num_models)transpose on a meaningful axis, not just aggregate flat bytes. Confirmed non-vacuous (the two models'Wdiffer by ~0.16 in the test fit).9. Added one paragraph to
.rules/testing.mdacknowledging the direct-call variant of the sanctioned injection pattern (calling the real method on a hand-built input for an organically unreachable edge — no subclass needed), whichtest_mlx_reject.py/test_numpy_reject.pyalready use for the all-rejected branch.Deliberately not changed here (per explicit reviewer direction):
model_loglik/model_probabilityon both backends lack a degenerate-fit/finiteness guard andX.ndim/X.shape[0]input validation (the same anti-pattern issue Guard raw-backend accessors on degenerate fits and bad transform input #306 already tracks for the other accessors), andmodel_probability's all-non-finite error message says "-inf log-likelihood" when the sameisfinitecheck equally fires on NaN, misdiagnosing the cause. Both are now folded into issue Guard raw-backend accessors on degenerate fits and bad transform input #306's scope (see its new comment) rather than fixed piecemeal here, so the fix lands as one cross-backend PR for the whole family, per.rules/backend_parity.md.good_idxrange/shape validation onfrom_state_dict/load— independently verified inert, not just taken on faith: every internal read ofself.good_idx(_accumulate_blocks,_reject_outliers,_fit_once'sX_use/block-tune/reject-statistic lines) is reachable only from inside_fit_once, which unconditionally resetsgood_idxat its top (self.good_idx = mx.arange(n_total) if self.do_reject else None) before any of them run. A stale or out-of-range value from a hand-edited payload can therefore only ever be observed via a direct attribute read on a freshly-loaded, not-yet-refit model -- never by any internal code path.Verification
Lt.sum()/(n_good*nw) - final_ll_measured0.0(n_models=2, seed=42, max_iter=8, 4096 samples) in-process; other configs measured ~1e-9–1e-7 (float32 summation noise) and ~0.011 under a rejection-on-the-last-iteration config (matching the reference-faithful residual documented for the array backends).do_rejectagreement: same config (seed=7, rejsig=2.0, rejstart=2, rejint=3, maxrej=2, max_iter=10, 4096 samples) — MLX and PyTorch both reject exactly 350/4096 samples, identical index sets.write_amica_output→loadmodoutround trip passes for 1- and 2-model fits; single- and 2-model exports were byte-compared against a float64AMICATorchNGtwin built from identical fitted parameters (gm,W— including per-model slices,S,mean,c,alpha,mu,sbeta,rho,LL,A,LLt,comp_list) — agreement to float32 precision (~1e-7) or exact.do_rejectoff,mir_step=0) is bit-identical, same-process, to the epic tip before this phase (2e04006, loaded live viagit showas a sibling module) —test_mlx_fit_noop.py, 3/3 passed, now with a CI-safe shallow-clone fallback._choose_pdfsdo_reject fix: reproduced the pre-fix 1/32pdtypemismatch, confirmed 0/32 after, against a float64 torch twin.pamica/tests/mlx_tests/(251 passed) + everytest_mlx_*_cross_backend.py+test_restart_policy.py(78 passed, 1 skipped, pre-existing/unrelated) = 329 passed, 1 skipped.ruff check,ruff format --check,ty checkall clean across the whole repo.write_amica_outputguard) is verified against every torch test file that exerciseswrite_amica_output/state_dict:test_ng_backend.py+test_amica_ng_wrapper.py+test_llt_stash.py+test_amicaout_reduced.py+test_ng_convergence.py+test_viz.py= 157 passed, 1 skipped (pre-existing/unrelated), plus a fresh targeted re-run of just thewrite_amica_output/state_dicttests (7 passed) after every later commit. A fullpamica/tests/torch_tests/run (beyond the originally required scope, extra diligence since this PR now touchestorch_impl/core.py) was also kicked off; if it hasn't finished by review time I'll post its result separately.Test plan
uv run pytest pamica/tests/mlx_tests/ -q— 251 passeduv run pytest pamica/tests/test_mlx_*_cross_backend.py -q(all six) — 78 passeduv run pytest pamica/tests/test_restart_policy.py -q— included above (1 pre-existing skip, numpy-backend degenerate-signaling difference, unrelated to this PR)write_amica_output/state_dict— 157 passed, 1 skipped (pre-existing), plus a fresh 7-test targeted re-run after every later commituv run pytest pamica/tests/torch_tests/ -q— full directory (extra diligence, beyond the required scope); kicked off, still running as of this PR updateuv run ruff check .uv run ruff format --check .uv run ty checkLt.sum()/(n_good*nw) == final_ll_invariant measured in a fresh scriptwrite_amica_outputbyte-compared against a torch twin's export_choose_pdfsfix reproduced-then-fixed via a before/after script