Skip to content

feat: component sharing (share_comps) in AMICATorchNG - #68

Merged
neuromechanist merged 2 commits into
mainfrom
60-implement-component-sharing-share_comps-in-amicatorchng
Jul 7, 2026
Merged

neuromechanist merged 2 commits into
mainfrom
60-implement-component-sharing-share_comps-in-amicatorchng

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #60. Ports the last unimplemented Fortran feature: multi-model component sharing.

What it does

On the share_start/share_iter schedule, components that are near-collinear across different models (cosine angle of their de-sphered mixing columns above comp_thresh) are merged into one shared mixing column and one shared density (Fortran identify_shared_comps, amica15.f90:1898). An A-freeze holds the mixing update for ~6 iterations after each merge so densities can settle.

Design (mirrors the #26 adaptive-PDF precedent)

  • No bit-exact oracle. The reference's similarity metric Spinv2 is never declared/initialized in amica15.f90 (which has implicit none, so it would not even compile as-is) -- its reassignment never actually fires, exactly like the dead do_choose_pdfs switch (Adaptive-PDF selection for AMICATorchNG #26). So this implements the intended algorithm (cosine similarity of de-sphered scalp maps) and validates by real-data behavior, not byte parity.
  • Off by default, and a no-op for n_models=1 -- single-model (Verify NG init-basin vs Newton bit-parity via Fortran load_* init-matching #24) and default multi-model (Multi-model NG partition matching vs Fortran (>0.95 cross-corr) #27) parity stay byte-for-byte (full torch suite green: 95 passed).
  • The M-step already sums sufficient stats through comp_list (index_add), so shared densities update jointly for free. The A-update was refactored to accumulate shared columns the same way (dAk index_add) -- byte-identical to the per-model update when unshared.
  • Merged-away columns are frozen in the density M-step (they get no stats, so 0/0 -> NaN otherwise; Fortran tolerates this behind its comp_used mask, we keep them finite so save/the degenerate-fit contract aren't tripped).

Tests (tests/torch_tests/test_ng_sharing.py, 6)

  • single-model byte-identical with sharing on vs off
  • controlled single collinear-pair merge
  • the 'no double-share within a model' guard (all-collinear 2x2 -> 2 shared comps, not 1)
  • default multi-model leaves comps unshared
  • full 2-model share fit stays finite and shares
  • save/load round-trips the share config + merged comp_list

No new persisted state (comp_list already persisted; comp_used is derived). Also gitignores .env.

Port the Fortran share_comps / identify_shared_comps reassignment: on the
share_start/share_iter schedule, components near-collinear across different
models (cosine angle of their de-sphered mixing columns above comp_thresh) are
merged into one shared mixing column and density, with an A-freeze for ~6 iters
after each merge.

The M-step already accumulates sufficient stats through comp_list (index_add),
so shared densities update jointly; refactor the A-update to accumulate shared
columns the same way (byte-identical to the per-model update when unshared).
Freeze merged-away columns in the density M-step (they receive no stats, so
0/0 -> NaN otherwise; Fortran tolerates this behind its comp_used mask).

OFF by default and a no-op for n_models=1, so single-model (#24) and default
multi-model (#27) parity stay byte-for-byte (full torch suite green). No
bit-exact oracle -- the reference Spinv2 metric is dead code (like #26) -- so
behavior-validated on real data. Also gitignore .env.

Closes #60.
@neuromechanist neuromechanist linked an issue Jul 7, 2026 that may be closed by this pull request
4 tasks
@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Welcome to Codecov 🎉

Once you merge this PR into your default branch, you're all set! Codecov will compare coverage reports and display results in all future pull requests.

Thanks for integrating Codecov - We've got you covered ☂️

PR review (4 reviewers) surfaced real bugs in the merged path (all off the
default byte-identical path, which was verified correct):

- A-update used a raw sum over models for shared columns; Fortran uses a
  gm-weighted average (dAk/zeta, amica15.f90:1730-1743). The raw sum over-steps
  by the contributor count and destabilizes the fit. Port the weighted average
  (single-model gm=[1] cancels exactly -> #24 stays byte-identical).
- keep_best (#51) restored comp_list from a pre-merge snapshot, silently
  reverting merges (returned model unmerged under the default keep_best=True).
  Disable keep_best under share_comps (+ warn), like do_reject; return the last
  merged iterate (Fortran).
- _a_frozen anchored on itf%share_iter, which permanently freezes A for
  share_iter<=6 and misaligns with the merge schedule. Anchor on
  (itf-share_start)%share_iter and require share_iter>6.
- _identify_shared_comps ran after W was rebuilt, leaving W stale (pre-merge
  comp_list) for one E-step. Rebuild W right after the merge.
- torch.linalg.inv(sphere) had no singularity guard (average-referenced /
  rank-deficient EEG); a NaN t0 also fell through 't0<thresh'. Guard the
  inversion (clear error), reject share_comps+pcakeep/pcadb up front, and guard
  t0 finiteness. Reset _spinv per fit; gate the Newton-direction compute under
  not-frozen (counter no longer polluted); add alpha to the non-finite check.

Comments corrected (Spinv2 declared-but-never-allocated -> UB, not benign;
amica17->amica15:1786-1797 citation; periodic-window framing). Tests reworked
8 -> 19: validation, freeze-window schedule, 3-model guard, comp_thresh=1.0,
singular-sphere-raises, merge-survives-to-final-model, unique-count-drops-
without-LL-degradation. Full torch suite green (108 passed).
@neuromechanist

Copy link
Copy Markdown
Member Author

Review complete (4 reviewers, Sonnet) + all findings addressed

Ran the pr-review-toolkit reviewers (code, tests, silent-failure, comments) in parallel. The default share_comps=False path was verified byte-identical (single-model #24 exact, multi-model #27 preserved); the real bugs were all in the merged path and are now fixed.

Critical

  • A-update was a raw sum, not Fortran's gm-weighted average (dAk/zeta, amica15.f90:1730-1743). The raw sum over-steps by the contributor count and destabilized the fit (LL dropped after a merge and never recovered). Ported the weighted average; single-model gm=[1] cancels exactly so Verify NG init-basin vs Newton bit-parity via Fortran load_* init-matching #24 stays byte-identical.
  • keep_best (Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51) silently reverted merges by restoring comp_list from a pre-merge snapshot -> the returned model was unmerged under the default keep_best=True. Disabled keep_best under share_comps (+ warning), like do_reject; returns the last merged iterate (Fortran).
  • _a_frozen froze A permanently for share_iter<=6 and misaligned with the merge schedule. Anchored on (itf-share_start)%share_iter and require share_iter>6.

Important

  • Stale W after a merge: _identify_shared_comps ran after W was rebuilt, so the next E-step read a pre-merge W while indexing densities by the merged comp_list. Now rebuild W immediately after the merge (Fortran order).
  • Unguarded sphere inversion: inv(sphere) crashes / returns garbage on average-referenced or rank-deficient EEG, and a NaN t0 fell through t0<thresh. Added an inversion guard (clear error), reject share_comps+pcakeep/pcadb up front, and guard t0 finiteness.

Low

Newton-fallback counter no longer polluted during a freeze; alpha added to the non-finite check; _spinv reset per fit().

Comments/docs

Spinv2 reframed as declared-but-never-allocated (undefined behavior / crash, not a benign no-op); amica17->amica15:1786-1797 citation corrected; "after each merge"->periodic-window.

Tests: 8 -> 19

Added constructor validation, the _a_frozen window schedule, a 3-model guard case, comp_thresh=1.0, singular-sphere-raises, merge-survives-to-final-model, and unique-count-drops-without-LL-degradation. Full torch suite green (108 passed, 5 skipped). No findings skipped.

@neuromechanist
neuromechanist merged commit 4cc9ef6 into main Jul 7, 2026
5 checks passed
@neuromechanist
neuromechanist deleted the 60-implement-component-sharing-share_comps-in-amicatorchng branch July 7, 2026 23:42
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.

Implement component sharing (share_comps) in AMICATorchNG

1 participant