Skip to content

Phase 1: sensor-space sharing similarity for numpy - #266

Merged
neuromechanist merged 3 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-258-phase1-sharing-space
Aug 23, 2026
Merged

neuromechanist merged 3 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-258-phase1-sharing-space

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Ports the PyTorch backend's sensor-space share_comps merge metric to the NumPy
backend (issue #258), so both backends make the same merge decision on the
same fitted state.

identify_shared_components used to compare mixing columns directly in the
sphered space.
It now takes de-sphered sensor-space maps, pinv(sphere) @ A, mirroring
AMICATorchNG._identify_shared_comps (torch_impl/core.py:1696-1741) and the
Fortran identify_shared_comps + Spinv back-map (amica15.f90:1916,
:568-578) exactly: same loop order (h < hh, then i, ii), same
tiny/isfinite guard on the cosine ratio, same within-model guard placed
after the threshold test, same merge direction (cj folds into ci).

A new cached, guarded _pinv_sphere() mirrors AMICATorchNG._pinv_sphere():
built on first use, invalidated wherever self.sphere is reassigned, and
raises a RuntimeError naming a degenerate fit on a non-finite sphere before
np.linalg.pinv gets a chance to fail more confusingly.
get_sensor_mixing_matrix() is refactored onto the same helper.

identify_shared_components is now a stateless pure function of
(atil, comp_list, comp_thresh) (dropped the vestigial W parameter and
stopped 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.AMICA has no analogue of AMICATorchNG._load_params --
there is no method that reassigns self.sphere on an already-constructed
instance.
The only place self.sphere is ever set is inside _preprocess_data, called
from fit() on a fresh instance.
pamica/numpy_impl/load.py's loadmodout/AmicaOutput is a separate,
unrelated class for reading Fortran binary output for validation/plotting; it
never touches AMICA_NumPy.
So __init__'s self._sphere_pinv = None plus the single invalidation site
added at the end of _preprocess_data (after all five self.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_list into a matched
AMICATorchNG, one scan of identify_shared_components (NumPy) and
_identify_shared_comps() (PyTorch) at comp_thresh=0.9 produces byte-identical
comp_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 sphered
space
(raw A columns) -- a real, non-trivial shift. With the default
comp_thresh=0.99 this flips the decision: sensor space would merge that
pair, the old sphered-space metric would not.

Test adjustments

No existing merge-dependent test's comp_thresh needed lowering --
test_sharing_leaves_finite_mixture_parameters and
test_forced_merge_fit_is_finite_in_both_backends both still fire a merge
under 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_list from NumPy and PyTorch on one matched state, merge
    confirmed non-vacuous.
  • test_rank_reduced_numpy_sharing_completes -- pcakeep=16 (sphere becomes
    (16, 32)), share_comps=True, completes with finite params and
    comp_used.sum() < num_comps. do_newton=False: see note below.
  • test_zero_norm_column_is_not_merged_and_raises_no_warning -- pins the
    tiny denominator guard: a zero-norm column's cosine is a clean 0.0,
    never NaN, and never merges.
  • test_non_finite_sphere_fails_loudly -- a directly-injected non-finite
    sphere makes get_sensor_mixing_matrix() raise RuntimeError matching
    "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 NumPy
Newton 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 into
the other's in a single scan. This reproduces with do_newton=True and is
unrelated 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=False to stay in scope. Flagging for the lead / a follow-up
issue 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

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
neuromechanist merged commit 7c50e83 into feature/issue-260-epic-mlx-parity Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-258-phase1-sharing-space branch August 23, 2026 05:59
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