Skip to content

Phase 5: wire MIR/PMI into the AMICA API - #160

Merged
neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-137-phase5-api-wiring
Jul 17, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-137-phase5-api-wiring

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Exposes the Phase 1-2 metrics on the model itself, per Scott Makeig's original request: computable at decomposition end, and optionally at specified decomposition waypoints.

  • AMICATorchNG.mir(X, *, model_idx=0, nbins=None) -> (mir_nats, variance) and .pmi(X, *, model_idx=0, nbins=None) -> mi_matrix
  • AMICA.mir / AMICA.pmi delegating through _check_usable, so they inherit the AMICA wrapper marks is_fitted_ even on a degenerate (nan_ll/singular_ll) fit #50 degenerate-fit contract for free
  • fit(..., mir_step=0) waypoint schedule populating mir_history_ as (iteration, mir_nats, variance)

Closes #137
Part of epic #133

Why this phase matters more than "convenience wiring"

Hand-composing the unmixing is demonstrably error-prone. While building Phase 4 I got it wrong, wrote the wrong rule into the verification doc, and a reviewer then escalated a non-bug as critical on that authority. #159 subsequently proved loadmodout itself reads W/sbeta/rho in the wrong byte order. A supported accessor removes a whole class of that.

The load-bearing test is test_mir_composes_unmixing_the_documented_way, which asserts model.mir(X) exactly equals metrics.mir(get_unmixing_matrix(0) @ sphere, X). Verified it catches the real mistake: dropping the .T (the exact Phase 4 error) makes it fail. Note the numbers, because they explain why this was so easy to get wrong and so hard to spot — correct 42.5486 vs wrong 42.4688, a 0.2% difference. A plausible number from a wrong matrix. An allclose test would sail past it; only exact equality against the documented composition catches it.

Design notes

  • mir needs the full raw-data-to-sources transform, W[:, :, m].T @ sphere (note the transpose), not bare W. MIR is shift-invariant, so the mean/c centering transform applies is irrelevant to it. pmi needs sources, so it calls transform rather than hand-rolling.
  • MIR-only waypoints, on measured evidence: on the real 32x30504 sample, mir costs 20 ms and pairwise_mi 678 ms (34x), against a CPU fit iteration of ~36-400 ms. PMI on a schedule would dominate the fit, for a quantity that is a final structural diagnostic rather than a convergence signal. MIR over iterations is what actually answers the request. model.pmi(X) stays available on demand.
  • PCA guard: pcakeep/pcadb leave the sphere rank-deficient, so MIR's sum(log|eig|) log-Jacobian is undefined. Both mir() and mir_step>0 raise a clear ValueError naming the flags, up front rather than mid-fit, mirroring the existing share_comps guard (torch_impl/core.py:553-561) which rejects the same flags for the same underlying reason.
  • Waypoint gate follows the repo idiom: if mir_step > 0 and it % mir_step == 0, the same shape as the NumPy backend's writestep/histstep (numpy_impl/core.py:1429-1435). AMICATorchNG.fit had no hook mechanism of any kind; no plugin system was invented.
  • keep_best (Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51) interaction: mir_history_ is a true trajectory like ll_history and is not rewritten by a best-iterate rollback. The fit-end value is model.mir(X) (computed from the restored, exported parameters), not mir_history_[-1] — mirroring the existing final_ll_ vs ll_history_[-1] distinction that exists precisely because of Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51. Documented in-code.
  • Not persisted: mir_history_ stays out of state_dict() (a diagnostic, not a fitted parameter; adding it would need a format-version bump). format_version stays 3.
  • Not blocked by loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159: that bug is in the loaded-fit path (loadmodout). Everything here reads the live model's own W/sphere and transform(), which are correct. A loaded-fit accessor belongs to loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159.

Test plan

