Repository navigation
Fix Fortran parity in NG + NumPy backends (issue #24) - #25
neuromechanist merged 12 commits into
Conversation
Seed the Fortran binary and corrected NG from the identical init (load_* files) and compare 200-iter trajectories. Result: from the same start Fortran reaches -3.402 (corr 0.998) while Python plateaus at -3.460 (corr 0.51) => residual per-iteration M-step bit-parity bug, not init-basin. The gap is already in the first-order NG phase: with lrate pinned at 0.05 Python tracks Fortran ~5 iters then descends; the fit-loop lrate ratchet masks it as a -3.46 plateau. Newton is secondary. Adds .context/issue-24/verify_init_basin.py (reproducible harness, works around the reference binary's load_sphere segfault) and findings.md. Tested: harness runs green on CPU/float64.
Teacher-forced per-iteration M-step diff (seed CorrectedNG from Fortran's true state k, one step, compare to k+1). Findings (see .context/issue-24/drift_localization.md): - W/A, alpha, c updates are faithful; c-omission ruled out (Fortran c ~1e-16). - Bug 1 (proven): rho numerator misses a factor rho (amica17.f90:1568); adding it matches Fortran iter-1 rho to 1.7e-5. - Bug 2: rho per-component mask (rho!=1&rho!=2) zeros the numerator at the minrho clamp (Fortran only guards per-sample underflow). - Neither rho fix stops the pinned-lrate descent (-3.497): the dominant drift is the mu/beta exact-EM denominator (Bug 3, open; |mu|-dependent, in sbeta*sum(ufp/y)). - Flagged amica17.f90:1465 (rho-0.0 vs rho-1.0) for non-MKL rebuilds. Adds localize_drift.py (reproducible, --fixrho toggle).
The -3.46 parity gap is a transpose/wrong-side error in the natural-gradient A-update, proven machine-exact vs the Fortran binary. The prototype stores A as Fortran's A^T, so the step must be A <- A - lr*(I - G^T/dgm)@A (G = g^T b, left-multiply, transposed), not A <- A - lr*A@(I - G/dgm). At k=0 (matched sphere) only the left/transposed form matches Fortran's A_new to 7.8e-16 (current form off by 1.6e-3). With the fix the pinned-lrate fit ascends to -3.4265 / corr 0.648, matching Fortran pinned NG (-3.4269 / 0.645), vs the old descent to -3.4974 / 0.506. Invisible at the fixed point (G ~ G^T) so fixed_point_test passed. Also disproves the earlier "Bug 3 mu/beta denominator": bit-exact with Fortran once the same sphere is used; the 4.5e-3 drift was a benign sphere artifact (torch.cov cov/(N-1) vs Fortran cov/N, pure scalar sqrt(N/(N-1)) amplified by the singular sum(ufp/y) denominator). Adds root_cause_Aupdate.py (self-contained repro, --fit for the 200-iter parity check) and a RESOLVED banner + corrected BUGS TO FIX in drift_localization.md. Verified on real sample data + amica15mac.
Port the issue #24 root-cause fix (natural-gradient A-update transpose) plus the supporting exact-EM M-step into the shipped backends, replacing the old first-order gradient M-step that descended away from Fortran. torch_impl/amica_torch_ng.py and pyAMICA.py: - A-update: A -= lrate*(dir^T @ A) (left-multiply, transposed direction), for both natural gradient and the Newton precondition (H^T @ A), because A is stored as Fortran's A^T. Was A += lrate*(A @ dir) (wrong on both the side and the transpose) -- the root-cause descent bug. - Exact-EM mixture updates using the score fp (not dpdf): mu += dmu_n/dmu_d, beta *= sqrt(dbeta_n/dbeta_d); accumulator keys dmu/dbeta/drho/dA -> dmu_n/dmu_d/dbeta_n/dbeta_d/drho_n/dWtmp. - rho: leading rho factor + no per-component mask (Bugs 1+2) and the 1/psi(1+1/rho) digamma factor. - Symmetric-ZCA sphere with population covariance (torch.cov(correction=0) / np.cov(bias=True)); was PCA-whitening on the sample-covariance. - Output transpose: get_mixing/get_unmixing/transform return W^T / A^T. - NumPy LL: add the sldet + log|det W| Jacobian and compute it from pre-normalization logits via logsumexp (was a post-norm z-sum, positive and Jacobian-free). Result: AMICATorchNG Newton fit ascends to LL -3.4017 / corr 0.997 vs Fortran -3.4018 / 0.998 (0 Newton fallbacks); the NumPy trajectory is bit-identical (i100 LL -3.4110 both). The >0.95 end-to-end-vs-Fortran gate now passes (xfail removed); NG<->NumPy sufficient-stat parity holds to 1e-8. Tested on real sample data + the amica15mac binary.
Multi-model (n_models=2) M-step is bit-exact vs the Fortran binary: one seeded step matches per-model unmixing to ~1e-15 and gm exactly, and NG's sphere matches Fortran to ~1e-13. Add a Fortran-free NG<->NumPy multi-model sufficient-stat parity test (now valid since both backends carry the Jacobian LL) covering all accumulators + ll to 1e-8; generalize _numpy_ref_like for n_models>1. A full 2-model fit reaches comparable LL (NG -3.355 vs Fortran -3.345) but lower Hungarian cross-correlation (~0.77) due to multi-model partition ambiguity (many near-degenerate solutions; NG is self-consistent at 1.0 across block sizes) -- intrinsic, not a defect. Documented in AGENTS.md.
Remove the two synthetic source-recovery tests (test_full_pipeline, test_full_amica): they fabricated data (against the NO-MOCK policy) and used a broken metric (corrcoef on raveled sources, no permutation/sign matching, so they could never pass and were permanently xfail). Fitting that degenerate synthetic data was also the source of the transient slogdet RuntimeWarnings in the now-correct Jacobian LL. Replace with test_sample_data_numpy_vs_fortran: a real-data NumPy-vs- Fortran parity test (get_weights()@Sphere, Hungarian-matched component correlation > 0.9 vs amicaout at 150 iters; passes). Refresh the stale xfail reasons on the other sample-data tests that blamed the (now-fixed) LL scale/sign bug. Park AMICATorchV2 with a superseded note: the working AMICATorchNG replaces its unstable Newton path; retained only for the adaptive-PDF prototype.
With do_approx_sphere=False (sample_params.json) the natural gradient can pass through a near-singular W for an iteration, making np.linalg.slogdet emit divide-by-zero/overflow FP warnings while still returning a correct large-negative logdet. Wrap only that call in np.errstate(divide/over/ invalid='ignore'): the value still flows into logV and the fit-loop's NaN check still guards genuine divergence, so no failure is suppressed -- just the console noise for an expected numerical excursion. The fit is healthy (LL ascends, final W finite). Removes the last slogdet warning from the suite.
|
Follow-up work added to this branch after the initial description: Multi-model validation (commit 954ea51)
Synthetic-test cleanup + slogdet (commits ab7f47a, 40cb4b6)
Parked / captured
Suite: 53 passed, 0 failed, 0 slogdet warnings; slow e2e-vs-Fortran gate passes. |
From the pr-review-toolkit pass on PR #25: - Newton lambda_ finalization (torch): finalize BEFORE the exact-EM mu update so lambda uses the pre-update mu (Fortran/NumPy convention), not the post-update value. Was a real Newton-regime bug the init-time stat tests could not catch. New regression test test_newton_finalize_uses_preupdate_mu; the full-M-step cross-check now asserts mu/beta/rho/alpha/gm too, not just A. - Non-finite LL guard (both backends): a singular W gives logdet -> -inf (not NaN); guard on isfinite so a degenerate model stops instead of running to max_iter undetected. Distinct stop_reason. - Zero-silent-failure hardening: log-then-replace on the rho nan_to_num, a NaN canary after mu/beta (matching Fortran's live "NaN in sbeta" check), and an explicit isfinite(logdet_W) log so the slogdet errstate suppression is not the only trace of a singular W. - Parity: drho underflow guard uses Fortran's epsdble=1e-16, not finfo.tiny (~2e-308). - Multi-model c-update: documented as an omitted, fixable contributor to the 2-model gap (not purely partition ambiguity); tracked in #27. - e2e test now asserts n_newton_fallbacks == 0. Full suite green (54 passed, 0 slogdet warnings); e2e-vs-Fortran and NumPy real-data parity still pass.
Review completed (pr-review-toolkit, Sonnet) + findings addressedRan code / silent-failure / test-coverage / simplification reviewers in parallel. Two real bugs and several zero-silent-failure gaps found and fixed (commit 8ed06a1): Real bugs
Zero-silent-failure hardening (both backends)
Parity
Verified: A-update transpose (the PR's core claim) independently re-derived and confirmed correct. Full suite green (54 passed, 0 slogdet warnings); e2e-vs-Fortran (>0.95, 0 Newton fallbacks) and NumPy real-data parity both pass. Deferred (larger, filed/tracked): multi-model |
Summary
Closes the Fortran-parity gap for the natural-gradient backends (issue #24, completing the
phase-4 parity work). The
AMICATorchNGbackend and the legacy NumPypyAMICA.pynow ascend tothe Fortran solution instead of descending away from it.
Root cause: the natural-gradient A-update was transposed and multiplied on the wrong side.
Because
Ais stored as Fortran'sA^T, the step must beA -= lrate*(dir^T @ A)(left-multiply,transposed direction), not
A += lrate*(A @ dir). This was invisible at the fixed point (whereg^T b ~ (g^T b)^T), so the existingfixed_point_testpassed while every free-running fitdescended. Localized to machine precision in
.context/issue-24/root_cause_Aupdate.py(of fourcandidate update forms, only the correct one matches Fortran's
A_newto 7.8e-16).What changed (both
AMICATorchNGandpyAMICA.py)H^T @ A).fp(not the density derivativedpdf):mu += dmu_n/dmu_d,beta *= sqrt(dbeta_n/dbeta_d). Accumulator keys renameddmu/dbeta/drho/dA -> dmu_n/dmu_d/dbeta_n/dbeta_d/drho_n/dWtmp.rhofactor + no per-component mask + the1/psi(1+1/rho)digammafactor (issue Verify NG init-basin vs Newton bit-parity via Fortran load_* init-matching #24 Bugs 1+2).
torch.cov(correction=0)/np.cov(bias=True)); was PCA-whitening on the sample covariance.get_mixing/get_unmixing/transform(W^T/A^T).sldet+log|det W|and compute from pre-normalization logitsvia
logsumexp(the old post-normalization z-sum was positive and Jacobian-free, whichmisguided the fit-loop learning-rate ratchet).
Validation (real sample data + the
amica15macbinary)AMICATorchNGNewton fit ascends to LL -3.4017 / correlation 0.997 vsFortran -3.4018 / 0.998 (0 Newton fallbacks). The
>0.95end-to-end-vs-Fortran gate nowpasses (
xfailremoved).Fortran (one seeded step matches per-model unmixing to ~1e-15,
gmexactly); the spherematches to ~1e-13. Added an NG<->NumPy multi-model sufficient-stat parity test (all
accumulators +
llto 1e-8). A full 2-model fit reaches comparable LL (NG -3.355 vs Fortran-3.345) but a lower Hungarian cross-correlation (~0.77) because multi-model AMICA has many
near-degenerate partitions (unlike single-model's unique solution), so the two implementations
settle into different but equally-valid partitions. This is intrinsic partition ambiguity, not
a code defect (NG is self-consistent at cross-corr 1.0 across block sizes).
Separate follow-ups (not in this PR)
AMICATorchNG(present in the NumPy path). This is a feature beyondFortran parity, which uses a fixed generalized-Gaussian PDF; not parity-blocking.
AMICATorchV2Newton path is superseded by the now-workingAMICATorchNGandwas not touched.
degenerate data the now-correct Jacobian LL emits transient
slogdetRuntimeWarnings. The LL mathis correct; the right fix is to move those tests to real data.
Test plan
uv run pytest pyAMICA/tests -m "not slow"-> 53 passeduv run pytest -k test_end_to_end_correlation_vs_fortran(slow) -> passes (corr > 0.95).context/issue-24/root_cause_Aupdate.py --fitreproduces the machine-precision localization