Repository navigation
Phase 8: store components as rows and fix sharing - #342
Merged
neuromechanist merged 22 commits intoSep 23, 2026
Merged
neuromechanist merged 22 commits into
neuromechanist merged 22 commits into
Conversation
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.
This was referenced Sep 23, 2026
…-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
merged commit Sep 23, 2026
5b6ae4f
into
feature/issue-324-epic-mlx-first-class
8 checks passed
This was referenced Sep 23, 2026
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.
Summary
Every array backend (PyTorch, NumPy, MLX) now stores the mixing matrix with one component per row,
Aof shape(n_comps, n_channels), the reference'sA(nw, num_comps)transposed (ADR 0007).A component id in
comp_listnow names the same component inAas inmu,beta,alphaandrho, soshare_compsfollows the reference'sidentify_shared_comps:pinv(sphere) @ A.T(columncomp_list[i, h]is columniofget_sensor_mixing_matrix(h));comp_listand retires the folded row, copying and averaging nothing;gm-weighteddAk/zetastep averages one component across the models that share it;doscalingrescales 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
share_comps=Truein which a merge fires now differ (toward the reference). Refit them.(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=100avoids it; the kitchen-sink andsharing_reducestest recipes were retuned (below).ndtmpsummoves by float round-off (it now sums per component row, as the reference sums per component).Anormalization 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, forPyTorch, NumPy and MLX, each at
n_models1 and 2 xdoscalingon/off x Newton on/off xpdftype0/1, plus: 2 models withdo_rejectand Newton; two 3-model configurations; single-modelpdftype2, 3 and 4; four blocks of 1024 samples; akeep_bestfit that restores an earlier snapshot (asserted); and best-of-two restarts. NumPy implements onlypdftype0 and has nokeep_best, so those cases run on PyTorch and MLX, andtest_numpy_rejects_other_pdftypespins the first reason. 62 cases in all.ndtmpsumdiffers 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 (
Spinv2is never allocated, so every similarity is NaN; see below), butload_comp_listseeds a mergedcomp_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):AmusbetadoscalingondoscalingoffSummarized as the worst of
doscalingon and off (ADR 0007, changelog): after 3 iterationsA1.5e-12,mu3.7e-9,sbeta1.8e-11, LL 4.7e-14; the old column semantics was off by 0.21 inAand 4.3e-4 in LL.The oracle keeps
maxrho=1.99: the reference'srho == 2branch normalizes with the single-precision literallog(dble(1.772453851)), 3.0e-8 offlog(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)0 Newton fallbacks in each run.
Persistence policy
state_dictisformat_version4, MLX save format 2; both convert throughpamica.component_layout.rows_from_legacy_columns.comp_listis converted without loss (every block carries over element for element; sources, accessors and exports match the saved model exactly).comp_listshares a component across models raisesValueErrorasking for a refit (its merges were made under the column semantics).AMICA.savestays 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
Ais written in the reference layout for every model count ((nw, num_comps)column-major, the bytes of the component-rowAin C order); single-model export directories are byte-identical to the pre-change export for every file.load_resultsreads that layout and refuses anAthat does not invert theWbeside 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_ngstores the given matrix asA.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; thepinv-vs-invmetric check usesA.T.test_sharing_reduces_unique_count_without_degrading_ll:comp_thresh0.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_start4 -> 8 andcomp_thresh0.9 -> 0.99, same reason (the old recipe merged 27 of 32 and gave a non-finitemu); 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 ofAand now runs withdoscalingon (a retired row's scale is exactly 1, so the exact comparison holds with the rescale; before, it had to turndoscalingoff).test_numpy_share_comps.py: planted merges and duplicates copy rows; metric inputs come from_component_sensor_maps(); the hand-builtgm-weighteddAk/zetareference accumulates rows; the two frozen/dead-component tests run withdoscalingon and the dead row is now compared exactly (assert_array_equalinstead ofatol=1e-12).test_mlx_sharing_cross_backend.py: rows,_component_sensor_maps(); thegm_prevdiscrimination numbers re-measured in the row layout (6.3e-8 fixed vs 5.6e-3 with the post-updategm; 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_columncopies a row; the save format is 2 andAis(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'sAis mapped onto rows withrows_from_legacy_columnsbefore the bit-for-bit comparison; every other array is compared unchanged. Itsgit fetch --depth 1now 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; thefb13d76byte-identity loader is replaced by the sharedpre_change.load_pre_change_package(whole package, so no helper module leaks between trees), with the oldAconverted; the gated oracle mapsAthroughnative_oracle.reference_mixing.native_oracle.py:reference_mixing(A)is now the transpose (the reference'sAis the row-layoutAtransposed).Tests no longer fetch (#343)
pamica/tests/pre_change.pyis now the only loader of historical code, and it only reads the repository. It checks the pin withgit cat-file -e <sha>^{commit}; when the commit is missing it fails underCIand otherwise skips with the command to run (git fetch origin <sha>, orgit fetch --unshallow originin a shallow clone). Pins must be full SHAs.test_mlx_fit_noop.py, which fetched--depth 1on 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 othergit fetchor--depthcall; the ones left are in CI workflows.test_pre_change_loader.pyruns the loader behind agitwrapper onPATHthat 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 underCI. 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 underCIand otherwise skip with their own message, and an alias cannot be reused for another commit.Early mass merges are the reference's behavior too
share_compson runs its scan but never merges:Spinv2is never allocated, so every similarity is NaN. From pamica's initialization, a scan at iteration 8 leavescomp_listunchanged and reports 64 unique components, even atcomp_thresh=0.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 atcomp_thresh0.9, 0.95 and 0.99 (identicalcomp_lists). The 8-iteration states agree toA2.0e-6 and LL 8.9e-8 (PyTorch), which is the early fit's own sensitivity: pamica against itself withAscaled by 1+1e-15 diverges the same way (LL 6.1e-7 after 8 iterations with 2 models).share_iter=100nothing 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.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 (withczeroed, asload_comp_listrequires), the reference's update collapses in step: after the first scan the second model'sgmfalls 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).Notes for review
The reference freezes
Awhether or notshare_compsis on: amica15.f90:1803 holds the A-update wheneveriter >= share_startandmod(iter, share_iter) <= 5, without testingshare_comps. Measured: from a seeded state withshare_comps=0,share_start=1anddoscaling=0, the binary'sAafter 2 iterations equals the seed exactly, and moves by 0.041 withshare_start=1000. So every default reference run (share_start=share_iter=100) holdsAat iterations 100-105, 200-205 and so on, which pamica never does without sharing.pamica/schedule.py'sshare_freezedocstring 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.asfortranarraybefore the row norms: the old fancy indexA[:, 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 thepdftype2, 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.pyfetches a pinned commit only when it is missing: an unconditionalgit fetch --depth 1in 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,typoson changed filesuv run pytest pamica/tests -q --no-cov -n 4 -m "not slow"(withCI=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(withCI=1, after the review fixes): 10 passed, 2 xfailed (the two existingtest_sample_data.pyxfail markers)AMICA_RUN_FORTRAN=1(merged-state oracle on PyTorch and NumPy withdoscalingon and off, the two early-merge tests, Phase 7doscalingoracles, Phase 9 schedule oracles): 12 passedtest_component_rows.py(byte identity, semantics, export) andtest_component_rows_persistence.py(24 passed)uv run --extra docs mkdocs build --strictschedule/component_layoutimports 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)test_pre_change_loader.py(10 passed, also withCIset), including the committed negative control, whose fetch the wrapper refuses before any git runs;git rev-parse --is-shallow-repositoryprints false afterwardtest_component_layout.py(11 passed: everyrows_from_legacy_columnsValueError branch and the new dtype check), truncated-Aload_resultstest (2 passed), widened byte-identity matrix (62 cases), MLX save-again tail (2 passed)test_the_reference_scan_never_merges,test_an_early_mass_merge_collapses_the_reference_too(gated, pass)