Repository navigation
Phase 2: Isolated correctness fixes (mixture factorization, alpha, LL scale) - #19
Conversation
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.
Review outcome (Sonnet code-reviewer + team-lead verification)Confirmed correct — keep as-is:
Reworked before merge (bug 3): The Canonical docs corrected on the epic branch ( |
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.
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
amica_torch.py,amica_torch_v2.pyfallback): per-sourcelogsumexpover mixtures THEN sum over sources, instead of summing sources before the mixture reduction.alpha[k, :]per source, notalpha_k.mean().n_samples * n_sources(Fortranamica17.f90:1866). Jacobian handled viafor_trainingflag — excluded from the reported/Fortran-parity LL (Fortran omitslog|det W|too), included in the training loss gradient (removing it entirely destabilized training: LL went positive, A error 15.3).pyAMICA.py): floordalphaat 1e-10 before dividing; eliminates the NaN.Result (real sample data, seed 42)
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
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.Note: first commit includes ruff-format churn on two never-formatted files (pre-commit hook).