Repository navigation
Fix numpy_impl share_comps A-update and NaN mixture parameters - #257
Merged
Merged
Conversation
A column shared by two models took one step per contributing model, the second against an already-stepped A, instead of Fortran's single averaged DAXPY (amica15.f90:1749-1761, :1807). Build one gm-weighted dAk and apply it once, port the 6-iteration post-merge A-freeze from AMICATorchNG, and reject the share settings that would freeze A permanently. The merge schedule now uses the same 1-indexed anchor as the PyTorch backend and rebuilds W from the merged comp_list. Weights are normalized per model (gm[h]/zeta), so a single-contributor column has weight exactly 1.0 and the default trajectory is bit-identical. Refs #242
The mixture update computed every column's ratio and masked the dead ones with np.where, so a merged-away column's 0/0 was evaluated and had to be silenced with np.errstate -- which also hid a genuine 0/0 in a live column. Index the live columns out instead: the dead ones are never divided, nothing is suppressed, and a live collapse still warns. rho is now held on dead columns too, matching AMICATorchNG. Refs #240
A finite likelihood is not proof of a usable fit: a collapsed mixture component can leave NaN in mu or beta while the reported LL stays finite, which fit() returned as a success. Check the fitted parameters at exit and set converged=False with a stop_reason naming them, mirroring the PyTorch wrapper's degenerate-fit contract; nothing is written in that case. Also record the two share_comps divergences from the reference in docs/guides/amica-differences.md. Refs #240
Real sample EEG throughout, merges forced by construction so no test can skip under the bug it guards. Covers: the issue #240 reproduction is finite and raises no divide warning; a degenerate ending reports failure; the shared column takes Fortran's single gm-weighted step (asserting the sequential loop is a materially different result, not a rounding difference); merged-away columns hold; the A-freeze window and its gradient measurement; and cross-backend agreement with AMICATorchNG on the shared column from matched state. Refs #240, #242
The gm-ordering scaffolding merged comp_list but left comp_used all-True, so the merged-away column was marked live and its empty statistics were divided 0/0 -- the stale-mask state of issue #240, now visible as a warning since the dead columns are no longer silenced. Derive the mask from the merged list, as a fit-time merge does. Refs #240
The degenerate-fit guard only covered fit()'s final write. The periodic writestep/histstep checkpoints had no finiteness gate, so a state that went non-finite mid-fit was persisted and read back by loadmodout without complaint -- and because the 0-indexed loop counter satisfies iter % writestep == 0 at iter 0, essentially every fit wrote a checkpoint after its first iteration whatever writestep said. Extract _nonfinite_params() as the single definition of a persistable state, used by fit()'s outcome and by _write_checkpoint(), which skips a degenerate write with a loud log naming the parameter and leaves the last valid output untouched. Anchor writestep/histstep on the Fortran-style 1-indexed iteration (amica15.f90:1124/1130) so the first checkpoint lands at iteration writestep, as in the reference. Refs #240
Reproduces the reviewer's scenario on real sample EEG: a component collapsing at an early iteration with writestep=1 used to persist NaN mu to disk (verified: with the gate removed, loadmodout reads back non-finite mu; with it, the on-disk output is clean). Asserts the pre-collapse checkpoint survives intact, every array read back is finite, and the skip is logged with the parameter name. Also drops doscaling in the frozen-column test -- the rescale pass normalizes dead columns too, so their mu moves by a ULP and the exact comparison failed on Linux but not macOS -- relaxes the cross-backend dead column to the same 1e-12 tolerance for the same reason, and corrects the comment claiming a large writestep meant no intermediate write. Refs #240
This was referenced Aug 23, 2026
Merged
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.
numpy_impl'sshare_compspath diverged from both Fortran andAMICATorchNGin three ways, all of them reachable only after a merge and none of them on the default disjointcomp_list. This PR brings the NumPy backend onto the same algorithm as the PyTorch one and makes a degenerate ending impossible to mistake for success.What changed
One
gm-weighted A step per shared column (#242). The A-update was a per-model loop, so a column shared by two models took one step per contributing model, the second against an already-steppedA. Fortran builds a singledAkas agm-weighted average across contributing models, divides byzeta = sum_h gm[h], and applies it once (amica15.f90:1749-1761 build, DAXPY at :1807/:1814).numpy_implnow builds that samedAk-- the one it already built for the gradient norm -- and applies it once.The weights are normalized per model (
gm[h]/zeta) rather than summed and then divided. That is the same average mathematically, but a column with a single contributor then has weight exactlygm[h]/gm[h] == 1.0, so the step is bit-identical to the old per-model update instead of drifting by the ULP a multiply-then-divide round trip can introduce. Every column has exactly one contributor unlessshare_compsmerged one, which is what keeps the default multi-model trajectory byte-for-byte (evidence below).Post-merge A-freeze (#242). Ported from
AMICATorchNG._a_frozenwith the same anchor and the same 6-iteration duration:Ais held for the merge iteration and the 5 after it, along with the lrate ramp and the Newton-fallback bookkeeping that Fortran nests inside the same guarded block (amica15.f90:1785).dAkand the gradient norm are still computed every iteration, frozen or not, because Fortran computes them in the accumulation pass that runs unconditionally. The merge schedule now uses the same 1-indexed anchor as the PyTorch backend, so an identical(share_start, share_int)fires on the same iterations in both, andWis rebuilt from the mergedcomp_list(Fortran runsidentify_shared_compsbeforeget_unmixing_matrices, amica15.f90:1840,1845) instead of leaving the next E-step reading a staleW.Merged-away columns are frozen, and never divided (#240). The mixture update computed every column's ratio and masked the dead ones with
np.where, which meant the 0/0 was evaluated and had to be silenced withnp.errstate-- and that suppression also hid a genuine 0/0 in a live column. The live columns are now indexed out instead (colsis a full slice whenever every column is live, so the ordinary path stays copy-free and bit-identical): a dead column's division never happens, nothing is suppressed, and a live component whose responsibility mass collapses still raises numpy's own warning.rhois held on dead columns too, matchingAMICATorchNG; previously it ratcheted up on its floored denominator every iteration.A non-finite fit no longer reports success, and no write can persist one (#240). A finite likelihood is not proof of a usable fit: a collapsed component can leave NaN in
mu/betawhile the reported LL stays finite._nonfinite_params()is now the single definition of a persistable, reportable state -- it names every fitted parameter holding a non-finite value -- and it gates both outcomes:fit()setsconverged=Falsewith astop_reasonnaming what went non-finite (mirroring the PyTorch wrapper's degenerate-fit contract, #50, on the two fieldsAMICA_NumPyalready had), and_write_checkpoint()gates every write site, periodicwritestep/histstepcheckpoints included. A degenerate checkpoint is skipped with a loud log naming the parameter, and the last valid output on disk is left untouched. No new API.Review follow-up, and the reason that predicate is shared rather than inline: the first version of this PR gated only
fit()'s final write. The periodic checkpoint had no gate, so a component collapsing early withwritestep=1persisted NaNmuthatloadmodoutread back without complaint -- the run's only on-disk artifact was corrupt. Verified both ways on real sample data: with the gate removed, the loadedmuis non-finite; with it, the on-disk output is clean.Checkpoint cadence now matches the reference (#240).
writestep/histstepare anchored on the Fortran-style 1-indexed iteration (mod(iter, writestep) == 0, amica15.f90:1124/1130), so the first checkpoint lands at iterationwritestep. The 0-indexed transcription satisfiediter % writestep == 0at iteration 0, so every fit wrote a checkpoint after its first iteration whateverwritestepsaid -- including fits far shorter than one interval. This is a divergence removal, not a new divergence, and it is observable: a short fit with the defaultwritestep=100previously left an iteration-1 checkpoint on disk and now leaves onlyfit()'s final write, which is unconditional for a converged fit. Recorded indocs/changelog.md.Configuration validation, the same values and reasons as
AMICATorchNG:share_start >= 1,share_int > 6,comp_threshin(0, 1].share_int <= 6is the one that matters -- the freeze window is 6 iterations, so a shorter cycle would holdAfrozen on every iteration of every cycle and the fit would silently stop moving its mixing matrix. This rejects the literal reproduction config from #240 (share_int=2), which is why the reproduction test runs atshare_int=7.Bit-identity evidence
Hard invariant: with sharing off, and with
share_comps=Truewhose schedule never fires, the trajectory must be unchanged. Both were run on the real bundled sample EEG (32 channels, 4096 samples), 10 iterations, seed 13, on a cleandevcheckout and on this branch, comparingrepr()of every LL and every gradient norm.n_models=2, sharing off:lln_models=2, sharing off:ndn_models=1:ll,ndn_models=2,share_comps=True,share_start=100(never fires):ll,ndThe two-model LL history, byte for byte on both sides:
One clarification on the invariant as stated in the issue: the A-freeze fires on its schedule whether or not that cycle's merge pass actually merged a pair, in both this backend and the PyTorch one (that is the reference's behavior, amica15.f90:1785). So
share_comps=Truewith a schedule that fires inside the run does change the trajectory even when no merge happens -- deliberately. The bit-identity claim covers sharing off and a schedule that never fires.Tests
All in
pamica/tests/test_numpy_share_comps.pyon real sample EEG, merges forced by construction so no test can silently skip under the bug it guards.test_share_constructor_validation(5 cases, including numpy_impl share_comps produces NaN mu/beta and reports success #240'sshare_int=2)test_sharing_leaves_finite_mixture_parameters-- the numpy_impl share_comps produces NaN mu/beta and reports success #240 reproduction: finiteA/mu/beta/gm/alpha/rho,converged is True, and no divide/invalidRuntimeWarningraised during the fittest_unused_columns_keep_their_last_finite_value--muandrhounchanged on dead columns, not merely finitetest_non_finite_parameters_are_reported_as_failure-- a live component's mass zeroed on the final iteration: LL stays finite,converged is False,stop_reasonnamesmu, the log says so, and the collapse still raises numpy's warning (the counterpart to the silence on dead columns)test_shared_column_takes_one_gm_weighted_step-- pins Fortran's single weighted application to 1e-12 and asserts the sequential per-model loop differs by more than 1e-3 on the same state, so the test fails against either mistake rather than passing on bothtest_merged_away_column_does_not_movetest_a_frozen_window_matches_the_torch_schedule,test_a_frozen_is_off_for_a_single_model,test_freeze_holds_A_but_still_measures_the_gradienttest_shared_column_update_matches_the_torch_backend-- cross-backend, per.rules/backend_parity.md: both backends driven from one set of parameters and one sphered data matrix, so only the A-update is under test; they agree to ~1e-16 on the shared column (asserted at 1e-12) and exactly on the dead onetest_forced_merge_fit_is_finite_in_both_backends-- end to end, NumPy and PyTorchtest_checkpoints_never_persist_non_finite_parameters-- the reviewer's scenario: collapse injected at iteration 2 of 4 withwritestep=1into atmp_pathoutdir; the pre-collapse checkpoint survives intact, every arrayloadmodoutreads back is finite, and the skip is logged with the parameter nametest_numpy_grad_norm.py's shared-column scaffolding mergedcomp_listbut leftcomp_usedall-True, which is the stale-mask state of #240; it now derives the mask as a fit-time merge does, and that is why its warnings disappear rather than being suppressed.Gates
uv run ruff check .,uv run ruff format --check .,uv run ty check .all clean;uv run pytest -m "not slow" -n autogives 403 passed, 17 skipped, 1 xfailed (after mergingdev, which brought #256 and #252). The three remaining warnings are pre-existingslogdetwarnings intest_sample_data.py, unrelated to this change.One CI-only failure from the first push is also fixed:
test_unused_columns_keep_their_last_finite_valuecompared a frozen column exactly, but the rescale pass normalizes every column including dead ones, so theirmumoves by a ULP whenever the column norm is 1.0 only to within rounding -- it failed on Linux and passed on macOS. The test now disablesdoscaling, and the cross-backend dead-column comparison is at the same 1e-12 tolerance as the rest for the same reason.docs/guides/amica-differences.mdrecords the deliberate divergences this creates: frozen (rather than NaN-behind-comp_used) merged-away columns, theshare_start-anchored freeze window with no bit-exact oracle to check it against, and row 5 now says what is actually true of degenerate output -- the final write is refused and periodic checkpoints are skipped with a logged reason, where the reference writes NaN out on its cadence.Closes #240
Closes #242