Skip to content

Write LLt from the stashed E-step logV - #297

Merged
neuromechanist merged 7 commits into
devfrom
feature/issue-157-llt-stash
Aug 24, 2026
Merged

neuromechanist merged 7 commits into
devfrom
feature/issue-157-llt-stash

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Decision

LLt is now written from the per-sample logV the training E-step already computes, on both the PyTorch and NumPy backends, instead of being recomputed by a fresh full-dataset forward pass at write time.

This adopts the reference's ordering rather than pamica's previous self-consistent one. modloglik(num_models,N)/loglik(N) are allocated once in the reference (amica15.f90:2619-2620), filled by every E-step (amica15.f90:1406-1411) and dumped verbatim by write_output (amica15.f90:2338-2343), so the file on disk is one M-step older than the W/A beside it. Between #155 and #157 pamica instead recomputed from the post-update parameters, which read better in isolation but was not comparable with the binary's output. Byte-comparability with the reference is this project's definition of correct, so the reference's ordering wins. Decided 2026-08-23; documented as reference-faithful in docs/guides/amica-differences.md.

Closes #157.

Fortran ordering, and the evidence

The reference's iteration is get_updates_and_likelihood (amica15.f90:996) -> update_params (amica15.f90:1122) -> write_output (amica15.f90:1126 for a writestep checkpoint, 1146 after the loop). The LLt written at any point is therefore the E-step of the parameters as they stood before the preceding M-step, and is the E-step that produced the last entry of the LL trajectory written beside it. The invariant that expresses this is Lt.sum() / (n_good_samples * nw) == LL[-1], where n_good_samples is the count that E-step ran over (good_idx.numel() under do_reject, n_samples otherwise) — the same normalization ll_history uses.

That is measured, not argued. On the committed reference output pamica/sample_data/amicaout (produced by amica15mac), sum(Lt)/(N*nw) equals its own LL[-1] with a residual of exactly 0.0, while the adjacent iterate LL[-2] is 3.7e-5 away. test_fortran_reference_llt_is_the_last_estep pins that on the reference's own bytes; test_written_llt_matches_the_fortran_write_convention pins the same relation on what each pamica backend writes, read back through the same loadmodout. A freshly-run-binary variant is gated behind AMICA_RUN_FORTRAN=1 (test_native_binary_llt_is_the_last_estep, verified passing locally against the bundled binary).

The one reference-faithful exception

The equality above holds bit for bit except on a write whose iteration also fired a rejection — for the final write, a do_reject fit that rejects on its own last executed iteration. ll is normalized over the good set as it stood before that rejection, and _reject_outliers then zeroes the dropped samples' stash entries, so the two sides stop counting the same samples. This is Fortran's ordering, not a pamica defect: the reference computes LL(iter) = LLtmp2/dble(numgoodsum*nw) (amica15.f90:1770) before reject_data (amica15.f90:1138) shrinks numgoodsum (amica15.f90:2252) and zeroes the rejected modloglik/loglik (amica15.f90:2232-2234), and the binary shows the same residual on the same schedule.

It is pinned as behavior rather than silenced, on both backends and in both directions. test_llt_invariant_breaks_when_rejection_fires_on_the_last_iteration schedules exactly one rejection on the fit's final iteration and asserts the residual is bounded-but-nonzero — measured 0.0114872 for a pass that drops 68 of 4096 samples, identical to seven digits in torch and NumPy. test_llt_invariant_returns_one_iteration_after_a_rejection is the control: the same rejection with one more iteration after it re-normalizes over the shrunk good set and the residual returns to exactly 0.0, which confines the exception to the case named rather than to do_reject in general. Every "always"/"bit for bit" claim in the docstrings, _llt_arrays, the changelog and the amica-differences entry now carries this caveat.

A second, sharper pin needs no reference at all: a fit of N iterations stashes bit-for-bit what model_loglik returns on a fit of N-1 iterations, and differs from its own post-update model_loglik by ~29 nats per sample (test_stashed_llt_is_one_m_step_behind_the_written_parameters, and the rewritten test_model_loglik_matches_internal_lht).

keep_best semantics

keep_best (#51) is pamica's own; the reference has no counterpart, so the coherent choice had to be made here rather than ported. _snapshot_params/_restore_params now carry the stash alongside the parameters. Because the snapshot is taken immediately after the E-step that measured best_ll and before that iteration's M-step, a restore rolls back the parameters and the LLt to the same point in the loop, and there is no staleness at all in that case.

One sentence covers both paths: the exported LLt is the E-step that produced the exported final_ll_, so Lt.sum()/(n_good_samples*n_channels) == final_ll_ holds either way. test_keep_best_restore_rolls_the_llt_stash_back forces a real restore on real EEG (peak at iterate 57 of 60) and asserts the stash matches final_ll_, not ll_history[-1], and that model_loglik on the restored model reproduces the exported Lht exactly.

Performance

Bundled 32-channel sample (30504 samples), float64, torch-CPU, median of 5:

before after
NumPy _write_results (one writestep checkpoint) 78.1 ms 0.8 ms
torch write_amica_output 13.9 ms 1.1 ms
torch: extra full E-step per fit() 12.8 ms 0

For scale, one torch E-step accumulate pass over the same data is 27.1 ms, so the recompute pamica used to pay once per fit was about half an EM iteration. "Before" is the removed recompute reconstructed verbatim in the same process against the same fitted state, so the delta is this change and nothing else.

The stash costs (n_models + 1) * n_samples * itemsize (~0.7 MB for the bundled two-model case), which grows with the data but stays far below the sphered dataset already resident, since n_channels >> n_models + 1 in any real fit. The keep_best snapshot clones it once per improving iteration, negligible against the E-step's O(n_samples * n_channels^2 * n_mix).

Notes

The per-sample values are genuinely reused, not recomputed: _get_block_updates already computed logsumexp(logV, dim=1) on its way to the scalar block LL, and that vector is now kept rather than discarded. block_ll is the same summation as before, bit for bit. The values ride out of _get_block_updates in the returned dict and are popped by _accumulate_blocks before the accumulators are folded, so they are never summed and the accumulator dict the cross-backend tests compare is unchanged. The _tune_block_size probes leave the buffers untouched, so the tuner still leaves no state behind.

The do_reject zero sentinel is unchanged and now arrives the way the reference produces it: rejected samples are zeroed in _reject_outliers on both backends, mirroring amica15.f90:2232-2234, instead of being arranged at write time. A fit that never completed an E-step (max_iter=0, or a degenerate first iteration) leaves _llt_lht/_llt_lt as None so the existing warn-and-omit path fires, rather than writing an all-zero file that load_rej would read as "every sample rejected".

test_model_loglik_matches_internal_lht had to change: it asserted the old post-update equality, which is exactly the invariant this decision inverts. It now asserts the stronger paired claim described above, and additionally checks the comparison is not vacuous.

One follow-up observed but deliberately not taken here: under do_reject the torch backend's _sample_ll still runs a separate full forward pass to produce the rejection statistic, which the stash could serve for free (the NumPy backend already reads it from the stash). Left alone to keep this change to the write path, since changing the tensor layout the rejection statistic comes from risks perturbing existing bit-exact do_reject results.

Gates

Replaces the write-time full-dataset recompute with the per-sample logV the
E-step already produces, matching Fortran's permanently-allocated
modloglik/loglik. The stash is snapshotted and restored with keep_best, so the
exported LLt is always the E-step that produced final_ll_. Tested.
_write_results now reads the stash instead of recomputing a full forward pass
at every writestep checkpoint (78 ms -> 0.8 ms on the bundled sample). Rejected
samples are zeroed on rejection, mirroring amica15.f90:2232-2234, so the
load_rej sentinel is unchanged. Tested.
Pins the write convention on the committed reference output (its LLt sums to
its own LL[-1] exactly), on both backends' written files, on a freshly-run
binary behind AMICA_RUN_FORTRAN, across backends on matched state, under a
keep_best restore, and that no forward pass runs at write time.
amica-differences.md gains a section on the one-M-step staleness pamica now
inherits from the reference, with the decision (2026-08-23) and its Fortran
citations; changelog, eeglab guide and the wrapper docstring follow.
The invariant normalizes by the GOOD sample count, not n_samples (measured
residual 0.083 vs 4.4e-16 on a do_reject fit), matching the wording already
used in the docs and the numpy backend. Also caveats the one reference-faithful
break: a rejection on the write's own iteration normalizes LL(iter)
(amica15.f90:1770) before reject_data shrinks numgoodsum (:1138, :2252).
Schedules exactly one rejection on the fit's own final iteration and pins the
resulting residual as bounded-but-nonzero on both backends (0.0115 for a
68-of-4096 pass, identical in torch and numpy), paired with a control one
iteration later where the next E-step re-normalizes and the equality returns
exactly. Pins the Fortran-faithful behavior rather than silencing it.
The keep_best pointer named a test and file that do not exist, and a numpy
docstring still referenced the removed _compute_full_posterior_ll.
@neuromechanist
neuromechanist merged commit 06c0e60 into dev Aug 24, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-157-llt-stash branch August 24, 2026 02:07
@neuromechanist neuromechanist mentioned this pull request Aug 25, 2026
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.

Stash per-sample logV during the E-step instead of recomputing for LLt

1 participant