Real bundled sample EEG throughout, reusing the existing module-scoped real_data/fitted_ng fixtures; no synthetic data (.rules/testing.md).

  • model.mir(X) exactly equals the documented composition; model.pmi(X) exactly equals pairwise_mi(model.transform(X))
  • Real fitted unmixing gives mir > 0 and mir > mir(identity)
  • mir/pmi added to the existing unfitted-raises and test_degenerate_fit_refuses_output lambda lists, rather than parallel new tests
  • mir_step=2 populates mir_history_ at [0, 2, 4] with finite values; mir_step=0 leaves it empty and is byte-identical to omitting it; mir_step<0 raises
  • pcakeep + mir() raises naming pcakeep; pcakeep + mir_step>0 raises before fitting
  • Suite: 267 passed, 9 skipped, 1 pre-existing xfail. Exactly +9 vs the 258 baseline, matching the 9 new tests.
  • ruff check, ruff format --check, ty check clean; mkdocs build --strict passes

No MATLAB gate this phase: MIR is already pinned to the Apache-2.0 getMIR.m oracle at 1.7e-15 and PMI to minfojp at r=0.9887 (Phase 4). This is wiring over already-verified metrics, and the tests assert the wiring reproduces the free functions exactly, so there is no new numerical claim to gate.

The waypoint called self.mir(X) unprotected, so a raising waypoint
propagated straight out of fit() and destroyed the whole decomposition.
Verified by forcing the raise: the ValueError escaped fit() and the run
was lost.

This was reachable, not theoretical. metrics.mir raises on a
near-singular unmixing, and a near-singular W mid-fit is a transient the
natural gradient can pass through -- the training path only warns about
the same condition. So enabling a purely diagnostic flag could throw away
hours of training over something the optimiser was about to recover from.

Now caught at the waypoint: warn naming the iteration and cause, and
record (iter, nan, nan) so the gap stays visible in mir_history_ rather
than silently absent. A plotted trajectory shows a hole exactly where the
transient was. The fit itself is unaffected.

The new test fails on the unprotected version.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review summary

