Skip to content

Phase 3: posterior-probability (LLt) output parity with Fortran - #156

Merged
neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-155-phase3-llt-parity
Jul 16, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-155-phase3-llt-parity

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

The reference Fortran binary writes an LLt file on every run: the per-timepoint, per-model log-likelihood (modloglik) plus the total per-sample log-likelihood (loglik). Neither pyAMICA backend produced this file, and the reader had a separate latent bug. Since parity with the Fortran reference is this project's definition of correctness, a reference artifact we fail to reproduce is a regression, not a missing nice-to-have. This phase closes both gaps.

Two distinct bugs:

  1. Missing writer. write_amicaout() emitted gm/A/W/S/mean/c/alpha/mu/sbeta/rho/comp_list/LL but never LLt, so no pyAMICA run produced the file at all.

  2. Reader reshape order (pre-existing, latent). loadmodout() reshaped the raw LLt bytes with numpy's default order="C", but Fortran's write_output (amica15.f90:2308-2333) writes, per timepoint, each model's log-likelihood then the total, which is a column-major (num_models+1, N) layout (matching EEGLAB's loadmodout15.m). Verified against the bundled sample_data/amicaout/LLt fixture: under order="C" the single-model Lht disagrees with Lt for 87% of samples, where they must be exactly equal; under order="F" they match exactly and Lt.mean() recovers nw * final_ll independently. This was latent only because nothing in the repo read Lht/Lt/v.

Approach

Neither backend retains a full-dataset per-sample log-likelihood after fit; it is computed per block during the E-step and discarded once folded into sufficient statistics. Both backends therefore recompute it with a fresh full-dataset forward pass at write time, from whatever parameters are currently on the model. This is what makes the output correct after a keep_best rollback (#51), where the final exported parameters are an earlier iterate than the training loop's last.

modloglik is confirmed against the Fortran as log|det W_h| + log(gm_h) + sldet + sum_i ll_src, and loglik as its log-sum-exp over models.

Closes #155
Part of epic #133

Test plan

All against real bundled sample EEG and the real Fortran-produced fixture; no synthetic data.

  • test_loadmodout_llt_reshape_order reads the real Fortran amicaout/LLt fixture and asserts single-model Lht[0] == Lt exactly plus Lt.mean() ~= nw * final_ll. This is the oracle that pins the layout to Fortran; it fails under the old order="C".
  • test_numpy_llt_roundtrip and test_write_amica_output_llt_roundtrip fit real single-model NumPy/NG models and round-trip the written LLt through the fixed reader. A writer/reader order mismatch scrambles the interleave and breaks these, so they transitively pin the writer to Fortran's layout.
  • test_write_amica_output_llt_multimodel checks a real 2-model NG fit satisfies Lt == logsumexp(Lht, axis=0).
  • Full suite green on the rebased branch: 218 passed, 9 skipped (MLX absent), 1 pre-existing xfail.
  • ruff check, ruff format --check, ty check all clean.

Fortran writes a per-timepoint, per-model log-likelihood file (LLt) on
every run; neither pyAMICA backend produced it, and loadmodout read the
bundled Fortran fixture with a C-order reshape where the layout is
column-major (verified against sample_data/amicaout/LLt: single-model
Lht != Lt for 87% of samples under order='C', exact equality under 'F').

Both backends now recompute the full-dataset per-sample log-likelihood
from their current parameters at write time, so the output is correct
after a keep_best rollback. Tested against real sample EEG.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review summary

Reviewed by four parallel agents (code, tests, comments, silent failures) plus a maintainer pass against the Fortran reference. CI was green on the first push, but the review surfaced a real parity bug. All findings below are being addressed in follow-up commits; none are being deferred.

Critical

1. do_reject breaks LLt parity with Fortran. Found independently by the test reviewer, the silent-failure reviewer, and the maintainer pass. Fortran zeroes modloglik(:,i) and loglik(i) for rejected samples before writing (amica15.f90:2211-2216). Those zeros are load-bearing, not incidental: Fortran's load_rej reads LLt back and reconstructs the rejection mask by testing sum(modloglik(:,i)) == 0.0 as the sentinel for a rejected sample (amica15.f90:887-896). Both backends currently compute over the full unfiltered dataset and write real log-likelihoods everywhere, so a Fortran load_rej run reading a pyAMICA LLt would silently conclude nothing was rejected. Secondary hazard: rejected outlier samples were being pushed through the model for the first time at write time. Fix: compute only over good_idx and scatter into zero-filled full-length arrays, so rejected samples are exactly 0.0 and are never evaluated. Guarded by new tests on both backends.

2. Restored models silently write no LLt. fit() -> save() -> load() -> write_amica_output() is a fully public path that produces an output directory missing LLt, with no warning at any layer. from_state_dict never sets the training data, and the wrapper's _check_usable does not know about it. The wrapper docstring does not even list LLt among the written files, so nothing documented was being violated either. Fix: explicit logger.warning naming the restored-model case, plus docstring updates on both the backend and the wrapper.

Important

3. _X_t retained the full sphered dataset for the model's lifetime. The torch backend previously freed the training data after fit(); retaining it pins n_channels * N * 8 bytes, on GPU too, for exactly the large-data case the backend exists to serve. Fix: compute LLt once at the end of fit() (strictly after any keep_best rollback, so it reflects the exported parameters) and retain only the compact (n_models+1, N) arrays, roughly 16x smaller at 32 channels. The NumPy backend is unchanged here: it already retained self.data before this PR and must keep writing at mid-training writestep boundaries.

4. NumPy duplicated the forward pass instead of sharing it. The torch side correctly reuses _forward; the NumPy _compute_full_posterior_ll was a hand copy of _get_block_updates's b/z/logV math. This repo has had one-sided forward-pass bugs before (#24's fp-vs-dpdf sign error), and a future fix to one copy would silently produce plausible-but-wrong LLt from the other. The copy had also dropped the isfinite(logdet_W) guard the original carries, so a singular W would write silent -inf/NaN into LLt. Fix: extract one shared _forward_block used by both callers, which restores the guard on the write path. Being verified bit-exactly against the pre-refactor LL trajectory, since this touches the training path.

