Skip to content

Phase 2: Isolated correctness fixes (mixture factorization, alpha, LL scale) - #19

Merged
neuromechanist merged 5 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-11-phase2-bugfixes
Jul 2, 2026
Merged

neuromechanist merged 5 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-11-phase2-bugfixes

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Fixes the three isolated math bugs in the current Adam-based torch backend, plus the legacy-NumPy Newton divide-by-zero. Surgical fixes only; the architecture rewrite is Phase 3.

Closes #11
Part of epic #9

Fixes

  • Mixture factorization (amica_torch.py, amica_torch_v2.py fallback): per-source logsumexp over mixtures THEN sum over sources, instead of summing sources before the mixture reduction.
  • Per-source alpha: use alpha[k, :] per source, not alpha_k.mean().
  • LL normalization: divide by n_samples * n_sources (Fortran amica17.f90:1866). Jacobian handled via for_training flag — excluded from the reported/Fortran-parity LL (Fortran omits log|det W| too), included in the training loss gradient (removing it entirely destabilized training: LL went positive, A error 15.3).
  • Legacy Newton divide-by-zero (pyAMICA.py): floor dalpha at 1e-10 before dividing; eliminates the NaN.

Result (real sample data, seed 42)

100 iters before 100 iters after
Fortran LL -3.4108 -3.4113
PyTorch LL -43.80 -0.967
LL ratio 12.8x 0.28x
Mean corr 0.4313 0.4312

LL scale now comparable to Fortran (Known Issue #2 resolved). Correlation unchanged as expected — the Adam-vs-natural-gradient trajectory divergence is Phase 3's scope.

Test plan

  • New test_correctness_fixes.py: 5 tests, real data, hand-computed numpy/scipy reference for the GG-mixture LL; asserts per-source factorization, per-source alpha effect, and LL scale.
  • Full suite: 40 passed, 6 xfailed (verified by team lead).
  • xfail reasons updated where the NaN fix changed the failure mode to the correlation gap.

Note: first commit includes ruff-format churn on two never-formatted files (pre-commit hook).

Three bugs made the torch backend's reported LL and gradients diverge
from AMICA's actual model: mixture logsumexp was reduced across all
sources before the per-source reduction (forcing every source to
share one mixture label), alpha was collapsed to a scalar mean instead
of using each source's own weight, and the reported LL was normalized
by n_samples only (Fortran divides by n_samples * n_sources) while
also carrying an explicit log|det W| term Fortran's reported LL never
includes.

Dropping the Jacobian term entirely destabilizes this Adam-based
optimizer (nothing else constrains A/beta from drifting into a
degenerate high-density region), so compute_log_likelihood now takes
a for_training flag: the Jacobian is kept in the training objective
but excluded from the reported/normalized value used for logging and
comparison against Fortran.
A mixture component's responsibility mass (dalpha) can collapse to
zero when it has no assigned samples; dividing dmu/dbeta/drho by it
directly produced NaN. Floor dalpha with an epsilon before using it as
a divisor, matching the epsilon-floor pattern already used elsewhere
in this module.

This eliminates the NaN that previously made test_full_amica and
test_full_pipeline fail immediately, but both still fail on a
different, pre-existing assertion (component correlation ~0.19 vs the
required >0.8/0.9), so their xfail markers stay in place with updated
reasons.
Locks the mixture-factorization, per-source-alpha, and LL-scale fixes
to the real sample EEG data: reported LL is checked against a
hand-computed numpy/scipy reference built independently from the
model's own alpha/mu/beta/rho, deliberately different per-source alpha
is checked to actually change the per-source mixture contribution, and
the reported LL is checked against Fortran's ballpark from
.context/phase1_baseline.md.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review outcome (Sonnet code-reviewer + team-lead verification)

Confirmed correct — keep as-is:

  • Bug 1 (per-source mixture factorization): traced line-by-line against amica17.f90:1313-1360; logsumexp(dim=0).sum() matches Fortran's per-source reduction then sum-over-sources.
  • Bug 2 (per-source alpha): alpha_k.unsqueeze(1) correct; no downstream .mean() collapse remains.
  • Legacy dalpha epsilon floor: sound narrow guard, eliminates the Newton NaN.
  • The new test_correctness_fixes.py numpy reference is a genuine independent re-derivation for bugs 1 and 2.

Reworked before merge (bug 3): The for_training Jacobian split was based on a wrong premise (mine) that Fortran omits log|det W| from the reported LL. Verified against source: Fortran INCLUDES it — amica17.f90:975-980 computes log|det W| via QR of W, and :1273 seeds Ptmp = Dsum + log(gm) + sldet (unmixing + sphering log-determinants) before the density loop, flowing into the printed LL at :1866. Fix: include log|det W| unconditionally in the reported LL and add the sphering log-det sldet; drop the for_training split (which also silently gave the Newton/optimizer call sites a Jacobian-less objective). Test bound tightened toward Fortran's ~ -3.4.

Canonical docs corrected on the epic branch (research.md). Bugs 1/2 stand; bug 3 rework in progress.

Fortran's printed LL DOES include log|det W| (via QR of W,
amica17.f90:975-980) and the sphering log-determinant sldet
(seeded into Ptmp before the density loop, amica17.f90:1273),
flowing unchanged into the final LL/(n_samples*nw) normalization
at amica17.f90:1866. The for_training split from the previous
commit had this backwards: it excluded the Jacobian from the
default/reported value, which was both wrong per Fortran and a
silent regression for the Newton/optimizer call sites that invoke
compute_log_likelihood(X) with no kwarg.

Removed the for_training flag; compute_log_likelihood now always
includes log|det W| and self.sldet. self.sldet is a new buffer set
in preprocess_data as sum(-0.5*log(kept eigenvalues)), matching
Fortran's sldet formula exactly including the PCA-reduced-rank
case. Also switched log|det A| from torch.logdet to
torch.linalg.slogdet, since Fortran's own Dtemp uses log(abs(...))
and plain logdet NaNs on a negative determinant.

On the real sample data this brings the reported LL to within
0.5% of Fortran's value (previously off by ~13x, then briefly
inverted-sign-of-the-bug after the first Bug 3 attempt).
The hand-computed numpy reference now includes the same log|det W|
and sldet terms as compute_log_likelihood, taking the model's own A
and sldet as inputs instead of asserting them away. Tightens the
Fortran-ballpark assertion from a loose order-of-magnitude range to
within 30% of Fortran's -3.41, now that the fix lands the reported LL
within 0.5% on the real sample data. Rebuilds the nw-normalization
regression test around two independently-constructed models (instead
of slicing one model's sources) since slicing would silently pair a
partial source set with the full model's Jacobian, which no longer
makes sense now that the Jacobian is part of the reported value.
@neuromechanist
neuromechanist merged commit b9e1d09 into feature/issue-9-epic-torch-parity Jul 2, 2026
@neuromechanist
neuromechanist deleted the feature/issue-11-phase2-bugfixes branch July 3, 2026 18:26
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