Skip to content

Phase 3: MLX rejection, LLt, export, MIR - #311

Merged
neuromechanist merged 16 commits into
feature/issue-278-epic-mlx-parityfrom
feature/issue-289-phase3-mlx-reject-llt
Sep 1, 2026
Merged

neuromechanist merged 16 commits into
feature/issue-278-epic-mlx-parityfrom
feature/issue-289-phase3-mlx-reject-llt

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

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):

Design decision worth flagging explicitly

do_reject's rejection statistic is read from the LLt stash (_llt_ll indexed by good_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-empts AMICATorchNG's own open follow-up, issue #298, which tracks removing torch's redundant _sample_ll forward pass. The two statistics are mathematically identical (both are the E-step's own per-sample logsumexp), 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_backends fits 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 in docs/guides/amica-differences.md's new "MLX's rejection statistic reads the LLt stash" section.

W-layout note

MLX's W is (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 layout AMICATorchNG's W already has. The adapter therefore does np.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:

  1. CI-breaker: test_mlx_fit_noop.py's git show 2e04006 failed with "bad object" in CI's depth-1 checkout. Fixed: git fetch origin 2e04006 --depth 1 first (tolerating failure), then pytest.skip with a loud shallow-clone-naming reason if the object is still unreachable, instead of letting git show raise.
  2. Cross-backend numerical bug: _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 outliers do_reject had already excluded. Fixed to pass X_use. Confirmed to actually matter: reproduced a 1/32 per-source pdtype mismatch against a float64 torch twin before the fix, 0/32 after; regression test pins the fixed behavior.
  3. Silent degenerate export: write_amica_output had no refusal guard on EITHER backend — a non-finite/degenerate model could be written to disk silently. The AMICA wrapper's usability gate only protects callers going through it; a caller using AMICATorchNG/AMICAMLXNG directly had no gate at all. Added the same two-layer guard state_dict() already has (degenerate stop_reason refusal, then a defense-in-depth isfinite sweep over the parameter arrays, named RuntimeError) 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 (reusing test_mlx_restarts.py's SEEDS=[54,50,42] winner-first fixture), good_idx/numrej/A match a solo fit from the winning seed bit-for-bit.
5. do_reject × share_comps with a GENUINE merge (real-data comp_thresh=0.9 recipe, not a forced/synthetic column): fit completes with finite params, the merged comp_list/comp_used survives, and good_idx has shrunk alongside it.
6. mir_step × auto rank reduction: no behavior change — confirmed torch itself never gates auto-detected reduction upfront either (only explicit pcakeep/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 _preprocess runs; the real reason is torch-parity, not timing), added a clarifying amica-differences.md section, and added the missing test (fit(mir_step=N) on rank-reduced real data completes with a warned, all-NaN mir_history_).

Small:
7. keep_best-inactive reason precedence now matches torch exactly ("do_reject" if self.do_reject else "share_comps") — MLX checked share_comps first; 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-model W[:,:,0]/W[:,:,1] diff (reshaped from the raw on-disk file back to write_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' W differ by ~0.16 in the test fit).
9. Added one paragraph to .rules/testing.md acknowledging 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), which test_mlx_reject.py/test_numpy_reject.py already use for the all-rejected branch.

Deliberately not changed here (per explicit reviewer direction):

  • model_loglik/model_probability on both backends lack a degenerate-fit/finiteness guard and X.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), and model_probability's all-non-finite error message says "-inf log-likelihood" when the same isfinite check 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.
  • The loaded good_idx range/shape validation on from_state_dict/load — independently verified inert, not just taken on faith: every internal read of self.good_idx (_accumulate_blocks, _reject_outliers, _fit_once's X_use/block-tune/reject-statistic lines) is reachable only from inside _fit_once, which unconditionally resets good_idx at 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_ measured 0.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).
  • Cross-backend do_reject agreement: 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 → loadmodout round trip passes for 1- and 2-model fits; single- and 2-model exports were byte-compared against a float64 AMICATorchNG twin 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.
  • Fit-path no-op: a default fit (do_reject off, mir_step=0) is bit-identical, same-process, to the epic tip before this phase (2e04006, loaded live via git show as a sibling module) — test_mlx_fit_noop.py, 3/3 passed, now with a CI-safe shallow-clone fallback.
  • _choose_pdfs do_reject fix: reproduced the pre-fix 1/32 pdtype mismatch, confirmed 0/32 after, against a float64 torch twin.
  • Full suite (the originally required scope): pamica/tests/mlx_tests/ (251 passed) + every test_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 check all clean across the whole repo.
  • The torch-side change (item 3's write_amica_output guard) is verified against every torch test file that exercises write_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 the write_amica_output/state_dict tests (7 passed) after every later commit. A full pamica/tests/torch_tests/ run (beyond the originally required scope, extra diligence since this PR now touches torch_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 passed
  • uv run pytest pamica/tests/test_mlx_*_cross_backend.py -q (all six) — 78 passed
  • uv run pytest pamica/tests/test_restart_policy.py -q — included above (1 pre-existing skip, numpy-backend degenerate-signaling difference, unrelated to this PR)
  • Every torch test file touching write_amica_output/state_dict — 157 passed, 1 skipped (pre-existing), plus a fresh 7-test targeted re-run after every later commit
  • uv run pytest pamica/tests/torch_tests/ -q — full directory (extra diligence, beyond the required scope); kicked off, still running as of this PR update
  • uv run ruff check .
  • uv run ruff format --check .
  • uv run ty check
  • Manual: Lt.sum()/(n_good*nw) == final_ll_ invariant measured in a fresh script
  • Manual: cross-backend reject-set agreement measured in a fresh script
  • Manual: write_amica_output byte-compared against a torch twin's export
  • Manual: _choose_pdfs fix reproduced-then-fixed via a before/after script

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
neuromechanist merged commit a189c73 into feature/issue-278-epic-mlx-parity Sep 1, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-289-phase3-mlx-reject-llt branch September 1, 2026 11:07
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