Skip to content

Derive mir PCA guard from fitted geometry - #300

Merged
neuromechanist merged 3 commits into
devfrom
fix/issue-283-mir-guard
Aug 24, 2026
Merged

neuromechanist merged 3 commits into
devfrom
fix/issue-283-mir-guard

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

AMICATorchNG._pca_reduced() decided PCA-reduction incompatibility by checking only the explicit pcakeep/pcadb constructor parameters.
A fit whose rank reduction came from automatic numerical-rank detection (mineig/mineig_rel, on by default) slipped past that guard.
AMICAICA.mir() then crashed with an opaque numpy.linalg.LinAlgError instead of the documented, clean ValueError.

_pca_reduced() is now derived from the fitted sphere's geometry (sphere.shape[0] != sphere.shape[1]), so it catches rank reduction regardless of which mechanism caused it.
A new _pca_reduction_requested() keeps the old explicit-parameter check for exactly one remaining caller: _fit_once's upfront mir_step > 0 gate, which runs before that fit's sphere exists, so geometry is not yet knowable there.
The auto-detected case for that pre-fit gate was already handled gracefully (the mid-fit MIR waypoint catches both ValueError and LinAlgError, logs, and records NaN), so that path's behavior is unchanged.

Before / after (real EEG, rank-16 SVD projection, mineig_rel auto-detection, no pcakeep)

Before (base commit d392ba0):

n_components_: 16 of 32
numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square

After this fix:

n_components_: 16 of 32
ValueError: mir() is incompatible with PCA reduction: the fitted sphere is rank-deficient (16 of 32 channels kept), whether from explicit pcakeep/pcadb or automatic mineig/mineig_rel numerical-rank detection, so MIR's log-Jacobian term is undefined for the resulting non-square/non-invertible unmixing.

NumPy backend

No equivalent hole exists to fix.
mir()/pmi() are AMICATorchNG-only (issues #137/#143); numpy_impl/core.py has no mir() method at all, so there is nothing to port this guard to.

Tests

pamica/tests/torch_tests/test_amica_ng_wrapper.py gets a backend-level regression test (auto-detected reduction through AMICA -> mir() raises the documented ValueError, not LinAlgError) plus a full-rank positive control.
pamica/tests/mne_tests/test_annotation_rank_reduction.py gets the AMICAICA-level regression test PR #282 deliberately left unpinned, using the existing fitted_auto_rank fixture, plus a full-rank positive control through the wrapper.

Test plan

  • uv run pytest pamica/tests/mne_tests/ pamica/tests/torch_tests/ -q --no-cov -m "not slow" (332 passed, 5 skipped)
  • uv run pytest -m "not slow" -n auto (685 passed, 26 skipped, 1 xfailed)
  • uv run ruff check . / uv run ruff format --check . / uv run ty check (all clean)

Closes #283

@neuromechanist
neuromechanist merged commit 3e54aa2 into dev Aug 24, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the fix/issue-283-mir-guard branch August 24, 2026 04:53
@neuromechanist neuromechanist mentioned this pull request Aug 25, 2026
@neuromechanist neuromechanist mentioned this pull request Sep 1, 2026
11 of 12 tasks
neuromechanist added a commit that referenced this pull request Sep 1, 2026
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.
neuromechanist added a commit that referenced this pull request Sep 1, 2026
* 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).
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.

mir() misses auto-detected rank reduction in _pca_reduced

1 participant