Four reviewers, each in its own isolated worktree this time (sharing one worktree across concurrent reviewers in #158 manufactured three phantom findings, so that is fixed). One real bug, one flaw in my own test design, and two doc nits.

The real bug (9343656): a failed waypoint destroyed the fit

The waypoint called self.mir(X) unprotected, so a raising waypoint propagated straight out of fit() and threw away the whole decomposition. Verified by forcing the raise: the ValueError escaped fit() and the run was lost.

This was reachable, not theoretical. metrics.mir raises on a near-singular unmixing, and a near-singular W mid-fit is a transient the natural gradient can pass through — the training path only warns about the same condition (numpy_impl/core.py:827). So enabling a purely diagnostic flag could throw away hours of training over something the optimiser was about to recover from.

Now caught at the waypoint: warn naming the iteration and cause, and record (iter, nan, nan) so the gap stays visible in mir_history_ rather than silently absent — a plotted trajectory shows a hole exactly where the transient was. Not a silent failure. test_failing_mir_waypoint_does_not_kill_the_fit fails on the unprotected version.

CI caught a flaw in my own test design

I had insisted on exact equality for the convention test. It passed locally and failed on CI:

assert (42.548551297...9056413769711) == (42.548551297...9056413769711)

Identical to ~12 digits, differing in the last bits: mir() composes W.T @ sphere in torch while the test composes it in numpy, and the two BLAS paths disagree at the ULP level. Relaxed to rtol=1e-12, which is still nine orders of magnitude tighter than the 1.9e-3 error it guards (dropping the .T gives 42.4688 vs 42.5486). Verified it still fails on a dropped .T. The guard is intact and now portable.

Checked and cleared (verified, not assumed)

  • Degenerate fit: refused at both layers — RuntimeError: Refusing to compute MIR: fit ended degenerate at the wrapper, LinAlgError: Array must not contain infs or NaNs at the backend. No plausible-but-wrong number, which was the main risk for a metric API.
  • NaN/Inf in X: clear ValueError from validate_signal_matrix for both mir and pmi, inherited from the Phase 1/2 metric hardening.
  • Docs: the comment reviewer found no inaccurate claims and specifically confirmed this diff does not repeat the epic's W-convention mistake, asserts nothing about AmicaOutput/loadmodout (leaving loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159 untouched), and states the keep_best caveat in three places a user would see.

Doc fixes

  • "MIR" now expanded at its true first use in each file (AGENTS.md: define abbreviations before use). It appeared unexpanded in the AMICA class docstring, which is the first thing help(AMICA) shows.
  • AMICA.mir/AMICA.pmi gained Raises sections: a user reading only the wrapper had no way to learn about the pcakeep/pcadb ValueError, which lives on the backend method.

Suite: 268 passed, 9 skipped, 1 pre-existing xfail.

Three review findings, each proven by sabotage rather than argued.

model_idx and nbins were never exercised: hardcoding either inside mir()
and pmi() left all nine tests passing, because the shared fixture is
single-model and every wiring test defaulted to model 0 and nbins=None on
both sides of the comparison. The new tests use a genuine 2-model fit and
a non-default nbins, and both fail on that sabotage.

The pca up-front test matched on "pcakeep", which is generic: mir()'s own
downstream guard says it too, so the test could not distinguish "rejected
before iteration 0" from "rejected during iteration 0" -- the entire claim
it exists to make. Now matches "Rejected up front", which is unique to
fit()'s guard.

Note the waypoint fix in the previous commit incidentally hardened this:
with the ValueError now caught at the waypoint, deleting the up-front
guard produces no error at all rather than a look-alike message. The
tighter match keeps the test honest independently of that.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 2: remaining findings resolved (9b9c9bd)

Two real test gaps, proven by sabotage

model_idx and nbins were never exercised. Hardcoding either one inside mir() and pmi() left all nine tests passing, because the shared fixture is single-model and every wiring test defaulted to model 0 / nbins=None on both sides of the comparison. Fixed with a genuine 2-model fit and a non-default nbins; verified both new tests fail on that exact sabotage:

model_idx hardcoded to 0  -> FAILED test_mir_and_pmi_honour_model_idx: model_idx=1 returned model 0's MIR
nbins hardcoded to None   -> FAILED test_mir_and_pmi_honour_nbins: nbins was ignored by pmi()

A test that could not test its own claim

test_mir_step_raises_under_pca_reduction_up_front matched on "pcakeep" — which both guards mention, fit()'s up-front one and mir()'s downstream one. So it could not distinguish "rejected before iteration 0" from "rejected during iteration 0", which is the entire claim it exists to make. Now matches "Rejected up front", unique to fit()'s guard.

(The waypoint fix in 9343656 incidentally hardened this: with the ValueError now caught at the waypoint, deleting the up-front guard yields no error at all rather than a look-alike message. The tighter match keeps the test honest independently of that.)

One CRITICAL refuted, with evidence

A reviewer flagged as critical that pmi() returns a finite matrix on a singular W while mir() refuses — the "plausible but wrong" failure mode. Tested, and it is a false positive. With W made exactly singular (min |eig| = 4.8e-17):

sources 3 and 5 are now identical:   max|s3 - s5| = 0.00e+00
MI(3,5) = 2.7478   <- the collinear pair, and the MAXIMUM off-diagonal
H(s3)   = 2.7478   <- MI(3,5)/H(s3) = 1.0000 exactly
median off-diagonal MI = 0.0291     (MI(3,5) is 94x this)

That is not a plausible-but-wrong number: it is the mathematically correct answer, MI(X,X) = H(X), the theoretical maximum. It is the degeneracy alarm. The asymmetry with mir() is principled rather than a gap: MIR needs an invertible transform (its log|det W| term is undefined for a singular map, so refusing is correct), while PMI is mutual information between signals and stays well-defined for degenerate sources. Adding the proposed conditioning guard to pmi() would reject a correct and diagnostically valuable answer.

Deferred (not blocking)

mir_step x keep_best rollback, and mir_history_ after save/load. Both are documented claims without direct tests. They are diagnostic-trajectory bookkeeping on an opt-in feature, and the underlying mechanism (mir_history_ is absent from _PARAM_TENSORS, so _restore_params cannot touch it) was verified by review. Worth a follow-up rather than holding the epic's final phase.

Suite: 270 passed, 9 skipped, 1 pre-existing xfail.

@neuromechanist
neuromechanist merged commit 4e47885 into feature/issue-133-epic-mir-pmi-metrics Jul 17, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-137-phase5-api-wiring branch July 17, 2026 06:16
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