Skip to content

Epic: MLX backend non-fitting parity - #318

Merged
neuromechanist merged 23 commits into
devfrom
feature/issue-278-epic-mlx-parity
Sep 1, 2026
Merged

neuromechanist merged 23 commits into
devfrom
feature/issue-278-epic-mlx-parity

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

Closes #278.

Brings AMICAMLXNG from fitting-only parity to the full torch-equivalent surface. Every phase PR was individually planned, implemented, multi-agent reviewed, and squash-merged into this branch; this final merge is a regular merge commit to preserve the per-phase history per the epic workflow.

Phases completed

  1. Transform and save/load — Phase 1: MLX transform and save/load #287, PR Phase 1: MLX transform and save/load #305: transform, mixing/unmixing/sensor-map accessors, get_rho, n_channels_in, state_dict/from_state_dict, hardened single-file .npz save/load. Transform agrees with a float64 torch twin to 2.98e-07 (max-norm); round trips are bit-identical.
  2. keep_best — Phase 2: MLX keep_best #288, PR Phase 2: MLX keep_best #310: the Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51 best-iterate safeguard with torch's exact snapshot/restore semantics; the no-rescue-of-diverged-fits guard pinned in both backends.
  3. Rejection, LLt, export, MIR — Phase 3: MLX outlier rejection and LLt/MIR #289, PR Phase 3: MLX rejection, LLt, export, MIR #311: do_reject with the rejection statistic served from the LLt stash (the design open issue Serve torch do_reject rejection statistic from the LLt stash #298 records as torch's destination; cross-backend rejection sets verified identical at 350/4096), the Fortran-faithful LLt stash with keep_best rollback, model_loglik/model_probability, EEGLAB write_amica_output (byte-compared against a torch twin, now guarded on BOTH backends against exporting degenerate models), and MIR/PMI. Review also caught and fixed a real cross-backend bug: the pdftype=1 switcher seeing unrejected samples under do_reject.
  4. Audit polish — PR Epic polish: audit fixes #316: a three-lens feature-parity audit (backend surface, Fortran coverage, integration) drove the variance_order port (the one genuine remaining gap), doc corrections, and the future-work ledger below.

