Repository navigation
Phase 3: posterior-probability (LLt) output parity with Fortran - #156
Conversation
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.
Review summaryReviewed 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. Critical1. 2. Restored models silently write no LLt. Important3. 4. NumPy duplicated the forward pass instead of sharing it. The torch side correctly reuses 5. Test gaps being closed
Verified and cleared
|
_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.
Review findings addressedAll findings from the review above are fixed; none deferred. Five commits on top of the original:
The parity bug (critical)Both backends now score only Shared forward pass, verified bit-exact
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 Bit-identical on all four, so the refactor is provably behavior-preserving and single-model #24 parity is untouched. Torch memory
New tests (7)
Suite: 225 passed, 9 skipped (MLX absent), 1 pre-existing xfail. Up 7 from 218, no regressions. Deliberate divergences, documented not silent
|
686dbd3
into
feature/issue-133-epic-mir-pmi-metrics
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.
Summary
The reference Fortran binary writes an
LLtfile 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:
Missing writer.
write_amicaout()emittedgm/A/W/S/mean/c/alpha/mu/sbeta/rho/comp_list/LLbut neverLLt, so no pyAMICA run produced the file at all.Reader reshape order (pre-existing, latent).
loadmodout()reshaped the rawLLtbytes with numpy's defaultorder="C", but Fortran'swrite_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'sloadmodout15.m). Verified against the bundledsample_data/amicaout/LLtfixture: underorder="C"the single-modelLhtdisagrees withLtfor 87% of samples, where they must be exactly equal; underorder="F"they match exactly andLt.mean()recoversnw * final_llindependently. This was latent only because nothing in the repo readLht/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_bestrollback (#51), where the final exported parameters are an earlier iterate than the training loop's last.modloglikis confirmed against the Fortran aslog|det W_h| + log(gm_h) + sldet + sum_i ll_src, andloglikas 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_orderreads the real Fortranamicaout/LLtfixture and asserts single-modelLht[0] == Ltexactly plusLt.mean() ~= nw * final_ll. This is the oracle that pins the layout to Fortran; it fails under the oldorder="C".test_numpy_llt_roundtripandtest_write_amica_output_llt_roundtripfit real single-model NumPy/NG models and round-trip the writtenLLtthrough 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_multimodelchecks a real 2-model NG fit satisfiesLt == logsumexp(Lht, axis=0).ruff check,ruff format --check,ty checkall clean.