Skip to content

loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159

Closed

Description

@neuromechanist

Surfaced while building Phase 4's plot_topo_pdf (#136), which needs per-component source activations derived from an AmicaOutput. Splitting it out rather than guessing, per the #155 precedent.

The observation

loadmodout's W does not reproduce the live model's own sources at high fidelity, under either orientation, even in the cleanest possible case.

Setup: real bundled sample EEG (32ch x 8192), AMICATorchNG(n_models=1, n_mix=3, seed=1), 30 iterations. Single model, so out.c is identically zero (verified: ||out.c|| = 0.000000), no gm model reordering, no component sharing. Ground truth is the model's own ng.transform(data). Compared per-component by best |corr|, which is invariant to the per-component scale, sign and permutation that loadmodout legitimately introduces (it normalises to unit-norm A columns and variance-reorders):

candidate mean |corr| min n > 0.999
out.W[:, :, 0] @ sphered 0.877 0.47 0/32
out.W[:, :, 0].T @ sphered 0.932 0.81 0/32

where sphered = out.S[:out.num_pcs] @ (data - out.data_mean[:, None]).

If out.W were simply a normalised, variance-reordered AMICATorchNG.W, one of these should hit |corr| ~ 1.000 for all 32 components, because correlation already quotients out exactly the transformations loadmodout applies. Neither does. 0.88/0.93 is "close but not it" (random would be ~0.1-0.2 in 32 dimensions), so this is not a permutation or scaling artefact.

Reproduced on a 2-model fit too (0.85 / 0.83 for model 0, 0.77 / 0.75 for model 1), with the gm model pairing explicitly checked and identity.

Why this is not obviously a bug

loadmodout is verified bit-exact against EEGLAB's real loadmodout15.m on the genuine Fortran fixture and on pyAMICA-written output, single- and multi-model (.context/issue-155/matlab_interop_verification.md, .context/issue-136/matlab_viz_verification.md). Issue #92 separately verified the mixture-parameter layout through a MATLAB round-trip. So out.W is correct in the EEGLAB sense. The A @ (out.W @ sphered) reconstruction identity also holds to ~1e-15.

So the question is not "is loadmodout broken" but: what exactly is out.W relative to AMICATorchNG.W, and what is the correct way to derive source activations from an AmicaOutput?

Why it matters

Anyone reconstructing sources from a loaded fit (rather than a live model) needs this: PMI/MIR on a saved fit, activation histograms, ERP-style analyses, any downstream EEGLAB interop. There is currently no supported accessor, so callers hand-roll it — and hand-rolling it is demonstrably error-prone (see below).

AMICATorchNG.transform (torch_impl/core.py:1909) does self.W[:, :, m].T @ (X_t - self.c[:, m]), matching the E-step at torch_impl/core.py:828 and the Fortran's b = W(x - c). That formula is correct for the live model. It does not port to AmicaOutput, and it is not currently known what does.

Relevant convention facts

  • loadmodout normalises A by COLUMNS (A[:, i, h] /= na) but W by ROWS (W[i, :, h] *= na), with mu[:, i, h] *= na, sbeta[:, i, h] /= na (numpy_impl/load.py). It variance-reorders W's rows (W[:, :, h] = W[idx, :, h]) alongside A/mu/sbeta/alpha/rho columns.
  • A = pinv(W @ S) (load.py ~332), which ignores c entirely. This makes the A @ (W @ sphered) reconstruction identity circular as evidence about c: A and W @ S are inverse by construction.
  • Fortran c is SPHERED-CHANNEL indexed, not component indexed. Established from amica15.f90:1979: call DGEMV('N',nw,nw,1.0,W(:,:,h),nw,c(:,h),1,0.0,wc(:,h),1) computes wc = W @ c, and wc(i,h) is then consumed component-indexed (b(:,i,h) = -wc(i,h)). So loadmodout NOT reordering c by the per-component variance index is correct.
  • c is identically zero for n_models=1, so this only bites multi-model.

The open sub-question: should c be subtracted?

Unresolved. The fit centres (b = W(x - c)), so mu/sbeta describe the centred variable, which argues for subtracting. But the shift is material, not negligible: measured |wc| / std ~= 0.197 mean, 0.535 max (2-model, 40 iters), with |wc| (5.3) comparable to |mu| (13.6). Yet the fitted mixture mean sum(alpha*mu) ~= 0.01 ~= 0, whereas E[b] = -wc ~= -5.3 would be expected if mu described the centred variable. That inconsistency is itself unexplained and may be the same root cause.

Warning: three natural tests are all degenerate here

Recorded because each one produced a confident wrong or useless answer during triage, and the next person will reach for them:

  1. Activation mean vs fitted mixture mean — degenerate. The fitted mixture is near-symmetric (alpha=[0.32,0.393,0.287], mu=[-22.79,0.36,24.95] gives sum(alpha*mu) ~= 0.01), so with E[sphered]=0 the no-c formula matches trivially (0 ~= 0) regardless of correctness.
  2. Best-match correlation vs transform() — cannot discriminate c at all: Pearson correlation is shift-invariant, so it returns bit-identical numbers with and without c (0.849780 both). It only discriminates the transpose.
  3. L1 between the activation histogram and the fitted PDF — too insensitive: it ranked no-c better (0.297 vs 0.326), but a 20%-of-spread shift should produce a far larger gap than 10%, so it is likely dominated by the unconverged fit rather than by the shift. (It was also silently invalid until the gammaln fix, since the "density" integrated to -8.82.)

A discriminating test needs something the symmetry does not wash out: quantile/CDF comparison against the fitted mixture, a deliberately asymmetric source, or a direct algebraic derivation of out.W from AMICATorchNG.W through write_amicaout -> loadmodout.