Final review round (four deep reviewers on this PR's full diff)

Critical fixes:

  • C1 — exception-state consistency (both backends). Every mid-loop invariant raise (MLX's MLX linalg failure aborts the process instead of raising #274 singular-unmixing guard, _choose_pdfs's invariant, _pinv_sphere's non-finite guard; torch's _update_unmixing_matrix LinAlgError and its own _pinv_sphere guard) now sets self.stop_reason = restarts.ERROR_STOP_REASON before raising, so an instance that survives a caught raise (e.g. under best-of-N restarts) is left provably degenerate rather than at a stale healthy stop_reason. Sabotage-verified: reverting the fix and re-running the new regression test fails with AssertionError: assert 'max_iter' == 'restart_error', confirming the test would have caught the original bug.
  • C2 — stale _logdet_W/_lgamma_table after a keep_best restore (MLX, default config). _restore_params rolled back W/rho but left the two derived caches at the discarded iterate's values, so a restored model's own log-likelihood was silently wrong. Fixed by adding both to the restart snapshot (rebuilt alongside every other parameter, rather than a separate post-restore recompute step a future caller could forget). Regression test demonstrates the bug directly: a forced-restore fit's model_loglik disagreed with the same model's state_dict/from_state_dict round trip by max abs diff 0.3804016 before the fix, 0.0 after.

Important fixes:

  • MIR waypoint flood (both backends): after the first ValueError, one warning fires and further waypoints are skipped for the rest of the fit; a LinAlgError (near-singular unmixing, genuinely transient) still records a per-waypoint NaN and keeps trying.
  • MLX _load_params: the isfinite validation that already covered comp_list/pdtype now covers all 10 float _PARAM_ARRAYS, named per-array.
  • max_iter >= 1 is now validated at fit entry on all three backends — torch and MLX as a fit()-time check (matching their max_iter fit parameter), NumPy as a fit()-time re-check of self.max_iter (already validated at construction, but reassignable afterward, so fit() re-validates too).
  • MLX loader: good_idx/numrej restoration now raises the same named "malformed AMICAMLXNG state: ..." error on a bad payload, instead of a raw int()/asarray exception.

New tests:

  • MIR × best-of-N restarts, winner not last (mirrors the existing do_reject version) — confirms mir_history_ round-trips through the restart snapshot/restore path correctly.
  • One kitchen-sink lifecycle test (test_mlx_kitchen_sink.py): n_models=2, a forced share_comps merge, do_reject, n_restarts=2, and pdftype=1 together on one fit, walking every accessor, state_dict/from_state_dict, .npz save/load, and write_amica_output/loadmodout — including confirming keep_best=True is accepted but logged inactive under the combined exclusion.
  • share_comps × export (genuine merge, then write_amica_output/loadmodout round trip) and share_comps × mir() on a merged model.
  • test_mlx_fit_noop's bit-identical-parameter comparison now covers all 12 _PARAM_ARRAYS (previously missing mean/sphere/pdtype), so the module docstring's "every fitted array" claim is literally true.
  • Fallout from the max_iter>=1 fix: two pre-existing tests (test_llt_stash.py and its MLX twin) reached their "no E-step ran" state via fit(max_iter=0), which the new guard now rejects before that state is reachable. Rewritten to check the same construction-time invariant directly; the write_amica_output-omits-LLt behavior they also covered is already exercised elsewhere (test_from_state_dict_write_amica_output_omits_llt / test_from_state_dict_model_warns_and_omits_llt).

Doc/citation fixes: four stale "epic complete as of Phase 3" claims now name the post-Phase-3 polish round and variance_order (mlx_impl/__init__.py, .rules/backend_parity.md, docs/changelog.md, AGENTS.md, docs/api/mlx-backend.md); a changelog note about do_reject joining the keep_best exclusion updated from future to past tense; several stale torch_impl/core.py line-number citations in mlx core.py recomputed against the current file, including two digamma citations that pointed at the wrong code entirely; docs/guides/validation.md now says rejection is 3-backend and correctly attributes the degenerate-fit refusal on transform/get_*/save to the AMICA wrapper (raw-backend gap tracked as #306), noting write_amica_output is the one accessor that gained its own raw-backend guard directly; .rules/testing.md documents the call-counting-spy test pattern; ADR 0003 gets a one-line addendum noting the safeguard now also covers AMICAMLXNG.

Deliberately not addressed in this PR (tracked separately, none blocking):

Remaining gaps, all recorded as issues (none blocking)

Test plan

  • Each phase PR: full mlx_tests + cross-backend suites + review-driven additions, all green in CI (including the Apple Silicon job).
  • Final review round: full mlx_tests (288 collected, 287 passed / 1 skipped), all six cross-backend files (42 passed), full torch_tests + test_restart_policy (308 collected, 302 passed / 6 skipped), test_llt_stash.py/test_pamica.py, and the touched NumPy suites — all green, zero failures. ruff check/ruff format --check/ty check clean across the whole project.
  • A deep integration-level review of this PR's full diff runs before merge.

* Add transform and mixing accessors to AMICAMLXNG

Ports AMICATorchNG.transform plus get_mixing_matrix/
get_unmixing_matrix/get_sensor_mixing_matrix/get_rho to the MLX
backend (issue #287, epic #278 Phase 1). transform derives the
unmixing composition from MLX's own _forward rather than
transcribing torch's tensor layout: MLX's W is (n_models, n, n),
not torch's (n, n, n_models). Fitting is untouched.

* Add state_dict/save/load persistence to AMICAMLXNG

state_dict/from_state_dict mirror AMICATorchNG's 12-name param set
and refusal guards (unfitted, degenerate, non-finite); save/load
write a single device- and framework-agnostic .npz (config/extra as
JSON-encoded scalars, params as native arrays -- no torch coupling,
no pickle). Loading rebuilds the MLX-only per-iteration caches
(lgamma table, log|det W|, comp_used) that AMICATorchNG instead
recomputes inline on every call.

* Add MLX transform tests

MLX-only mechanics for issue #287: model_idx validation, unfitted
errors, and transform(training X) reproducing the fit's own
E-step activations via the transpose identity _forward relies on.
Includes the fit-path no-op pin (C7): a short seeded fit is
bit-identical to a recorded run from the epic branch tip, proving
this phase touched nothing _fit_once calls.

* Add MLX transform cross-backend tests

Pins transform and the get_mixing_matrix/get_unmixing_matrix/
get_sensor_mixing_matrix/get_rho accessors against a float64
AMICATorchNG twin holding identical fitted parameters, following
the existing test_mlx_newton_cross_backend.py pattern. Covers
multi-model model_idx routing with nonzero c, and a genuinely
rank-reduced fit for get_sensor_mixing_matrix.

* Add MLX persistence tests

Round trip (state_dict/from_state_dict and .npz save/load): every
param bit-identical, config/extra equal, transform output
bit-identical pre/post. Sharing and adaptive-switcher state round
trip (forced merge, pdftype=1). Refusal guards: unfitted,
degenerate, wrong format_version, missing sections, shape drift.

* Document MLX transform and persistence support

Update the AMICAMLXNG module docstring, docs/api/mlx-backend.md,
docs/guides/amica-differences.md's backend table, AGENTS.md's MLX
status sentence and the changelog to reflect issue #287 (epic #278
Phase 1): transform/accessors/save-load are no longer "fast-follow"
gaps. Remaining gaps are keep_best (Phase 2) and outlier rejection
+ LLt/MIR (Phase 3).

* Persist n_newton_fallbacks in AMICAMLXNG state_dict

Plan enumeration for extra omitted this field (an oversight, not a
deliberate divergence -- torch's equivalent extra dict includes
it); a reloaded model was silently losing the Newton-fallback
counter. Round-trip test drives a genuine nonzero count via a
deliberately under-determined 256-sample block (same construction
as test_mlx_newton.py::test_fallback_ramps_toward_lrate_cap_and_counts)
through both state_dict/from_state_dict and .npz save/load.

* Harden AMICAMLXNG persistence load path

PR review on #305 found the load path under-validated:
- _load_params shape-checked only A/comp_list; extend to all 12
  _PARAM_ARRAYS against an expectation table read off
  _initialize_parameters's real allocations. sphere's input-channel
  width isn't derivable from config under rank reduction, so it's
  taken from the restored sphere itself and mean is cross-checked
  against it.
- comp_list/pdtype no longer force-cast unconditionally: a float
  array with NaN or a fractional value is numpy UB once cast to an
  index dtype. _safe_int_cast requires the value already be integer,
  or finite and whole, before casting; corrects the "dtype
  preserved" docstring claim (it force-casts).
- load() wraps the npz read so a byte-truncated or otherwise corrupt
  file (zipfile.BadZipFile/EOFError/OSError/ValueError) re-raises as
  the same named "malformed AMICAMLXNG save file" error instead of
  an opaque exception.
- extra now requires all 14 keys (format_version 1 has no older
  files to be lenient for), mirroring the params completeness check,
  instead of 10 keys raising bare KeyError and 3 silently
  defaulting to [].
- W recomputes log|det W| on load; a finite-but-singular restored W
  makes slogdet return -inf rather than raise, so that's checked
  explicitly.
- Dropped the dead _INT_PARAM_ARRAYS tuple (only _INT_PARAM_DTYPES
  is read).

Also adds AMICAMLXNG.n_channels_in (port of AMICATorchNG's property),
so a reloaded rank-reduced model can still report its original input
width, and corrects the stale "this backend has no load path" comment
on _sphere_np now that _load_params is a second sphere-assignment
point.

* Fix stale MLX backend-parity example in rules doc

.rules/backend_parity.md's "existing legitimate examples" sentence
still said transform raised NotImplementedError and save/load was
absent; both landed in epic #278 Phase 1 (#287). Names only the
genuinely still-absent items: do_reject, keep_best, LLt/MIR
(Phases 2/3).

* Add persistence hardening and review-requested test coverage

Covers the PR #305 review fixes:
- shape-drift rejection for every param (not just A/comp_list),
  including mean's sphere-derived n_channels_in cross-check
- comp_list dtype safety: rejects NaN and fractional values, accepts
  whole-valued float arrays
- singular restored W is rejected (a whole zeroed column reliably
  reaches slogdet's -inf; a duplicated column on an already
  float32-rounded W does not -- documented in the test)
- a real byte-truncated (not just well-formed-npz-missing-a-key)
  .npz raises the same named error
- get_rho() and state_dict() defense-in-depth: a force-set
  non-finite rho/param (clean stop_reason) is caught and named
- n_channels_in round trips on a rank-reduced fit
- rank-reduced save/load round trip: all 12 params + transform
  bit-identical through both state_dict and .npz
- n_restarts=3 round trip: restart_seeds_/restart_lls_/
  restart_stop_reasons_ keep their full per-restart length/content,
  not a vacuous length-1 list
- cross-backend accessor test: documents why get_unmixing_matrix
  alone needs the looser 1e-3 bound (independent per-backend matrix
  inversion, not a pure reindex/transpose like mixing/rho)

* Make fit-path no-op pin survive cross-GPU float32 noise

CI failed on a different Apple GPU model: MLX float32 is
bit-reproducible on one machine but not across GPU models
(observed: ll_history[0] differs from the M4 Pro recording by
~7e-8 relative). Reshape the pin instead of deleting it:

- ll_history/final_ll_ now compared per-entry within 5e-6 relative
  (~50x the observed ~1e-7 cross-GPU spread, below the ~1e-6+ shift
  a genuine fit-path change produces -- see #216's block_size
  precedent) instead of exact equality.
- Drop the SHA-256 A/W hashes (a cross-machine hash can never
  match); replace with the same 5e-6 tolerance on five
  representative A entries.
- stop_reason and len(ll_history) stay exact -- machine-independent.
- Docstring now says plainly that the bit-level no-op claim was
  verified same-machine at development time (epic tip 076605c,
  before/after, bit-identical there); this test is the looser
  cross-machine canary.

* Scale the A-entry no-op spot checks by matrix max, not per-entry

CI failed again: A[10, 20] is small (-0.0037), so the per-entry
5e-6 relative bound from the previous fix was an absolute tolerance
of ~1.9e-8 there -- tighter than the ~1.1e-7 cross-GPU float32
noise CI actually observed. Same near-zero-entry failure mode
_max_rel_disagreement's docstring in
test_mlx_transform_cross_backend.py already explains for
transform's output; apply the same fix here. The five A spot
entries are now compared against a recorded max(|A|) (~1.0, A
columns are ~unit-normalized) instead of against each entry's own
magnitude. ll_history/final_ll_ keep the per-entry relative check
(safe: their magnitude, ~3.3, stays well clear of zero).
* Add keep_best best-iterate safeguard to MLX backend

Ports #51's snapshot/restore mechanism from AMICATorchNG onto
AMICAMLXNG: fit() tracks the highest-LL iterate and restores it when
the run ends more than _KEEP_BEST_TOL below that peak. Inactive under
share_comps (a merge changes the parameter count, so an earlier
snapshot cannot be reverted to without undoing it). Persisted
additively in state_dict's config; ll_history is never rewritten.

Epic #278 Phase 2, issue #288.

* Add keep_best tests for MLX backend

Covers the monotone no-op pin, a genuine forced-restore overshoot
(measured, not assumed), ll_history immutability, bit-identical
truncated-refit comparison, n_kurt_done/pdtype consistency under
pdftype=1, the share_comps disable, and state_dict persistence
(including additive-compat for a payload missing the key). All
bit-identity checks run within a single test process to stay safe
against MLX's cross-GPU float32 non-reproducibility.

A cross-backend companion asserts the shared restore CONTRACT
(final_ll_ == max(ll_history) when active) without asserting decision
equality between PyTorch's float64 and MLX's float32 trajectories.

Epic #278 Phase 2, issue #288.

* Document MLX keep_best in the backend-parity docs

Backend table, gaps sentences (AGENTS.md, mlx-backend.md,
backend_parity.md) and changelog now reflect keep_best as
implemented on MLX; the remaining MLX gap is do_reject + LLt/MIR
(Phase 3).

Epic #278 Phase 2, issue #288.

* Test the degenerate-stop guard and restart record

PR #310 review additions: the restore guard's refusal to rescue a
diverged fit that peaked earlier is now pinned in both the MLX and
torch backends via the sanctioned error-injection subclass (real
iterations, then a forced nan_ll, asserting no restore and bit-
identity with keep_best=False); and the keep_best x n_restarts
composition is pinned (restart_lls_ reports the restored iterate,
bit-identical to a standalone fit's final_ll_). The grad_norm-stop
recipe variant is deliberately skipped: the guard is a set-membership
test on stop_reason, so nan_ll alone covers the branch. Tested:
13 keepbest tests + torch twin pass; ruff and ty clean.
* Add LLt stash to the MLX backend

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.

* Add do_reject outlier rejection to the MLX backend

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.

* Add model_loglik/model_probability to the MLX backend

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.

* Add write_amica_output EEGLAB export to the MLX backend

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.

* Add mir/pmi diagnostics to the MLX backend

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

* Add tests for MLX reject/LLt/export/scoring/mir/no-op

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.

* Document epic #278 Phase 3: MLX gaps closed

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.

* Fix test_mlx_fit_noop.py for shallow CI checkouts

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.

* Fix _choose_pdfs to use the do_reject good set on MLX

_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).

* Guard write_amica_output against degenerate/non-finite models

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

* Pin do_reject through best-of-N restarts and share_comps

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.

* Fix mir_step docstring and document the auto-rank-reduction parity

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.

* Match torch's keep_best-inactive reason precedence exactly

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.

* Extend the torch-twin export byte comparison to n_models=2

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.

* Document the direct-call injection-pattern variant in testing.md

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.

* Mention the write_amica_output guard in the changelog

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).
* Attribute degenerate-fit refusal to AMICA wrapper

Row 5 of the differences table credited the raw PyTorch backend with
refusing transform/get_*/save on a degenerate fit; that guard is the
AMICA wrapper's _check_usable contract. The raw AMICATorchNG backend
has no such guard of its own (tracked as issue #306).

* Document unmapped Fortran keywords

Add a section resolving the page's exhaustiveness contract: points to
fortran_params.py's FORTRAN_UNSUPPORTED_KEYS as the enumeration, names
filter_length/dft_length/decwindow as dead in the reference itself
(alongside the already-documented do_choose_pdfs/Spinv2 dead code),
and records the do_rho-vs-pdftype divergence: Fortran can freeze the
GG shape while keeping pdftype=0, but every pamica backend derives
the freeze from pdftype directly, making that combination unreachable.
Links issues #312/#314 for the live lifecycle/diagnostics gaps.

* Port variance_order to AMICAMLXNG

Adds the EEGLAB back-projected-variance component order (issue #92)
to the MLX backend, mirroring AMICATorchNG.variance_order with MLX's
model-major W layout ((n_models, n, n)) and the unfitted RuntimeError.
Closes the one accessor gap the epic's feature-parity audit found in
an otherwise-complete Phase 3; updates the module docstring's
ported-features claim to match.

Adds cross-backend parity coverage against a float64 AMICATorchNG
twin holding identical fitted parameters (order matches exactly on a
30-iteration multi-model fit with non-degenerate variance gaps, with
a gap-size assertion documenting the tie risk), plus MLX-only
unfitted/invalid-model_idx/permutation tests.

* Correct validation harness backend coverage claim

AGENTS.md claimed the harness runs "both implementations (NG +
NumPy)"; validate_implementations.py only exercises torch vs Fortran.
NumPy parity lives in pytest (test_sample_data_numpy_vs_fortran); MLX
validation lives in mlx_tests/ plus the cross-backend suites.
Extending the harness itself is tracked as issue #315.

* Fix unsupported-key comment for writestep/do_history

The FORTRAN_UNSUPPORTED_KEYS entries for writestep/do_history/
histstep said these have no pamica equivalent; false for the legacy
NumPy backend, which implements all three (numpy_impl/core.py's fit
loop and _write_history). Keeps the keys unsupported here (this
module targets the torch wrapper, which has no matching mechanism)
but corrects the reason: NumPy-only, torch/MLX gap tracked as #312.

* Refresh stale feature-parity status notes

feature_parity.md and progress_summary.md still claimed the runtime-
vs-Fortran benchmark was unmeasured and issue #15 (save/load and
plot_components test coverage) was open; both landed since. Also
corrects progress_summary.md's validation-harness claim (same fix as
AGENTS.md: torch-vs-Fortran only, not NG + NumPy). Adds a header note
to feature_parity.md pointing to amica-differences.md's table as the
live, maintained backend-parity source of truth.

* Align NumPy backend's inert pdftype default to 0

self.pdftype is never read after assignment (this backend always
runs the GG update; _compute_log_pdf takes no pdftype param), so the
old default of 1 was a harmless but confusing mismatch against
torch/MLX's constructor default of 0. Aligned for surface consistency
only; no behavior change.

* Add changelog entry for epic polish round

Summarizes the audit-driven fixes ahead of merge to dev: MLX
variance_order, the doc corrections, and the new tracking issues
(#312, #314, #315) plus the #306 extension.

* Scope variance_order precision claim to defaults
A RuntimeError from inside _fit_once's iteration body (the #274
condition-number guard, _choose_pdfs's pdtype invariant, and
_pinv_sphere's non-finite-sphere guard on MLX; _update_unmixing_
matrices's torch.linalg.inv failure and _pinv_sphere's guard on
torch) fires AFTER that iteration's _update_parameters already
reassigned A/mu/beta/rho/alpha/gm/c, but BEFORE W/_logdet_W are
updated. stop_reason stayed "max_iter", so a caller of the
single-restart fit() path (no try/except there) that catches the
propagated exception and persists the model anyway would have every
state_dict()/write_amica_output() degenerate-fit guard accept it
silently.

Set self.stop_reason = restarts.ERROR_STOP_REASON immediately before
each raise, so the instance itself -- not just the exception -- is
left degenerate regardless of whether the caller catches it. The
multi-restart path's own except block already did this; kept as
redundant-but-harmless so it does not depend on every raise site
doing this correctly.

Tests (both backends): a sanctioned injection subclass runs a real
fit for N genuine iterations, then forces the target guard's raise
on a later iteration -- confirmed to fail without the fix (stop_reason
stayed "max_iter") and pass with it, and that state_dict/
write_amica_output then refuse the resulting instance. Plus
direct-call coverage for the two guards not reachable via a real
fit trajectory.
_snapshot_params/_restore_params rolled back W/rho/etc via
_PARAM_ARRAYS, but the two MLX-only per-iteration caches
(_logdet_W, feeding log|det W| into every logV; _lgamma_table,
feeding the GG log-density) were never captured -- so a restore left
them at the LAST (discarded) iterate's values, silently corrupting
model_loglik/model_probability/mir on the "restored" model even
though W/rho themselves rolled back correctly.

Added both to the snapshot dict (captured unconditionally, since
both always exist once _initialize_parameters has run) rather than
rebuilding them post-restore the way _load_params does: it keeps the
snapshot a single self-contained point-in-time capture with nothing
a future _restore_params caller could forget, and _restore_params's
existing generic setattr loop handles them with no extra code at the
call site. Both are already in _RESTART_STATE_ATTRS.

Regression test (forced-restore recipe, oracle = a state_dict round
trip, which independently rebuilds both caches from the restored
W/rho): measured max_diff = 0.3804 (100% of 8192 elements, up to
~0.43% relative error) before the fix, 0.0 (bit-exact) after.
mir()'s ValueError (PCA reduction, or metrics.mir's own near-singular
-unmixing check) reflects the fit's geometry -- a fact that does not
spontaneously resolve mid-fit -- so every remaining scheduled
waypoint re-logged the identical warning on a long fit. LinAlgError
stays per-waypoint: that is the genuinely transient case (a
near-singular W the natural gradient can pass through) the existing
comment already describes.