5. write_amicaout silently skipped LLt when given only one of Lht/Lt. Not reachable today (both call sites pass them as a computed pair) but a latent footgun in a public writer. Fix: raise ValueError on a half-specified pair.

Test gaps being closed

do_reject + LLt on both backends; NumPy multi-model LLt (only torch had one, and the two implementations are independent); from_state_dict -> write_amica_output; and a partial final block (all three original tests used sample counts exactly divisible by block_size, so the remainder branch was never exercised).

Verified and cleared

  • test_loadmodout_llt_reshape_order is a genuine regression guard, confirmed empirically: reverting to the old order="C" gives a max abs difference of ~58.7 between Lht[0] and Lt on the real bundled fixture, where they must be exactly equal.
  • The writer is transitively pinned to Fortran's layout: the fixture test pins the reader to order="F", and the round-trip tests pin writer and reader to the same convention. No multi-model Fortran-produced LLt fixture exists in the repo, so the multi-model writer layout rests on reading amica15.f90:2308-2333 rather than on an oracle.
  • loadmodout's gm-based reordering does correctly permute Lht alongside W/c/alpha (load.py:313-314), so model indexing stays coherent. An earlier suspicion of a mismatch here was investigated and refuted.
  • Every Fortran line citation in the new comments was checked against the cited ranges and is accurate, including correctly distinguishing amica15.f90 (the reference binary's source) from amica17.f90 (the later GG-only trim).

_compute_full_posterior_ll now scores only good_idx under do_reject
and scatters into zero-initialized arrays, matching Fortran's zero
sentinel that load_rej relies on for its rejection mask. The numpy
backend's forward pass (b/z/logV) is extracted into a shared
_forward_block used by both _get_block_updates and
_compute_full_posterior_ll, so a future fix cannot silently drift
between two copies. Also drops the dead data= parameter (the only
caller never passed one) and documents the deliberate one-M-step-
fresher divergence from Fortran plus the added per-writestep cost.
Drops _X_t (which pinned the full sphered dataset on the model,
GPU included) in favor of computing LLt exactly once at the end of
fit(), strictly after any keep-best restore, storing only the
compact per-sample arrays. write_amica_output reads those stored
arrays directly and logs a warning instead of silently omitting
LLt for a model restored via from_state_dict (no training data to
recompute from). Under do_reject, only good_idx is scored and
scattered into zero-initialized arrays, matching Fortran's zero
sentinel. Documents the same deliberate divergence from Fortran's
one-M-step-stale LLt as the numpy backend.
Passing exactly one of Lht/Lt silently skipped the whole LLt file;
raise ValueError naming both params instead of a silent no-op.
Covers the review findings: do_reject zeroing on both backends,
a numpy multi-model round-trip (only torch had one), a partial
final block on both backends (existing tests were all evenly
divisible by block_size), a from_state_dict model omitting LLt
with a warning, and a real non-identity gm_ord case proving
loadmodout permutes Lht in lockstep with W/mod_prob rather than
leaving it in on-disk order.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review findings addressed

All findings from the review above are fixed; none deferred. Five commits on top of the original:

Commit Fixes
621c5db do_reject zero-sentinel parity + shared NumPy forward pass
85f2a35 torch LLt computed once after keep-best restore; warns when omitted
07a12b6 LLt documented in the wrapper's docstring
750cdb8 write_amicaout raises on a half-specified Lht/Lt pair
c4358fe Seven new regression tests

The parity bug (critical)

Both backends now score only good_idx and scatter into zero-filled full-length arrays, so a rejected sample is exactly 0.0 in both Lht and Lt, matching Fortran's sentinel that load_rej depends on. Computing only the good set also means rejected outliers are no longer pushed through the model at write time.

Shared forward pass, verified bit-exact

_get_block_updates and _compute_full_posterior_ll now share one _forward_block on the NumPy side (torch already shared _forward). This restores the isfinite(logdet_W) guard on the write path, which the duplicate had dropped.

Because this touches the training path in a bit-exact-parity codebase, it was verified against the pre-refactor commit rather than relying on a green suite: identical real-data fits were run on 1ab6797 and on the refactored tree, and the full LL trajectories compared with np.array_equal.

numpy     len  25 vs  25  array_equal=True  max|diff|=0.0
numpy_mm  len  15 vs  15  array_equal=True  max|diff|=0.0
torch     len  25 vs  25  array_equal=True  max|diff|=0.0
torch_mm  len  15 vs  15  array_equal=True  max|diff|=0.0

Bit-identical on all four, so the refactor is provably behavior-preserving and single-model #24 parity is untouched.

Torch memory

_X_t is gone. fit() computes LLt once, strictly after the keep-best restore (so it reflects the parameters actually exported), and retains only the compact (n_models+1, N) arrays. The full sphered dataset is no longer pinned for the model's lifetime, which matters on CUDA.

New tests (7)

do_reject zeroing on both backends (each asserts the fixture genuinely rejects something, so it cannot degrade into a tautology); NumPy multi-model; partial final block on both backends (the previous tests all used sample counts exactly divisible by block_size); from_state_dict -> write_amica_output asserting the warning fires and no LLt is written; and gm-reorder alignment, which pins Lht's model axis to W/gm against a real non-identity gm ordering read from raw bytes. That last one closes a gap we found in our own test: Lt == logsumexp(Lht, axis=0) is permutation-invariant over the model axis and so could never have caught a misalignment.

Suite: 225 passed, 9 skipped (MLX absent), 1 pre-existing xfail. Up 7 from 218, no regressions. ruff, ruff format --check, ty all clean.

Deliberate divergences, documented not silent

  • LLt staleness. Fortran fills modloglik during iteration i's E-step, the M-step then updates the parameters, and write_output writes both, so Fortran's on-disk LLt is stale by one M-step relative to its own written W/A. We recompute post-update, so ours is self-consistent with the written parameters. Immaterial near convergence and nothing downstream depends on the staleness, unlike the do_reject zero-sentinel, which is load-bearing and we do match. Commented at both call sites so nobody "fixes" it toward the wart.
  • Recompute cost. Documented in the docstrings and tracked as Stash per-sample logV during the E-step instead of recomputing for LLt #157 (stash per-sample logV during the E-step, as Fortran does), rather than left as a bare TODO.

@neuromechanist
neuromechanist merged commit 686dbd3 into feature/issue-133-epic-mir-pmi-metrics Jul 16, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-155-phase3-llt-parity branch July 16, 2026 22:48
neuromechanist added a commit that referenced this pull request Jul 16, 2026
The LLt tests in #156 only pin one direction of the interop contract (we
read Fortran's output, via the real bundled fixture). They cannot pin the
other direction: a self-consistently-wrong writer/reader pair passes every
round-trip test. Issue #92 caught a real column-major bug exactly there, and
LLt is a new file that had never been through that gate.

Verified by hand against real loadmodout15.m under MATLAB R2025b: it reads
pyAMICA's LLt bit-exactly (single- and multi-model), and both readers agree
bit-exactly on the genuine Fortran fixture. MATLAB is not on CI, so this is
recorded rather than automated.
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