Skip to content

Make share_comps work on rank-reduced fits - #256

Merged
neuromechanist merged 3 commits into
devfrom
253-share-comps-rank
Aug 22, 2026
Merged

neuromechanist merged 3 commits into
devfrom
253-share-comps-rank

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #253. Unblocks the Maxwell-filtered MEG report in #221.

The problem

_identify_shared_comps de-sphered mixing columns with Spinv = torch.linalg.inv(self.sphere) before comparing them, so share_comps=True raised RuntimeError: Component sharing needs an invertible sphere... on exactly the data class #223 had just made fittable: under rank reduction the sphere is (n_kept, n_channels) and has no inverse, and a square sphere fitted on rank-deficient data is singular. The constructor also refused share_comps together with pcakeep/pcadb up front.

Why the inverse was never required

The back-map only has to put the two columns in a common sensor-space frame before the cosine comparison. The reference does exactly that with a pseudo-inverse whenever reduction is active: Spinv(nx, numeigs) (amica15.f90:550-560). So pinv(sphere) is the faithful generalization, not a relaxation.

For the reduced PCA sphere S = D^-1/2 V_r^T the pseudo-inverse is pinv(S) = V_r D^1/2, i.e. a de-whitening followed by the orthonormal U_r = V_r embedding the reporter proposed in #221; an orthonormal embedding leaves the cosine untouched, so the comparison is the one the full-rank path already makes, evaluated in the subspace the data actually occupy.

What changed

  • pamica/torch_impl/core.py: the merge metric uses pinv(sphere); both invertibility RuntimeError paths are gone, as is the constructor's share_comps + pcakeep/pcadb rejection.
  • The two duplicate caches of the same matrix (_spinv for sharing, _sphere_pinv for get_sensor_mixing_matrix) are now one, behind _pinv_sphere(), invalidated per fit in _preprocess and on _load_params. Two caches of the same quantity with different invalidation points was a drift waiting to happen.
  • A non-finite sphere still fails loudly, and now says so: previously it surfaced as a LAPACK "ill-conditioned or too many repeated singular values" SVD error, which names the wrong cause for NaN input.
  • Docstrings on _identify_shared_comps, _pinv_sphere and comp_thresh carry the reasoning and cite amica15.f90:550-560.

Full-rank behavior is unchanged, measured not assumed

pinv == inv to ~1e-15 on a square full-rank sphere, orders of magnitude below the comp_thresh (~0.99) decision boundary. Confirmed end to end: the three existing full-rank sharing configurations (seeds 3 and 7 at 40 iterations, and the wrapper save/load config at 25) were run before and after the swap, and comp_list is identical with the final log-likelihood and A.sum() differing by exactly 0.0. share_comps is off by default and untouched paths are byte-for-byte unchanged, so single-model parity is unaffected.

Tests (real bundled sample EEG only, no synthetic data)

  • test_rank_reduced_share_fit_completes: public AMICA path, n_models=2 with pcakeep=16 and share_comps=True, non-square (16, 32) sphere, merges fire, all parameters finite, comp_list/comp_used/shared_components() mutually consistent, sensor maps (32, 16).
  • test_low_rank_projected_data_share_fit_completes: the Support for Maxwell-filtered Elekta MEG data #221 route, sample EEG projected onto its rank-20 subspace (what Maxwell filtering does to MEG), fitted with automatic rank detection plus sharing.
  • test_full_rank_merge_decisions_unchanged_by_pinv: from one real fitted full-rank state, the merge scan runs twice, once with pinv(sphere) and once with the exact inv(sphere) injected into the same cache, and must produce identical comp_list, with merges actually firing so the comparison is not vacuous.
  • test_pinv_matches_inv_on_a_fitted_full_rank_sphere: numerical pin, max|pinv(sphere) @ A - inv(sphere) @ A| < 1e-10 (measured 6.0e-14).
  • test_pca_reduction_no_longer_rejected_at_construction replaces the two removed ValueError cases; test_non_finite_sphere_still_fails_loudly replaces test_singular_sphere_raises_on_share, pinning the loud failure that remains.

NumPy backend: no equivalent change needed

Investigated rather than assumed. numpy_impl/utils.py:identify_shared_components compares the columns of A directly in the sphered space; it never de-spheres and inverts nothing, so the failure mode does not exist there. AMICA_NumPy also holds a reduced sphere fine (it shares the pamica/rank.py policy and sizes the model to the kept rank), and a share_comps=True fit on the same rank-20-projected sample data completes with a (20, 32) sphere, 20 used components and finite parameters. So there is nothing to port.

That does leave a genuine cross-backend divergence: PyTorch compares in sensor space, NumPy in sphered space, so the two can identify different pairs on the same data. It is pre-existing and not introduced here; it is recorded in docs/guides/amica-differences.md, and the NumPy sharing path is being reworked concurrently in #240/#242, so the port is tracked separately (pamica/numpy_impl/** is owned by that work and untouched in this PR). MLX has no share_comps at all, so it is not involved.

Gates

uv run ruff check ., uv run ruff format --check ., uv run ty check . all clean. uv run pytest -m "not slow" -n auto: 389 passed, 16 skipped, 1 xfailed. Full torch suite (slow included): 212 passed, 5 skipped.

The merge metric de-sphered mixing columns with inv(sphere), which raised
on every rank-reduced (non-square sphere) or rank-deficient fit, and the
constructor refused share_comps with pcakeep/pcadb up front. Invertibility
was never required: the reference's own sensor-space back-map under
reduction is the pseudo-inverse Spinv (amica15.f90:550-560).

Use pinv(sphere) unconditionally, through a single cached _pinv_sphere()
now shared with get_sensor_mixing_matrix, and drop the constructor
rejection. Full-rank fits are unchanged (pinv == inv to ~1e-15; comp_list
and LL bit-identical on the bundled sample). A non-finite sphere still
fails loudly, now with a message naming the degenerate fit instead of a
LAPACK SVD error.
Real sample EEG only. Two rank-reduced routes through the public AMICA
path (explicit pcakeep, and the #221 MEG recipe of projecting onto a
rank-20 subspace with automatic rank detection), both asserting finite
parameters and a comp_list/comp_used/shared_components() that agree.

Full-rank regression: the same fitted state merges identically under
pinv(sphere) and the exact inv(sphere), and the two de-sphered mixing
matrices agree to <1e-10. The singular-sphere test now pins the loud
failure that remains, a non-finite sphere from a degenerate fit.
Guide section on the pinv back-map and the NumPy backend's different
metric (sphered-space columns, no back-map), plus a changelog entry.
@neuromechanist
neuromechanist merged commit 02e7014 into dev Aug 22, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the 253-share-comps-rank branch August 22, 2026 23:47
neuromechanist added a commit that referenced this pull request Aug 23, 2026
* Port sensor-space sharing similarity to numpy (#258)

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.

* Document numpy sensor-space sharing change (#258)

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.

* Fix docstring test cross-reference
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.

share_comps fails on rank-reduced fits: sphere inversion requires full rank

1 participant