After the first ValueError: warn once (now naming that waypoints are
disabled), record that one NaN entry, and stop scheduling waypoints
for the rest of this fit (no more mir() calls, no more entries) --
both backends. A local flag inside _fit_once, not an instance
attribute: it only matters within one fit() call.

Updated the two existing tests this changes the contract of
(injected-failure and organic-rank-reduction) to assert the new
stop-after-first-ValueError behavior on both backends, including that
mir()/flaky_mir is never called again after the failure.
_load_params's finiteness check only covered comp_list/pdtype (via
_safe_int_cast) -- the other 10 float _PARAM_ARRAYS (A, W, c, mu,
alpha, beta, rho, gm, mean, sphere) had no isfinite check at all, so a
NaN/inf-poisoned payload would load "successfully" and only surface
later as a confusing downstream NaN with no diagnostic, contradicting
the same promise the existing W-singularity check already makes for
W specifically. Extends the named-ValueError check to every float
param.

Test: a NaN-poisoned mu payload (representative of the 10) is
rejected by from_state_dict with a named error.
max_iter=0 used to run the EM loop zero times and "complete"
successfully with stop_reason="max_iter" (not a degenerate marker)
and final_ll_=NaN -- an untrained model that every state_dict()/
write_amica_output() degenerate-fit guard then accepted, since none
of them check "did an E-step ever actually run", only "did
stop_reason end up degenerate".