Acceptance

  • A definitive, derived (not guessed) statement of what out.W is relative to AMICATorchNG.W, including how the #24 internal transpose interacts with the C-order write and loadmodout's row-normalise + variance-reorder.
  • A definitive answer on whether c must be subtracted when deriving activations from an AmicaOutput, and an explanation of the sum(alpha*mu) ~= 0 vs E[b] = -wc discrepancy.
  • Ideally a supported accessor (e.g. AmicaOutput.sources(X, model=0)) so nobody hand-rolls this again. Related: Phase 5: wire MIR/PMI into the AMICA API #137 (Phase 5) exposes model.mir() / model.pmi() for the live-model case; this is the loaded-fit counterpart.
  • A non-degenerate regression test locking it in.

Blocks plot_topo_pdf (scalp topography + generalized-Gaussian mixture PDF overlay), which was deferred out of #136 for exactly this reason. The other two Phase 4 plots are unaffected: they never touch raw data or sources.

Activity

  1. added
    bug
    on Jul 17, 2026
  2. changed the title [-]Define how to derive source activations from an AmicaOutput (loadmodout W convention)[/-] [+]loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output)[/+] on Jul 17, 2026
  3. neuromechanist commented on Jul 17, 2026

    @neuromechanist
    MemberAuthor

    RESOLVED as a real bug, with a non-circular oracle

    The framing in the issue body ("what IS out.W?") is now answered: loadmodout reads W, sbeta and rho in the wrong byte order. The writer writes all of them order="F"; the reader uses order="F" for alpha/mu but C order for W (load.py:174), sbeta (:278) and rho (:292).

    The oracle that settles it

    Every test I tried first was degenerate (see the issue body). The one that works: recompute the Fortran's own reported converged LL from its own written parameters. Log-likelihood is not transpose-symmetric, so unlike A @ W == I (which both conventions satisfy, since A@W=I implies Aᵀ@Wᵀ=I), it discriminates. On the genuine bundled sample_data/amicaout, whose LL file reports -3.4018730:

    W order mixture order recomputed LL |diff|
    F F -3.4018468 0.00003
    C F -3.5167152 0.115
    F C -3.5024789 0.101
    C C -3.5539805 0.152

    F/F reproduces the Fortran's own number to 5 significant digits (residual is the Fortran's block truncation). The shipped combination does not.

    Independently confirmed for the mixture params by a pairing test (loaded[:, i] == live[:, origord[i]], which unlike a sorted-multiset comparison can see a permutation):

    • alpha (reader uses order="F"): True, max diff 0.0
    • rho (reader omits it): False, max diff 0.969

    Two distinct bugs, different provenance

    1. sbeta/rho read C-order — new, undocumented, corrupts values. Drop-in EEGLAB AMICA replacement: equivalent output, no extra interpretation #92's MATLAB round-trip caught exactly this class for alpha/mu/c/comp_list and fixed them; sbeta/rho were missed. Bites whenever num_mix > 1 (default 3).
    2. W read C-order — known and documented in .context/scratch_history.md as a deliberate out-of-scope quirk, on the stated premise that it "does NOT corrupt values ... and nothing consumes those fields for correctness". That premise no longer holds: A = pinv(W @ S) is derived from the wrong-orientation W, so out.A, out.svar and out.origord are wrong too, and Phase 4: MIR/PMI visualizations #136/Phase 5: wire MIR/PMI into the AMICA API #137 need exactly those fields to derive sources. Note the scratch_history claim conflates a writer fact (C-order bytes are Fortran-identical, and only for num_models=1) with a reader consequence.
    3. Probable third: write_amicaout writes W C-order (load.py:121), which is a valid Fortran dump only for num_models=1. Not independently reverified here, but consistent with the above and worth checking as part of the fix.

    Why every gate missed it

    Phase 3's MATLAB interop gate verified Lht/Lt/v/mod_prob bit-exactly against the real loadmodout15.m — it never compared W/sbeta/rho. #92's round-trip covered the mixture params it knew about. And a pyAMICA-write -> pyAMICA-read round trip cancels the W error, so no self-consistency test can see it. It takes an external oracle (the Fortran's own LL, or MATLAB reading our bytes).

    Not affected

    • Phase 4's shipped plots (plot_pmi_heatmap, plot_model_probability): they use only out.Lht, which is read order="F" and verified bit-exact vs MATLAB. Confirmed by grep: out.Lht is the only AmicaOutput field viz.py touches.
    • Phase 3's LLt writer/reader: Lht/Lt are order="F" and MATLAB-verified.
    • The fit path and Fortran parity: nothing in the fit reads these files.
    • pyAMICA.metrics: operates on caller-supplied arrays.

    Acceptance (supersedes the issue body's)

    • W, sbeta, rho read order="F"; writer's multi-model W checked.
    • Regression test using the LL oracle above: recomputing the bundled Fortran fixture's LL from loadmodout's output must land within ~1e-4 of its own LL file. That is external, non-circular, and would have caught all of this.
    • A MATLAB gate comparing W/A/sbeta/rho against loadmodout15.m, not just Lht/Lt/v.
    • Then plot_topo_pdf (Phase 4: MIR/PMI visualizations #136) can be built on it, with the histogram responsibility-weighted (the per-model mixture describes the v_h-weighted distribution, so a pooled histogram is misaligned even with a correct W and c).
    • c SHOULD be subtracted when deriving activations (out.W @ (sphered - out.c[:, m])), and c is sphered-channel indexed, so loadmodout not variance-reordering it is correct. Both hold only once the loader is fixed.
  4. added 2 commits that reference this issue on Jul 17, 2026
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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions