Skip to content

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

Closed

Description

@neuromechanist

Part of #133. Blocks #136 (visualizations need real multi-model posterior data).

Background

While planning Phase 3 (MIR/PMI visualizations, #136 -- becoming Phase 4), the multi-model posterior-probability timeline plot needed real per-timepoint, per-model posterior data. This turned up a genuine parity gap, not just a missing input for the viz phase.

Fortran writes an LLt file every fit (amica15.f90/amica17.f90 write_output, gated by write_LLt, default .true.): a per-timepoint, per-model log-likelihood array (modloglik) plus the total per-sample log-likelihood (loglik), natural log, laid out as [model_1..model_M, total] per timepoint, sequential raw float64. It's a fresh E-step snapshot each time write_output runs (every writestep iterations, and once more after the loop), not an accumulated history.

Neither pyAMICA backend writes this file. _write_results (pyAMICA/numpy_impl/core.py) and write_amica_output (pyAMICA/torch_impl/core.py) both delegate to pyAMICA/numpy_impl/load.py's write_amicaout(), which writes gm/A/W/S/mean/c/alpha/mu/sbeta/rho/comp_list/LL -- no LLt.

Separately, the existing reader has a confirmed, latent bug. loadmodout() (pyAMICA/numpy_impl/load.py) reshapes the raw LLt bytes with order='C' (numpy's default); the file's actual layout is column-major w.r.t. a (num_models+1, N) matrix (matching pyAMICA/sample_data/loadmodout15.m's MATLAB reader, column-major by default there). Verified empirically against the real bundled pyAMICA/sample_data/amicaout/LLt fixture (num_models=1, so Lht must equal Lt exactly): current order='C' gives Lht != Lt for 87% of samples; order='F' gives exact equality everywhere, and mean(Lt) ~= -108.86 matches nw * final_ll = 32 * -3.40187 ~= -108.86 independently. This bug is latent today only because nothing exercises Lht/Lt/v anywhere in the repo (validate_implementations.py never calls loadmodout; no test reads these fields).

Scope

  1. Fix the reader's reshape bug (order="F"), with a regression test against the real bundled amicaout/LLt fixture.
  2. Add an LLt writer to both backends: a fresh full-dataset E-step forward pass at write time (neither backend persists per-sample per-model log-likelihood after fit; it's computed fresh per block every iteration and discarded), reusing each backend's existing block-chunked E-step loop. Wire into write_amicaout() (gains optional Lht/Lt params), _write_results (numpy), and write_amica_output (torch).
  3. Real-data validation: round-trip a real single-model fit's own LLt through the fixed reader (Lht == Lt exactly, mean(Lt) ~= nw * final_ll_), plus a small real 2-model fit checked for Lt ~= logsumexp(Lht, axis=0).

No mock/synthetic data -- real bundled sample EEG and the real bundled Fortran LLt fixture throughout.

Activity

  1. added
    feature
    on Jul 16, 2026
  2. neuromechanist commented on Jul 16, 2026

    @neuromechanist
    MemberAuthor

    Done in PR #156, squash-merged into the epic branch feature/issue-133-epic-mir-pmi-metrics (686dbd3). Closing manually: the PR targeted the epic branch rather than the default branch, so GitHub's auto-close on merge did not fire. Ships to main with epic #133.

    Both bugs fixed: loadmodout's column-major reshape, and the missing LLt writer on both backends. Review additionally caught a do_reject parity divergence (we wrote real log-likelihoods where Fortran writes exactly 0.0, which its load_rej relies on as the rejection-mask sentinel); that is fixed and guarded by tests on both backends. Follow-up #157 tracks the cheaper stash-logV-during-E-step design.

  3. neuromechanist commented on Jul 16, 2026

    @neuromechanist
    MemberAuthor

    Interop contract verified in both directions, bit-exact

    The acceptance bar here is bidirectional: pyAMICA's reader must understand Fortran's output, and EEGLAB's reader must understand pyAMICA's output. The automated tests in #156 only pin the first. They cannot pin the second, because the round-trip tests prove our writer agrees with our own reader, which a self-consistently-wrong writer/reader pair would also satisfy.

    That gap is not theoretical: #92 caught a real column-major bug exactly there, when loadmodout15.m read scrambled mixture params (per-component alpha not summing to 1) that code review had missed. LLt is a new file in the writer and had never been through that gate.

    Ran the real loadmodout15.m under MATLAB R2025b against pyAMICA-written output and against the genuine Fortran fixture, comparing every result to loadmodout's with np.array_equal (not allclose -- both readers parse identical bytes, so anything short of exact equality is a real bug):

    pyamica_m1  Lht (1, 4096)  equal=True | Lt (4096,)  equal=True | max|dH|=0.0 max|dT|=0.0
    pyamica_m2  Lht (2, 4096)  equal=True | Lt (4096,)  equal=True | max|dH|=0.0 max|dT|=0.0
    fortran     Lht (1, 30504) equal=True | Lt (30504,) equal=True | max|dH|=0.0 max|dT|=0.0
    
    EEGLAB loadmodout15 == pyAMICA loadmodout, bit-exact, all cases: True
    pyamica_m1  single-model Lht[0]==Lt via MATLAB: True
    fortran     single-model Lht[0]==Lt via MATLAB: True
    

    Corroborating: the 2-model mod_prob agrees (MATLAB [0.554689 0.445311] vs pyAMICA [0.5547 0.4453]), so both readers apply the same gm-descending reordering and the model axis stays aligned with W/mod_prob across implementations. The genuine Fortran fixture reads to Lt mean = -108.859935652062 under both readers, matching nw * final_ll = 32 * -3.40187 independently.

    MATLAB cannot run in CI, so this is recorded rather than automated, the same way #92's was: .context/issue-155/matlab_interop_verification.md (commit 0e0404c), with a pointer from .context/scratch_history.md next to the #92 lesson. Re-run it by hand if the LLt layout, write_amicaout, or loadmodout ever change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions