Repository navigation
Write LLt from the stashed E-step logV - #297
Merged
Merged
Conversation
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.
Merged
4 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Decision
LLtis now written from the per-samplelogVthe 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 bywrite_output(amica15.f90:2338-2343), so the file on disk is one M-step older than theW/Abeside 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 indocs/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 awritestepcheckpoint, 1146 after the loop). TheLLtwritten 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 theLLtrajectory written beside it. The invariant that expresses this isLt.sum() / (n_good_samples * nw) == LL[-1], wheren_good_samplesis the count that E-step ran over (good_idx.numel()underdo_reject,n_samplesotherwise) — the same normalizationll_historyuses.That is measured, not argued. On the committed reference output
pamica/sample_data/amicaout(produced byamica15mac),sum(Lt)/(N*nw)equals its ownLL[-1]with a residual of exactly 0.0, while the adjacent iterateLL[-2]is 3.7e-5 away.test_fortran_reference_llt_is_the_last_esteppins that on the reference's own bytes;test_written_llt_matches_the_fortran_write_conventionpins the same relation on what each pamica backend writes, read back through the sameloadmodout. A freshly-run-binary variant is gated behindAMICA_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_rejectfit that rejects on its own last executed iteration.llis normalized over the good set as it stood before that rejection, and_reject_outliersthen 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 computesLL(iter) = LLtmp2/dble(numgoodsum*nw)(amica15.f90:1770) beforereject_data(amica15.f90:1138) shrinksnumgoodsum(amica15.f90:2252) and zeroes the rejectedmodloglik/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_iterationschedules 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_rejectionis 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 todo_rejectin 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_loglikreturns on a fit of N-1 iterations, and differs from its own post-updatemodel_loglikby ~29 nats per sample (test_stashed_llt_is_one_m_step_behind_the_written_parameters, and the rewrittentest_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_paramsnow carry the stash alongside the parameters. Because the snapshot is taken immediately after the E-step that measuredbest_lland 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
LLtis the E-step that produced the exportedfinal_ll_, soLt.sum()/(n_good_samples*n_channels) == final_ll_holds either way.test_keep_best_restore_rolls_the_llt_stash_backforces a real restore on real EEG (peak at iterate 57 of 60) and asserts the stash matchesfinal_ll_, notll_history[-1], and thatmodel_loglikon the restored model reproduces the exportedLhtexactly.Performance
Bundled 32-channel sample (30504 samples), float64, torch-CPU, median of 5:
_write_results(onewritestepcheckpoint)write_amica_outputfit()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, sincen_channels >> n_models + 1in any real fit. Thekeep_bestsnapshot clones it once per improving iteration, negligible against the E-step'sO(n_samples * n_channels^2 * n_mix).Notes
The per-sample values are genuinely reused, not recomputed:
_get_block_updatesalready computedlogsumexp(logV, dim=1)on its way to the scalar block LL, and that vector is now kept rather than discarded.block_llis the same summation as before, bit for bit. The values ride out of_get_block_updatesin the returned dict and are popped by_accumulate_blocksbefore the accumulators are folded, so they are never summed and the accumulator dict the cross-backend tests compare is unchanged. The_tune_block_sizeprobes leave the buffers untouched, so the tuner still leaves no state behind.The
do_rejectzero sentinel is unchanged and now arrives the way the reference produces it: rejected samples are zeroed in_reject_outlierson 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_ltasNoneso the existing warn-and-omit path fires, rather than writing an all-zero file thatload_rejwould read as "every sample rejected".test_model_loglik_matches_internal_lhthad 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_rejectthe torch backend's_sample_llstill 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-exactdo_rejectresults.Gates
uv run pytest pamica/tests/torch_tests/ pamica/tests/test_numpy_share_comps.py pamica/tests/test_llt_stash.py pamica/tests/test_sample_data.py -q --no-cov -n auto: 284 passed, 6 skipped, 1 xfailed.uv run pytest -m "not slow" -n auto: 540 passed, 28 skipped, 1 xfailed. The Test mir_history_ against the keep_best rollback and save/load #161mir_history_tests and the Fix numpy_impl share_comps A-update and NaN mixture parameters #257 checkpoint tests are green.ruff check/ruff format --check/ty check: clean, zero new diagnostics.AMICA_RUN_FORTRAN=1 uv run pytest pamica/tests/test_llt_stash.py: 12 passed, including the freshly-run-binary check.