Repository navigation
Phase 5: wire MIR/PMI into the AMICA API - #160
neuromechanist merged 6 commits into
Conversation
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.
Review summaryFour 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 (
|
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.
Review round 2: remaining findings resolved (
|
4e47885
into
feature/issue-133-epic-mir-pmi-metrics
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_matrixAMICA.mir/AMICA.pmidelegating 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 freefit(..., mir_step=0)waypoint schedule populatingmir_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
loadmodoutitself readsW/sbeta/rhoin 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 assertsmodel.mir(X)exactly equalsmetrics.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. Anallclosetest would sail past it; only exact equality against the documented composition catches it.Design notes
mirneeds the full raw-data-to-sources transform,W[:, :, m].T @ sphere(note the transpose), not bareW. MIR is shift-invariant, so themean/ccenteringtransformapplies is irrelevant to it.pmineeds sources, so it callstransformrather than hand-rolling.mircosts 20 ms andpairwise_mi678 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.pcakeep/pcadbleave the sphere rank-deficient, so MIR'ssum(log|eig|)log-Jacobian is undefined. Bothmir()andmir_step>0raise a clearValueErrornaming the flags, up front rather than mid-fit, mirroring the existingshare_compsguard (torch_impl/core.py:553-561) which rejects the same flags for the same underlying reason.if mir_step > 0 and it % mir_step == 0, the same shape as the NumPy backend'swritestep/histstep(numpy_impl/core.py:1429-1435).AMICATorchNG.fithad 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 likell_historyand is not rewritten by a best-iterate rollback. The fit-end value ismodel.mir(X)(computed from the restored, exported parameters), notmir_history_[-1]— mirroring the existingfinal_ll_vsll_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.mir_history_stays out ofstate_dict()(a diagnostic, not a fitted parameter; adding it would need a format-version bump).format_versionstays 3.loadmodout). Everything here reads the live model's ownW/sphereandtransform(), 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_ngfixtures; no synthetic data (.rules/testing.md).model.mir(X)exactly equals the documented composition;model.pmi(X)exactly equalspairwise_mi(model.transform(X))mir > 0andmir > mir(identity)mir/pmiadded to the existing unfitted-raises andtest_degenerate_fit_refuses_outputlambda lists, rather than parallel new testsmir_step=2populatesmir_history_at [0, 2, 4] with finite values;mir_step=0leaves it empty and is byte-identical to omitting it;mir_step<0raisespcakeep+mir()raises namingpcakeep;pcakeep+mir_step>0raises before fittingruff check,ruff format --check,ty checkclean;mkdocs build --strictpassesNo MATLAB gate this phase: MIR is already pinned to the Apache-2.0
getMIR.moracle at 1.7e-15 and PMI tominfojpat 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.