Repository navigation
Phase 1: sensor-space sharing similarity for numpy - #266
Merged
neuromechanist merged 3 commits intoAug 23, 2026
Merged
neuromechanist merged 3 commits into
neuromechanist merged 3 commits into
Conversation
identify_shared_components now takes de-sphered sensor-space maps (pinv(sphere) @ A), mirroring AMICATorchNG._identify_shared_comps and the Fortran identify_shared_comps/Spinv back-map (amica15.f90:1916, :568-578) exactly, instead of comparing raw sphered A columns. Adds a cached, guarded _pinv_sphere() (mirrors AMICATorchNG._pinv_sphere), invalidated wherever self.sphere is reassigned, also used to refactor get_sensor_mixing_matrix. The merge log moves to the call site since the function is now stateless. Updates the two direct callers of the old 4-arg signature and adds cross-backend and rank-reduced sharing tests.
The amica-differences guide's numpy-compares-in-sphered-space passage (added with #256) is resolved: both backends now compare sensor-space maps, so it is rewritten with the current state and a concrete cosine example. Changelog gets one Unreleased bullet.
neuromechanist
merged commit Aug 23, 2026
7c50e83
into
feature/issue-260-epic-mlx-parity
8 checks passed
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.
Summary
Ports the PyTorch backend's sensor-space
share_compsmerge metric to the NumPybackend (issue #258), so both backends make the same merge decision on the
same fitted state.
identify_shared_componentsused to compare mixing columns directly in thesphered space.
It now takes de-sphered sensor-space maps,
pinv(sphere) @ A, mirroringAMICATorchNG._identify_shared_comps(torch_impl/core.py:1696-1741) and theFortran
identify_shared_comps+Spinvback-map (amica15.f90:1916,:568-578) exactly: same loop order (h < hh, theni,ii), sametiny/isfiniteguard on the cosine ratio, same within-model guard placedafter the threshold test, same merge direction (
cjfolds intoci).A new cached, guarded
_pinv_sphere()mirrorsAMICATorchNG._pinv_sphere():built on first use, invalidated wherever
self.sphereis reassigned, andraises a
RuntimeErrornaming a degenerate fit on a non-finite sphere beforenp.linalg.pinvgets a chance to fail more confusingly.get_sensor_mixing_matrix()is refactored onto the same helper.identify_shared_componentsis now a stateless pure function of(atil, comp_list, comp_thresh)(dropped the vestigialWparameter andstopped mutating the caller's
comp_list), so the merge log line(iteration, merge count, unique count) moved to the call site, computed from
the before/after unique-component count.
Load-path invalidation finding (Change 1)
numpy_impl.core.AMICAhas no analogue ofAMICATorchNG._load_params--there is no method that reassigns
self.sphereon an already-constructedinstance.
The only place
self.sphereis ever set is inside_preprocess_data, calledfrom
fit()on a fresh instance.pamica/numpy_impl/load.py'sloadmodout/AmicaOutputis a separate,unrelated class for reading Fortran binary output for validation/plotting; it
never touches
AMICA_NumPy.So
__init__'sself._sphere_pinv = Noneplus the single invalidation siteadded at the end of
_preprocess_data(after all fiveself.sphere =assignment branches) is a complete guard -- no additional invalidation site
was needed.
Evidence
On one real fitted 2-model NumPy state (
test_numpy_merge_decision_matches_torch_backend),after copying
A/mu/alpha/beta/rho/gm/c/sphere/comp_listinto a matchedAMICATorchNG, one scan ofidentify_shared_components(NumPy) and_identify_shared_comps()(PyTorch) atcomp_thresh=0.9produces byte-identicalcomp_lists, with a merge confirmed to have fired (non-vacuous).On a real fitted 2-model state (no forcing), scanning every cross-model
column pair for the maximum cosine similarity: the top candidate pair (model-0
component 19, model-1 component 51) measures 0.9916 in sensor space
(
pinv(sphere) @ A, the new metric) against 0.9701 in the old spheredspace (raw
Acolumns) -- a real, non-trivial shift. With the defaultcomp_thresh=0.99this flips the decision: sensor space would merge thatpair, the old sphered-space metric would not.
Test adjustments
No existing merge-dependent test's
comp_threshneeded lowering --test_sharing_leaves_finite_mixture_parametersandtest_forced_merge_fit_is_finite_in_both_backendsboth still fire a mergeunder the new sensor-space metric at their existing thresholds (0.99 default
and 0.9 respectively), confirmed by rerunning the full existing suite before
adding new tests.
New tests (
pamica/tests/test_numpy_share_comps.py, real sample EEG only)test_numpy_merge_decision_matches_torch_backend-- the acceptance test:identical
comp_listfrom NumPy and PyTorch on one matched state, mergeconfirmed non-vacuous.
test_rank_reduced_numpy_sharing_completes--pcakeep=16(sphere becomes(16, 32)),share_comps=True, completes with finite params andcomp_used.sum() < num_comps.do_newton=False: see note below.test_zero_norm_column_is_not_merged_and_raises_no_warning-- pins thetinydenominator guard: a zero-norm column's cosine is a clean0.0,never NaN, and never merges.
test_non_finite_sphere_fails_loudly-- a directly-injected non-finitesphere makes
get_sensor_mixing_matrix()raiseRuntimeErrormatching"non-finite".Pre-existing bug found (out of scope, not touched)
Writing the rank-reduced sharing test with the torch twin's exact parameters
(
do_newton=True,max_iter=25) hit a shape-mismatch crash in the NumPyNewton path (
self.sigma2 = updates["dsigma2"] / updates["dgm"][:, None],ValueError: operands could not be broadcast together with shapes (16,2) (2,1)) when a share pass collapsed every one of one model's components intothe other's in a single scan. This reproduces with
do_newton=Trueand isunrelated to the sensor-space metric change (it also occurs when only some
of the merged components are Newton-active); the new test sets
do_newton=Falseto stay in scope. Flagging for the lead / a follow-upissue rather than fixing here, per the Phase 1 plan's explicit "do not
touch Newton" scope.
Gate output
uv run pytest pamica/tests/test_numpy_share_comps.py pamica/tests/test_numpy_grad_norm.py pamica/tests/torch_tests/test_ng_sharing.py -q --no-cov-- 51 passed.uv run pytest -m "not slow" -n auto-- 407 passed, 18 skipped, 1 xfailed.uv run ruff check ./uv run ruff format --check ./uv run ty check .-- all clean.Closes #258
Part of epic #260