Skip to content

Phase 8: store components as rows and fix sharing - #342

Merged
neuromechanist merged 22 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-334-phase8-component-rows
Sep 23, 2026
Merged

neuromechanist merged 22 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-334-phase8-component-rows

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Every array backend (PyTorch, NumPy, MLX) now stores the mixing matrix with one component per row, A of shape (n_comps, n_channels), the reference's A(nw, num_comps) transposed (ADR 0007).
A component id in comp_list now names the same component in A as in mu, beta, alpha and rho, so share_comps follows the reference's identify_shared_comps:

  • the metric compares the components' scalp maps, pinv(sphere) @ A.T (column comp_list[i, h] is column i of get_sensor_mixing_matrix(h));
  • a merge re-points comp_list and retires the folded row, copying and averaging nothing;
  • the gm-weighted dAk/zeta step averages one component across the models that share it;
  • doscaling rescales each component row once, shared or not, and leaves a merged-away row alone.

Before, the component ids indexed stored columns of each model's block, which hold one sphered channel's loadings, not a component, so both the metric and the merge acted on the wrong vectors.

Part of epic #324; resolves #334 and #343 (both close when the epic merges to dev).

Behavior change

  • Fits with share_comps=True in which a merge fires now differ (toward the reference). Refit them.
  • A scan early in a fit now merges most components, because both models start near the identity and the metric now sees that
    (sample, 2 models, seed 42: 32 of 32 at iteration 8 with comp_thresh=0.95, 24 with 0.99; 24 and 5 at iteration 20).
    The reference's default share_start=100 avoids it; the kitchen-sink and sharing_reduces test recipes were retuned (below).
  • Every fit without a merge is byte-identical to before; the weight-gradient norm ndtmpsum moves by float round-off (it now sums per component row, as the reference sums per component).
  • Initial-A normalization is not part of this phase (Normalize the drawn initial mixing matrix #341); ADR 0006's line now points there.

Byte identity (vs 0930c0e, the epic head with Phase 9 and without this phase, loaded from git in-process)

pamica/tests/test_component_rows.py::test_unshared_fits_are_byte_identical_to_the_column_layout: every fitted array and the log-likelihood trajectory identical (np.array_equal) on real sample data, for
PyTorch, NumPy and MLX, each at n_models 1 and 2 x doscaling on/off x Newton on/off x pdftype 0/1, plus: 2 models with do_reject and Newton; two 3-model configurations; single-model pdftype 2, 3 and 4; four blocks of 1024 samples; a keep_best fit that restores an earlier snapshot (asserted); and best-of-two restarts. NumPy implements only pdftype 0 and has no keep_best, so those cases run on PyTorch and MLX, and test_numpy_rejects_other_pdftypes pins the first reason. 62 cases in all.
ndtmpsum differs by at most 2.2e-16 relative (float64) and one float32 unit (MLX); the test pins it at 2 eps.
The test fails under CI and skips locally only when the commit, git, or a git checkout is missing.

Native oracle from a merged state (AMICA_RUN_FORTRAN=1)

The reference's own scan never merges (Spinv2 is never allocated, so every similarity is NaN; see below), but load_comp_list seeds a merged comp_list.
From a 100-iteration warm two-model state of the sample with three merges seeded, max abs difference vs amica15mac (worst of PyTorch and NumPy):

A mu sbeta LL
1 iteration (worst of on/off) 1.3e-15 2.3e-11 1.4e-14 8.9e-16
3 iterations, doscaling on 4.1e-13 3.7e-9 1.8e-11 4.7e-14
3 iterations, doscaling off 1.5e-12 6.5e-10 1.6e-11 4.6e-14
3 iterations, no merge (noise floor) 1.9e-12 1.4e-8 1.9e-10 8.0e-15
3 iterations, old column semantics (on / off) 0.204 / 0.21 3.5e-4 / 4.3e-4

Summarized as the worst of doscaling on and off (ADR 0007, changelog): after 3 iterations A 1.5e-12, mu 3.7e-9, sbeta 1.8e-11, LL 4.7e-14; the old column semantics was off by 0.21 in A and 4.3e-4 in LL.

The oracle keeps maxrho=1.99: the reference's rho == 2 branch normalizes with the single-precision literal log(dble(1.772453851)), 3.0e-8 off log(sqrt(pi)) (2.8e-9 in LL on this state; recorded as row 16 of the differences page, issue #344).

End to end (sample, 2 models, seed 42, Newton, 300 iterations, share_start=100, share_iter=100, comp_thresh=0.95)

final LL merges (map |cos|)
sharing off -3.338683 none
pre-change (column metric) -3.348370 3 (0.062, 0.345, 0.547)
component rows -3.341568 3 (0.971, 0.956, 0.970); each group's sources have identical mixing vectors

0 Newton fallbacks in each run.

Persistence policy

  • PyTorch state_dict is format_version 4, MLX save format 2; both convert through pamica.component_layout.rows_from_legacy_columns.
  • A version 3 (PyTorch) or 1 (MLX) payload with an unmerged comp_list is converted without loss (every block carries over element for element; sources, accessors and exports match the saved model exactly).
  • One whose comp_list shares a component across models raises ValueError asking for a refit (its merges were made under the column semantics).
  • AMICA.save stays at version 2 and goes through the same conversion and refusal. All of this is tested against payloads written by the pre-change classes loaded from git.

EEGLAB export

A is written in the reference layout for every model count ((nw, num_comps) column-major, the bytes of the component-row A in C order); single-model export directories are byte-identical to the pre-change export for every file.
load_results reads that layout and refuses an A that does not invert the W beside it (a multi-model directory written before this change), with the remedy in the message.

Existing tests changed

Every change keeps the test's intent; none loosens a tolerance.

  • torch_tests/test_ng_sharing.py: _controlled_ng stores the given matrix as A.T (its columns are the component vectors, as before); the shape assertion is (n_comps, n_channels); the shared-group consistency check now also asserts every grouped source has the identical mixing vector; the pinv-vs-inv metric check uses A.T.
    test_sharing_reduces_unique_count_without_degrading_ll: comp_thresh 0.9 -> 0.99, because the correct metric merged most components at iteration 8 and the losing model collapsed to a non-finite LL; at 0.99 it merges five at iteration 8 and one at 18.
  • mlx_tests/test_mlx_kitchen_sink.py: share_start 4 -> 8 and comp_thresh 0.9 -> 0.99, same reason (the old recipe merged 27 of 32 and gave a non-finite mu); the winning restart's first scan still merges (six).
  • mlx_tests/test_mlx_sharing.py: shape and consistency checks as above; the merged-away freeze test reads rows of A and now runs with doscaling on (a retired row's scale is exactly 1, so the exact comparison holds with the rescale; before, it had to turn doscaling off).
  • test_numpy_share_comps.py: planted merges and duplicates copy rows; metric inputs come from _component_sensor_maps(); the hand-built gm-weighted dAk/zeta reference accumulates rows; the two frozen/dead-component tests run with doscaling on and the dead row is now compared exactly (assert_array_equal instead of atol=1e-12).
  • test_mlx_sharing_cross_backend.py: rows, _component_sensor_maps(); the gm_prev discrimination numbers re-measured in the row layout (6.3e-8 fixed vs 5.6e-3 with the post-update gm; the 1e-4 tolerance is unchanged).
  • test_mlx_newton_cross_backend.py: the planted merge copies a row; docstring wording.
  • mlx_tests/test_mlx_inv_guard.py: planted duplicates and the per-model block use rows.
  • mlx_tests/test_mlx_persistence.py: _force_merged_column copies a row; the save format is 2 and A is (n_comps, n_channels); a comment says the shape-drift test drops a channel.
  • mlx_tests/test_mlx_fit_noop.py: the historical (pre-Phase-3) model's A is mapped onto rows with rows_from_legacy_columns before the bit-for-bit comparison; every other array is compared unchanged. Its git fetch --depth 1 now runs only if the commit is missing (see below).
  • test_doscaling_rows.py (Phase 7): row-norm helper reads rows; the column-rule contrast is rebuilt through the column layout and converted back; the shared-component case now asserts the shared row is rescaled once and the merged-away row not at all; the zero/NaN-row test plants component rows; the fb13d76 byte-identity loader is replaced by the shared pre_change.load_pre_change_package (whole package, so no helper module leaks between trees), with the old A converted; the gated oracle maps A through native_oracle.reference_mixing.
  • native_oracle.py: reference_mixing(A) is now the transpose (the reference's A is the row-layout A transposed).

Tests no longer fetch (#343)

pamica/tests/pre_change.py is now the only loader of historical code, and it only reads the repository. It checks the pin with git cat-file -e <sha>^{commit}; when the commit is missing it fails under CI and otherwise skips with the command to run (git fetch origin <sha>, or git fetch --unshallow origin in a shallow clone). Pins must be full SHAs. test_mlx_fit_noop.py, which fetched --depth 1 on every run, now imports its whole pinned package through the helper and is still bit-identical. A repo-wide grep (tests, benchmarks, scripts) finds no other git fetch or --depth call; the ones left are in CI workflows. test_pre_change_loader.py runs the loader behind a git wrapper on PATH that logs its arguments and execs the real git, and asserts that nothing is fetched and the clone's shallow state is unchanged, for a present commit, a missing one locally, and a missing one under CI. The wrapper refuses fetch, pull and every depth or shallow option without running git, so the committed negative control (a fetch sent through _git) is caught and never reaches the repository. Missing git and a non-checkout root (tests run from a wheel or sdist) each fail under CI and otherwise skip with their own message, and an alias cannot be reused for another commit.

Early mass merges are the reference's behavior too

  • The pinned binary with share_comps on runs its scan but never merges: Spinv2 is never allocated, so every similarity is NaN. From pamica's initialization, a scan at iteration 8 leaves comp_list unchanged and reports 64 unique components, even at comp_thresh=0.
  • Its similarity with Spinv2 = Spinv^T Spinv, applied to the binary's own state after 8 iterations from pamica's initialization (2 models, full sample, the reference optimizer), merges exactly the pairs the PyTorch and NumPy scans merge: 32, 32 and 30 at comp_thresh 0.9, 0.95 and 0.99 (identical comp_lists). The 8-iteration states agree to A 2.0e-6 and LL 8.9e-8 (PyTorch), which is the early fit's own sensitivity: pamica against itself with A scaled by 1+1e-15 diverges the same way (LL 6.1e-7 after 8 iterations with 2 models).
  • With share_iter=100 nothing collapses: from the binary's merged state, the reference, PyTorch and NumPy all stay finite for 20 iterations at all three thresholds (LL within 1.1e-5), and pamica's own 28-iteration fits are finite.
  • The recipe that did go non-finite (4096 samples, pamica defaults, share_start=8, share_iter=10, comp_thresh=0.9): 28 merges at iteration 8 and one at 18, then NaN at iteration 20. From pamica's post-scan states (with c zeroed, as load_comp_list requires), the reference's update collapses in step: after the first scan the second model's gm falls from 0.41 to 5.037e-3 in two iterations on both sides; after the second it is exactly 0 after one iteration on both, and the next iteration is NaN on both (the binary prints NaN and reinitializes).
  • Conclusion: not a Phase 8 bug. Documented in the differences guide, ADR 0007 and the changelog; the retuned test recipes stay.

Notes for review

  • The reference freezes A whether or not share_comps is on: amica15.f90:1803 holds the A-update whenever iter >= share_start and mod(iter, share_iter) <= 5, without testing share_comps. Measured: from a seeded state with share_comps=0, share_start=1 and doscaling=0, the binary's A after 2 iterations equals the seed exactly, and moves by 0.041 with share_start=1000. So every default reference run (share_start=share_iter=100) holds A at iterations 100-105, 200-205 and so on, which pamica never does without sharing. pamica/schedule.py's share_freeze docstring calls that path dead in the reference. Out of scope here; reported to the lead for an issue.

  • NumPy's rescale takes the block as np.asfortranarray before the row norms: the old fancy index A[:, idx] was F-contiguous, and NumPy's pairwise summation depends on memory order, so this keeps unshared NumPy fits byte-identical.

  • The merged-state oracle keeps maxrho=1.99, with a comment citing Use the reference's single-precision density constants #344. The same kind of single-precision literal normalizes the pdftype 2, 4 and 1 families (amica15.f90:1333/1359/1371); pamica takes the double values of those decimal literals (computed offsets in the log: 3.7e-10, 2.0e-8, -2.1e-8). Commit 819a5f8 records this as row 16 of the differences page and corrects the _LOG_SQRT_2PI/_LOG_NORM_COSH_* comments that claimed bit-for-bit agreement; whether to adopt the reference's values is Use the reference's single-precision density constants #344.

  • pamica/tests/pre_change.py fetches a pinned commit only when it is missing: an unconditional git fetch --depth 1 in a full clone records the commit as a shallow boundary.

Test plan

  • uv run ruff check --fix . && uv run ruff format ., uv run ty check, typos on changed files
  • uv run pytest pamica/tests -q --no-cov -n 4 -m "not slow" (with CI=1, after the review fixes): 1627 passed, 27 skipped (all opt-in native tests, plus one existing NumPy restart-policy skip), 1 xfailed
  • -m slow (with CI=1, after the review fixes): 10 passed, 2 xfailed (the two existing test_sample_data.py xfail markers)
  • Gated oracles with AMICA_RUN_FORTRAN=1 (merged-state oracle on PyTorch and NumPy with doscaling on and off, the two early-merge tests, Phase 7 doscaling oracles, Phase 9 schedule oracles): 12 passed
  • New test_component_rows.py (byte identity, semantics, export) and test_component_rows_persistence.py (24 passed)
  • End-to-end 300-iteration run above
  • uv run --extra docs mkdocs build --strict
  • New test files with MLX hidden (Linux-like): pass or skip, none fail
  • CI green on 46a8f65 (Linux, macOS Apple Silicon, MNE, lint, ty, typos, build)
  • Epic (with Phase 9, Phase 9: align iteration-schedule gates with the reference #338) merged in 0a3626d: conflicts only in the schedule/component_layout imports and the differences table (Phase 9's row 15 kept, this PR's row now 16); byte-identity pin moved to 0930c0e and the full matrix, Newton included, passes (e9f8d20)
  • Tests make the local clone shallow #343: test_pre_change_loader.py (10 passed, also with CI set), including the committed negative control, whose fetch the wrapper refuses before any git runs; git rev-parse --is-shallow-repository prints false afterward
  • Review fixes: test_component_layout.py (11 passed: every rows_from_legacy_columns ValueError branch and the new dtype check), truncated-A load_results test (2 passed), widened byte-identity matrix (62 cases), MLX save-again tail (2 passed)
  • Early mass merges vs the reference: test_the_reference_scan_never_merges, test_an_early_mass_merge_collapses_the_reference_too (gated, pass)

pamica/tests/pre_change.py imports the whole package at a pinned commit
from git under a private name, so byte-identity tests can compare the live
backends with the pre-change ones in one process. It fetches only when the
object is missing (a --depth 1 fetch in a full clone makes it shallow), and
fails under CI but skips locally when the commit is unreachable.
All three backends now hold A as (n_comps, n_channels): row k is the
reference's column A(:, k), and model h's block is A[comp_list[:, h], :],
the same matrix as before, so W = inv(block) is unchanged (issue #334).
comp_list now indexes components in A as it does in the densities, so:

- the share metric compares pinv(sphere) @ A.T, the components' scalp
  maps, not stored columns of each block;
- a merge ties two components' mixing vectors and densities, and the
  gm-weighted dAk/zeta step averages one component across models;
- doscaling rescales each component row once, shared or not;
- accessors, W, the EEGLAB export (reference layout), load_results and
  the viz helpers follow the new layout.

Fits without a merge are byte-identical on every backend; ndtmpsum moves
by float round-off (it sums per component row, like the reference).
Existing sharing, doscaling and MLX tests are updated to the row layout;
two short sharing recipes are retuned because early scans now merge
most components. Tested: full non-slow suite and slow tests.
The PyTorch state_dict is now format_version 4 and the MLX save format 2.
A version 3 (PyTorch) or 1 (MLX) payload is converted through the shared
pamica.component_layout.rows_from_legacy_columns: without loss when its
comp_list is unmerged, and refused with a request to refit when a
component id is shared across models, since that merge was made under
the old column semantics. AMICA.save files (still version 2) go through
the same path.

Tested with test_component_rows_persistence.py (24 passed): round trips
in the new formats, and payloads written by the pre-change classes
loaded from git, converted or refused.
load_results now checks that each model's block of A inverts the W
written beside it (max |A_h W_h - I| <= 1e-3; measured at most 3.8e-7
for float32 MLX exports and 1.1e-15 for float64). A multi-model
directory written before issue #334 stored A with components as columns
and reads back scrambled (residual 1.5); it is refused with the remedy
instead of handing the viz helpers wrong sensor maps. Single-model
files are the same bytes in both layouts and still load.
test_component_rows.py pins, on the sample EEG:
- byte identity of every unshared configuration against the pre-change
  package (3627a6e) on PyTorch, NumPy and MLX: 1-3 models, doscaling,
  Newton, pdftype 0/1 and do_reject;
- the metric compares get_sensor_mixing_matrix columns, a planted
  duplicate merges, and a merged group shares one mixing vector;
- the EEGLAB A file is the reference layout, single-model exports are
  byte-identical, and load_results refuses a pre-change multi-model A;
- opt-in (AMICA_RUN_FORTRAN=1): updates from a merged load_comp_list
  state match amica15mac to float64 round-off on PyTorch and NumPy,
  with doscaling on and off.
All pass locally, including the gated oracle.
ADR 0007 records the row layout, the sharing semantics that follow from
it, the persistence and export policy, and the measured evidence; ADR
0006 and 0001 are amended, and ADR 0006's initial-A normalization line
now points to issue #341. The changelog, the differences page (sharing
rows, a new section for issue #334, and row 15: the reference's
single-precision density normalizers), and the backends, EEGLAB,
validation and API pages describe the new behavior. mkdocs build
--strict passes.
Docstring text only; no test logic changes.
The merged-save refusal test's wrapper route fitted an MLX model without first checking MLX was installed, so it failed on the Linux runner. _wrapper_fit now performs the check for every wrapper route. Tested with MLX hidden: the new test files pass or skip.
…-class' into feature/issue-334-phase8-component-rows

# Conflicts:
#	docs/guides/amica-differences.md
#	pamica/mlx_impl/core.py
#	pamica/torch_impl/core.py
The pre-change package is now 0930c0e, the epic head with Phase 9's schedule gates and without this phase, so the two sides differ by the layout change alone. The full byte-identity matrix (Newton included) and the persistence tests pass against it: 92 passed, 2 gated oracle tests skipped.
Tests that load historical code ran `git fetch origin <sha> --depth 1`,
which in a full clone records a shallow boundary that gc can prune
behind (issue #343). pre_change.py now only reads: it checks the pin
with `git cat-file -e` and, when the commit is missing, fails under CI
and otherwise skips with the command that fetches it (`git fetch origin
<sha>`, or `git fetch --unshallow origin` in a shallow clone). Pins must
be full SHAs.

test_mlx_fit_noop.py, the last loader that fetched, now imports the
whole package at its pin through the same helper; its fits are still
bit-identical. test_pre_change_loader.py runs the loader behind a git
wrapper that logs its arguments and execs the real git, and asserts no
fetch ran and the shallow state is unchanged (a negative control with a
real fetch trips the assertion). Tested: loader and fit-noop tests pass,
also with CI set.
The reference writes its density normalizers as dble(<literal>), which
gfortran reads in single precision: log(dble(1.772453851)) in the
rho == 2 branch is 3.0e-8 above log(sqrt(pi)) (measured in the seeded
oracle), and the Gaussian and cosh families' normalizers differ from
pamica's double values by 3.7e-10, 2.0e-8 and -2.1e-8 (computed).
Row 16 of the differences page records this, citing issue #344, which
decides whether to adopt the reference's values. The torch and MLX
comments that called _LOG_SQRT_2PI and _LOG_NORM_COSH_* bit-for-bit
with the binary are corrected, and the merged-state oracle's
maxrho=1.99 cites the issue. Comments and docs only.
With share_comps on, the pinned binary's scan runs but never merges:
Spinv2 is never allocated, so every similarity is NaN, even at
comp_thresh=0. Its similarity (Spinv2 = Spinv^T Spinv) applied to its
own state after 8 iterations from pamica's initialization merges exactly
the pairs the torch and NumPy scans merge (32, 32 and 30 at 0.9, 0.95
and 0.99). In the recipe that went non-finite, the reference's update
from pamica's post-scan states collapses in step: the second model's
gm falls to 5.04e-3 on both after the first scan, and after the second
reaches zero in one iteration and NaN in the next.

Two gated tests pin this (AMICA_RUN_FORTRAN=1, both pass). The
differences page, ADR 0007, the changelog, the validation table and the
torch/MLX comments that called the scan unrunnable now say what it does.
pre_change.py now fails under CI, and otherwise skips, with its own
message when git is not installed (instead of a raw FileNotFoundError)
and when the tests do not run from a git checkout (instead of advising
a fetch that cannot help). The repository root is a parameter, and a
cached alias must map to the same commit or loading raises.

The test's PATH wrapper now refuses fetch, pull and every depth or
shallow option without running git, so the committed negative control
(a fetch sent through _git) is caught by _assert_no_fetch and leaves the
clone untouched. New tests cover missing git, a non-checkout root and
alias reuse. Tested: 10 passed, also with CI set; the clone is not
shallow afterward.
rows_from_legacy_columns now refuses a non-integer comp_list (float or
NaN ids) with its own ValueError before the bounds check, instead of
letting it reach the indexing. test_component_layout.py adds direct
unit tests on small arrays for every ValueError branch: the comp_list
rank, the dtype, the A shape, an out-of-range id, an id repeated within
a model, and an id shared across models (the refit message), plus a
block-for-block conversion of an unmerged, permuted comp_list.
Tested: 11 new tests pass; persistence tests unchanged.
load_results now checks that the A file holds num_comps * nw values
before reshaping it to (num_comps, nw), and names the file and both
counts when it does not. Before, a length no reshape accepts surfaced
as a bare NumPy reshape error, and one short by a whole component
reshaped to the wrong width and failed later as a matrix-product error.
Tested on truncated copies of a real two-model export (both cases).
The fitted-A and outdir preconditions of AMICA_NumPy._write_results are
now explicit RuntimeErrors, since assert is stripped under python -O.
The comment above them also said the reference omits A from its
output; the binary does write it, in the layout pamica now writes.
Tested: NumPy write and load tests pass.
The unshared byte-identity test now also covers the Gaussian, logistic
and sub-Gaussian cosh families (pdftype 2, 3 and 4, single model, n_mix
1 for family 4), four blocks of 1024 samples, a keep_best fit whose
log-likelihood falls so the safeguard restores an earlier snapshot
(asserted), and best-of-two restarts, on every backend that supports
each. The NumPy backend has only the generalized Gaussian and no
keep_best, so those cases run on PyTorch and MLX; the test says so and
test_numpy_rejects_other_pdftypes pins the first reason. The helper now
lets a configuration override its defaults, and compares final_ll_.
Tested with CI=1: 66 passed.
test_old_mlx_save_converts_losslessly now saves the converted model
again, checks the file is format 2 with a component-row A, reloads it,
and compares A and every output with the saved model, as the torch test
does: a second load must not convert the already-converted A again.
Tested: both recipes pass.
The torch _identify_shared_comps docstring cited Spinv's allocation at :551; it is amica15.f90:569. A test_mlx_newton docstring said merged-away columns and curvature not indexed by mixing column; with components as rows the words are component and mixing vector. Comments only.
ADR 0007 and the changelog now say the 3-iteration oracle figures are the worst of doscaling on and off, and give the old column semantics' error as the matching worst value (A 0.21, LL 4.3e-4, not 0.20 and 4e-4); the test comment lists both measurements. Docs and comments only.
AGENTS.md and .context/progress_summary.md described the old column metric and merge as working. They now describe the component-row semantics (ADR 0007, #334): the metric compares de-sphered component mixing vectors, the merge ties components, and the reference binary's own scan never merges because Spinv2 is never allocated. Docs only.
@neuromechanist
neuromechanist merged commit 5b6ae4f into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-334-phase8-component-rows branch September 23, 2026 11:10
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.

1 participant