Skip to content

Fix Fortran parity in NG + NumPy backends (issue #24) - #25

Merged
neuromechanist merged 12 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-24-init-basin-verify
Jul 3, 2026
Merged

neuromechanist merged 12 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-24-init-basin-verify

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Closes the Fortran-parity gap for the natural-gradient backends (issue #24, completing the
phase-4 parity work). The AMICATorchNG backend and the legacy NumPy pyAMICA.py now ascend to
the Fortran solution instead of descending away from it.

Root cause: the natural-gradient A-update was transposed and multiplied on the wrong side.
Because A is stored as Fortran's A^T, the step must be A -= lrate*(dir^T @ A) (left-multiply,
transposed direction), not A += lrate*(A @ dir). This was invisible at the fixed point (where
g^T b ~ (g^T b)^T), so the existing fixed_point_test passed while every free-running fit
descended. Localized to machine precision in .context/issue-24/root_cause_Aupdate.py (of four
candidate update forms, only the correct one matches Fortran's A_new to 7.8e-16).

What changed (both AMICATorchNG and pyAMICA.py)

  • A-update transpose/side fix for natural gradient and the Newton precondition (H^T @ A).
  • Exact-EM mixture updates using the score fp (not the density derivative dpdf):
    mu += dmu_n/dmu_d, beta *= sqrt(dbeta_n/dbeta_d). Accumulator keys renamed
    dmu/dbeta/drho/dA -> dmu_n/dmu_d/dbeta_n/dbeta_d/drho_n/dWtmp.
  • rho update: leading rho factor + no per-component mask + the 1/psi(1+1/rho) digamma
    factor (issue Verify NG init-basin vs Newton bit-parity via Fortran load_* init-matching #24 Bugs 1+2).
  • Symmetric-ZCA sphere on the population covariance (torch.cov(correction=0) /
    np.cov(bias=True)); was PCA-whitening on the sample covariance.
  • Output transpose in get_mixing/get_unmixing/transform (W^T / A^T).
  • NumPy Jacobian LL: add sldet + log|det W| and compute from pre-normalization logits
    via logsumexp (the old post-normalization z-sum was positive and Jacobian-free, which
    misguided the fit-loop learning-rate ratchet).

Validation (real sample data + the amica15mac binary)

  • Single-model: AMICATorchNG Newton fit ascends to LL -3.4017 / correlation 0.997 vs
    Fortran -3.4018 / 0.998 (0 Newton fallbacks). The >0.95 end-to-end-vs-Fortran gate now
    passes (xfail removed).
  • NumPy backend: bit-identical trajectory to NG (LL -3.4110 at iter 100 on both).
  • Multi-model (n_models=2): the M-step and model responsibilities are bit-exact vs
    Fortran (one seeded step matches per-model unmixing to ~1e-15, gm exactly); the sphere
    matches to ~1e-13. Added an NG<->NumPy multi-model sufficient-stat parity test (all
    accumulators + ll to 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).
  • NG<->NumPy sufficient-stat parity (single + multi model) holds to 1e-8.
  • Full suite green: 53 passed, 0 failed (+ the slow e2e-vs-Fortran gate passes separately).

Separate follow-ups (not in this PR)

  • Adaptive-PDF selection for AMICATorchNG (present in the NumPy path). This is a feature beyond
    Fortran parity, which uses a fixed generalized-Gaussian PDF; not parity-blocking.
  • The experimental AMICATorchV2 Newton path is superseded by the now-working AMICATorchNG and
    was not touched.
  • Some pre-existing NumPy tests fit synthetic random data (against the NO-MOCK policy); on that
    degenerate data the now-correct Jacobian LL emits transient slogdet RuntimeWarnings. The LL math
    is correct; the right fix is to move those tests to real data.

Test plan

  • uv run pytest pyAMICA/tests -m "not slow" -> 53 passed
  • uv run pytest -k test_end_to_end_correlation_vs_fortran (slow) -> passes (corr > 0.95)
  • .context/issue-24/root_cause_Aupdate.py --fit reproduces the machine-precision localization

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.
@neuromechanist

Copy link
Copy Markdown
Member Author

Follow-up work added to this branch after the initial description:

Multi-model validation (commit 954ea51)

  • Proved the n_models=2 M-step is bit-exact vs the Fortran binary (one seeded step matches per-model unmixing to ~1e-15, gm exactly; sphere matches ~1e-13).
  • Added test_multimodel_sufficient_stats_match_numpy_reference (NG<->NumPy, all accumulators + ll to 1e-8).
  • Full 2-model fit reaches comparable LL (NG -3.355 vs Fortran -3.345) but ~0.77 Hungarian cross-corr due to intrinsic partition ambiguity (NG is self-consistent at 1.0 across block sizes). Tracked for a possible partition-matching pass in Multi-model NG partition matching vs Fortran (>0.95 cross-corr) #27.

Synthetic-test cleanup + slogdet (commits ab7f47a, 40cb4b6)

  • Removed the two synthetic source-recovery tests (fabricated data vs NO-MOCK; broken raveled-corrcoef metric; permanently xfail). They were the source of the transient slogdet warnings.
  • Added test_sample_data_numpy_vs_fortran: real-data NumPy-vs-Fortran Hungarian parity > 0.9 (passes).
  • Silenced the last (transient near-singular-W) slogdet FP warning locally in the NumPy LL without suppressing any value.

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.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review completed (pr-review-toolkit, Sonnet) + findings addressed

Ran 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

  • Newton lambda_ used post-update mu (torch): finalized Newton curvature before the exact-EM mu update so lambda uses the pre-update mu (matching Fortran/NumPy). Bit the Newton regime; init-time stat tests couldn't catch it. Added regression test + strengthened the full-M-step cross-check to assert mu/beta/rho/alpha/gm (not just A).
  • Bias c frozen at 0 is only a no-op for n_models=1 — a genuine multi-model contributor (not purely partition ambiguity). Documented + tracked in Multi-model NG partition matching vs Fortran (>0.95 cross-corr) #27; AGENTS.md corrected.

Zero-silent-failure hardening (both backends)

  • -inf LL from a singular W now caught (isfinite, not isnan-only) with a distinct stop_reason.
  • log-then-replace on the rho nan_to_num; NaN canary after mu/beta (matching Fortran's live NaN in sbeta check); explicit isfinite(logdet_W) log so the slogdet suppression isn't the only trace.

Parity

  • drho underflow guard uses Fortran's epsdble=1e-16, not finfo.tiny.

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 c-update and extra ratchet/public-wrapper test coverage (#27).

@neuromechanist
neuromechanist merged commit ca72ed7 into feature/issue-9-epic-torch-parity Jul 3, 2026
@neuromechanist
neuromechanist deleted the feature/issue-24-init-basin-verify 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