Skip to content

Fix numpy_impl share_comps A-update and NaN mixture parameters - #257

Merged
neuromechanist merged 8 commits into
devfrom
240-numpy-share-comps-parity
Aug 23, 2026
Merged

neuromechanist merged 8 commits into
devfrom
240-numpy-share-comps-parity

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 22, 2026 •

Copy link
Copy Markdown
Member

numpy_impl's share_comps path diverged from both Fortran and AMICATorchNG in three ways, all of them reachable only after a merge and none of them on the default disjoint comp_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-stepped A. Fortran builds a single dAk as a gm-weighted average across contributing models, divides by zeta = sum_h gm[h], and applies it once (amica15.f90:1749-1761 build, DAXPY at :1807/:1814). numpy_impl now builds that same dAk -- 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 exactly gm[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 unless share_comps merged one, which is what keeps the default multi-model trajectory byte-for-byte (evidence below).

Post-merge A-freeze (#242). Ported from AMICATorchNG._a_frozen with the same anchor and the same 6-iteration duration: A is 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). dAk and 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, and W is rebuilt from the merged comp_list (Fortran runs identify_shared_comps before get_unmixing_matrices, amica15.f90:1840,1845) instead of leaving the next E-step reading a stale W.

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 with np.errstate -- and that suppression also hid a genuine 0/0 in a live column. The live columns are now indexed out instead (cols is 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. rho is held on dead columns too, matching AMICATorchNG; 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/beta while 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() sets converged=False with a stop_reason naming what went non-finite (mirroring the PyTorch wrapper's degenerate-fit contract, #50, on the two fields AMICA_NumPy already had), and _write_checkpoint() gates every write site, periodic writestep/histstep checkpoints 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 with writestep=1 persisted NaN mu that loadmodout read back without complaint -- the run's only on-disk artifact was corrupt. Verified both ways on real sample data: with the gate removed, the loaded mu is non-finite; with it, the on-disk output is clean.

Checkpoint cadence now matches the reference (#240). writestep/histstep are anchored on the Fortran-style 1-indexed iteration (mod(iter, writestep) == 0, amica15.f90:1124/1130), so the first checkpoint lands at iteration writestep. The 0-indexed transcription satisfied iter % writestep == 0 at iteration 0, so every fit wrote a checkpoint after its first iteration whatever writestep said -- 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 default writestep=100 previously left an iteration-1 checkpoint on disk and now leaves only fit()'s final write, which is unconditional for a converged fit. Recorded in docs/changelog.md.

Configuration validation, the same values and reasons as AMICATorchNG: share_start >= 1, share_int > 6, comp_thresh in (0, 1]. share_int <= 6 is the one that matters -- the freeze window is 6 iterations, so a shorter cycle would hold A frozen 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 at share_int=7.

Bit-identity evidence

Hard invariant: with sharing off, and with share_comps=True whose 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 clean dev checkout and on this branch, comparing repr() of every LL and every gradient norm.

series dev vs branch
n_models=2, sharing off: ll identical (all 10)
n_models=2, sharing off: nd identical (all 10)
n_models=1: ll, nd identical (all 10)
n_models=2, share_comps=True, share_start=100 (never fires): ll, nd identical (all 10)

The two-model LL history, byte for byte on both sides:

 1  -3.332140312824202
 2  -3.281619886883841
 3  -3.2700028370394607
 4  -3.254485434653656
 5  -3.2373356296933875
 6  -3.2212060218233027
 7  -3.2070263521453626
 8  -3.195502720740207
 9  -3.186382960955939
10  -3.179138156406066

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=True with 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.py on 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's share_int=2)
  • test_sharing_leaves_finite_mixture_parameters -- the numpy_impl share_comps produces NaN mu/beta and reports success #240 reproduction: finite A/mu/beta/gm/alpha/rho, converged is True, and no divide/invalid RuntimeWarning raised during the fit
  • test_unused_columns_keep_their_last_finite_value -- mu and rho unchanged on dead columns, not merely finite
  • test_non_finite_parameters_are_reported_as_failure -- a live component's mass zeroed on the final iteration: LL stays finite, converged is False, stop_reason names mu, 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 both
  • test_merged_away_column_does_not_move
  • test_a_frozen_window_matches_the_torch_schedule, test_a_frozen_is_off_for_a_single_model, test_freeze_holds_A_but_still_measures_the_gradient
  • test_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 one
  • test_forced_merge_fit_is_finite_in_both_backends -- end to end, NumPy and PyTorch
  • test_checkpoints_never_persist_non_finite_parameters -- the reviewer's scenario: collapse injected at iteration 2 of 4 with writestep=1 into a tmp_path outdir; the pre-collapse checkpoint survives intact, every array loadmodout reads back is finite, and the skip is logged with the parameter name

test_numpy_grad_norm.py's shared-column scaffolding merged comp_list but left comp_used all-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 auto gives 403 passed, 17 skipped, 1 xfailed (after merging dev, which brought #256 and #252). The three remaining warnings are pre-existing slogdet warnings in test_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_value compared a frozen column exactly, but the rescale pass normalizes every column including dead ones, so their mu moves 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 disables doscaling, 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.md records the deliberate divergences this creates: frozen (rather than NaN-behind-comp_used) merged-away columns, the share_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

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
@neuromechanist
neuromechanist merged commit 0b6871a into dev Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the 240-numpy-share-comps-parity branch August 23, 2026 00:12
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.

numpy_impl share_comps applies a shared column's A-update twice numpy_impl share_comps produces NaN mu/beta and reports success

1 participant