Added a named ValueError at fit entry on both backends, alongside
the existing X.ndim/mir_step checks -- both are argument-validation
guards raising before any work happens, and the multi-restart path's
narrow "except RuntimeError" already lets ValueError propagate on
the first restart rather than swallowing it as a degenerate one.

The NumPy backend already validates max_iter >= 1 at construction
(pre-existing, unmodified); no fix needed there.

Tests: max_iter=0 raises the named error and leaves the model
untouched (unfitted) on both backends.
_load_params's numrej/good_idx restoration reached raw int()/
np.asarray() calls with no try/except -- a corrupted or hand-edited
payload's malformed value there raised an opaque bare
TypeError/ValueError instead of the "malformed AMICAMLXNG state: ..."
message every other field in this method already uses.

Tests: a non-numeric numrej and a good_idx that cannot be converted
to an integer index array each raise the named error.
Mirrors test_mlx_reject.py's do_reject analog. mir_history_ is in
_RESTART_STATE_ATTRS, so this exercises the same snapshot/restore path
with mir_step set so waypoints actually populate (PR #318 review item 7).
__init__ already validated max_iter, but it is a plain public attribute
a caller can reassign afterward, so fit() silently ran the EM loop zero
times if max_iter was mutated post-construction. torch/mlx take
max_iter as a fit() parameter re-validated every call; numpy takes it
only at construction, so re-check self.max_iter at fit entry to close
the same gap (PR #318 review item 5 clarification: all three backends).
One fit combines n_models=2, share_comps (forced genuine merge),
do_reject, n_restarts=2, and pdftype=1 (with keep_best=True passed to
confirm the do_reject/share_comps exclusion is logged, not silently
ignored), then walks every accessor, state_dict/from_state_dict,
.npz save/load, and write_amica_output/loadmodout, asserting
consistency at each stage (PR #318 review item 8).
Both use the deterministic two-model forcing recipe from
test_mlx_sharing.py (share_start=4, share_iter=8, comp_thresh=0.9): a
genuine merge, then write_amica_output/loadmodout round trips, and
mir() stays finite and per-model_idx-aware on the merged model
(PR #318 review item 9).
_PARAM_NAMES was missing mean/sphere/pdtype, so the module docstring's
'every fitted array is compared bit for bit' claim was not literally
true. All three agree bit-for-bit with the pre-Phase-3 epic tip
(PR #318 review item 10).
Both backends' no-E-step LLt tests called fit(max_iter=0) to reach a
'never fitted' state, which item 5's max_iter>=1 guard now rejects
before that state is reachable. Rewritten to check the same
construction-time invariant directly; the write_amica_output-omits-LLt
behavior they also exercised is already covered by
test_from_state_dict_write_amica_output_omits_llt (torch) and
test_from_state_dict_model_warns_and_omits_llt (mlx).
Four places claimed 'epic #278 is complete as of Phase 3' without
naming variance_order, which actually landed in the post-Phase-3
polish round (mlx_impl/__init__.py, .rules/backend_parity.md,
AGENTS.md); also fixed docs/changelog.md's do_reject/keep_best
exclusion note from future to past tense, now that do_reject shipped
in Phase 3 (PR #318 review items 11-12).
Several docstring/comment citations into torch_impl/core.py had drifted
from their targets (this epic's own accumulated edits, plus this
round's exception-consistency/max_iter changes): write_amica_output,
_PARAM_TENSORS, the digamma dorho-gate (also pointed at the wrong
code entirely -- the NaN-reset path, not the gate itself), and the
phase-1 accessor citations (transform, get_mixing_matrix,
n_channels_in, get_rho, get_sensor_mixing_matrix, get_unmixing_matrix,
_check_model_idx). All recomputed against the current file
(PR #318 review item 13).
docs/api/mlx-backend.md listed the Phase 1 accessors but omitted
variance_order, which landed in the post-Phase-3 polish round
(PR #318 review item 14).
docs/guides/validation.md's table said rejection was 'both backends'
(stale since MLX shipped it in Phase 3) and attributed the
degenerate-fit refusal on transform/get_*/save to the raw backends,
when it is actually the AMICA wrapper's contract (the raw-backend gap
is issue #306); write_amica_output is the one exception, which gained
its own raw-backend guard directly in this epic (PR #318 review item 15).
Adds the third variant to the sanctioned exception-injection section:
wrapping a real method with monkeypatch to count/record calls while
still delegating to the real implementation, used by
test_write_amica_output_makes_no_extra_forward_pass to prove zero
E-step passes (PR #318 review item 16).
One-line addendum: the safeguard was ported to the MLX backend in
epic #278 Phase 2 (issue #288), with the same default, tolerance, and
share_comps/do_reject exclusions (PR #318 review item 17).
@neuromechanist
neuromechanist merged commit 6a3b038 into dev Sep 1, 2026
14 of 15 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-278-epic-mlx-parity branch September 1, 2026 14:01
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.

Epic: MLX backend non-fitting parity

1 participant