Skip to content

Epic close-out: PyTorch backend Fortran parity (natural-gradient EM) - #28

Merged
neuromechanist merged 44 commits into
mainfrom
feature/issue-9-epic-torch-parity
Jul 3, 2026
Merged

neuromechanist merged 44 commits into
mainfrom
feature/issue-9-epic-torch-parity

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #9 (Epic: PyTorch backend parity with Fortran AMICA).

Brings the natural-gradient EM PyTorch backend (AMICATorchNG) and the legacy NumPy
pyAMICA.py to Fortran-reference parity, completing the epic.

Ordering (important)

Merge PR #25 into feature/issue-9-epic-torch-parity FIRST. This close-out PR currently
contains phases 1-3; the phase-4 parity fix (issue #24) lives in PR #25 (into this epic branch)
and will appear here automatically once #25 is merged. Do not merge this PR to main before #25
lands on the epic, or the phase-4 fix will be missing from main.

Epic summary

Status

Test plan

  • uv run pytest pyAMICA/tests -m "not slow" -> 53 passed
  • slow e2e-vs-Fortran gate (test_end_to_end_correlation_vs_fortran) passes (corr > 0.95)
  • real-data NumPy-vs-Fortran parity (test_sample_data_numpy_vs_fortran) passes (> 0.9)

Pin .python-version to 3.12 for torch/MPS wheel compatibility and
declare torch, pytest, pytest-cov in pyproject.toml/uv.lock. The
worktree venv had none of these installed, so the test suite could
not even collect.
load_data_file() and load_eeglab_data() reshaped the flat buffer to
(field_dim, data_dim) order='F' then transposed. That only reproduces
the original array when data_dim == field_dim; for the real sample
data (32 channels, 30504 samples) it silently scrambles the data.
Verified against the real eeglab_data.fdt: the buggy reshape gives a
lag-1 sample autocorrelation of ~0.7, the corrected reshape gives
~0.96-0.97, consistent with genuine continuous EEG. Fix: reshape
directly to (data_dim, field_dim) order='F' with no transpose.

Also fixes compare_with_fortran(), which compared a 2D A_pytorch
against the un-indexed 3D fortran_results.A (missing the [:, :, 0]
model slice applied to W just above it), causing a broadcast into a
3D array that np.linalg.norm(..., 'fro') cannot handle.
comp_list is written by the Fortran binary with a record length sized
for real*8 data (recl=2*nbyte*nw*num_models), which is 2x too large
for int32 comp_list data; the direct-access write zero-pads the
record. Reading it back naively doubles the perceived element count
(observed: 64 int32 values for a 32-element array, the trailing 32
all zero), breaking the reshape to (nw, num_models). Fix: slice to
the first nw*num_models values before reshaping.

Also fixes 'LL = read_binary_file(...) or np.array([0])', which
raises ValueError for any multi-element LL array since numpy arrays
do not support truthiness; replaced with an explicit None check.
Adds from_json_file() classmethod and get_weights() to the legacy
NumPy AMICA class, and makes fit() optionally self-load data from the
'files'/'data_dim'/'field_dim' params-file config when called with no
arguments (load_default_params() strips those keys as data-specific,
so they are read directly from the raw params_file JSON instead).

Also adds basic input validation: num_models/max_iter must be >= 1 in
__init__, fit() rejects empty/non-2D data, and transform() raises
RuntimeError if called before fit().
fit()'s catch-all **kwargs was forwarded wholesale to
preprocess_data(X, **kwargs), which only accepts do_mean/do_sphere;
any other kwarg (e.g. verbose, as the AMICA wrapper's own fit()
already passes through) raised TypeError. Give fit() explicit
do_mean/do_sphere/verbose parameters instead, and wire verbose into
the tqdm progress bar.

Also switches NewtonOptimizer's parameter flatten/unflatten helpers
from .view(-1) to .reshape(-1): the Hessian-vector product hits a
non-contiguous gradient tensor (from A.T-derived parameters), which
.view() cannot handle without copying.
test_pyAMICA.py, test_amica.py, and test_sample_data.py imported
'AMICA' expecting the legacy NumPy class (num_models/max_iter/
do_newton kwargs, W of shape (nw, nw, num_models)), but pyAMICA's
__init__.py now exposes the PyTorch-backed sklearn-style AMICA under
that name; fixed to import AMICA_NumPy. Also fixes several
call-signature drifts: load_data_file() no longer takes a num_files
positional arg, plot_components()/create_output_dirs() functionality
referenced by test_pyAMICA.py never existed or was relocated (removed
those two tests, justified in the phase1 report), and amica_cli.py's
relative imports require '-m pyAMICA.amica_cli' invocation, not a
direct script path.

Fixes two test-authoring bugs found while debugging: find_best_
permutation's return value is the inverse of the permutation used to
build the test fixture (fixed the expected value, not the function -
verified the function's semantics are internally consistent), and a
device-mismatch (mps vs cpu) in a torch.ones() comparison.

Marks genuine algorithm-math failures xfail(strict=False) rather than
fixing them, per Phase 1 scope (loading/plumbing only, not AMICA
math): legacy Newton hits NaN likelihood on synthetic data, torch
GaussianMixtureICA.fit_em's log-likelihood decreases across
iterations (EM should be monotonic - real M-step bug), and the full
2000-iteration real-data runs don't reach Fortran-level component
correlation (known LL-scale/sign issue, AGENTS.md Known Issue #2).
Runs validate_implementations.py (real Fortran binary + real sample
EEG data, no synthetic data) at 20 and 100 iterations to establish a
measured baseline. Reproduces the known ~13x LL scale gap and
sub-0.95 component correlation, and adds a new finding: correlation
degrades from 0.84 to 0.43 mean as iteration count increases from 20
to 100, concretely illustrating why the torch backend's Adam-based
optimizer diverges from Fortran's fixed point rather than converging
toward it (ADR 0001).

Marks the UV migration and real-data test suite plan items done.
fit() no longer forwards **kwargs anywhere (preprocess_data is now
called with explicit do_mean/do_sphere), so the catch-all silently
swallowed unknown/misspelled kwargs instead of raising. Verified:
AMICA(...).fit(X, verbos=True) previously completed silently; now
raises TypeError. Confirmed no caller (amica.py, amica_cli.py,
validate_implementations.py, tests) relies on any kwarg beyond the
already-named max_iter/lrate/do_newton/debug/output_dir/do_mean/
do_sphere/verbose.
The previous fix unconditionally sliced comp_list to the first
nw*num_models values, which would silently truncate any oversized or
corrupt file, not just the known zero-padded case. Now only accepts
exactly nw*num_models values, or 2x that with an all-zero tail (the
documented Fortran recl=2*nbyte*nw*num_models padding); anything else
raises ValueError. Verified against the real fixture (still loads)
and two synthetic corrupt cases (wrong size, and 2x size with a
non-zero tail) that now raise instead of silently truncating.
fit(data=None) already checked _config_files was set, but not that
_config_data_dim/_config_field_dim were configured, nor that
len(files) == len(field_dim). A mismatch there would silently
truncate to the shorter list via zip() inside load_multiple_files(),
producing a partially-zero-filled data array instead of an error.
Now raises ValueError for both cases. Verified: the existing working
config still loads, and a deliberately mismatched files/field_dim
length is rejected with a clear message instead of silently
truncating.
Flips the 5 pytest.mark.xfail(strict=False) markers to strict=True so
CI fails on XPASS once a later phase fixes the underlying bug,
forcing removal of the stale marker instead of it going unnoticed.
(test_amica.py uses unittest.expectedFailure, already strict, left
alone.)

Checked each marker's actual terminal exception with --runxfail
before adding raises=:
- test_full_pipeline, test_em_fitting, test_sample_data_scikit,
  test_sample_data_light: all terminate in a clean AssertionError;
  added raises=AssertionError so an unrelated future crash (e.g.
  ImportError) is not silently masked as expected.
- test_sample_data_cli: investigating this one surfaced a different,
  previously-unnoticed bug. Its actual terminal exception is
  FileNotFoundError, not AssertionError: legacy AMICA._optimize()
  writes results as .npy files (save_results in pyAMICA.py) but
  loadmodout() expects raw Fortran-format binary files with no
  extension, so the round-trip on the CLI's own output fails before
  ever reaching the correlation comparison. Reworded the reason to
  describe this and left off the raises= constraint since the failure
  mode is not AssertionError (per review: don't over-constrain a
  marker whose real failure isn't the assertion path).

Also rewords test_sample_data_light's reason, which previously cited
'not fully decorrelated after only 50 iterations' as if that were the
root cause; the real cause is the LL scale/sign bug (Final LL prints
a nonsensical positive ~1.5e6 before the assertion), matching its two
sibling tests' reason text (AGENTS.md Known Issue #2).
…rness

Phase 1: Validation harness & test repair
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.
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.
…gfixes

Phase 2: Isolated correctness fixes (mixture factorization, alpha, LL scale)
…-rewrite

Phase 3: Natural-gradient EM backend (opt-in)
* Fix NumPy Newton stats to Fortran spec

Newton curvature stats used the density derivative dpdf where Fortran
uses the score fp; dsigma2 was inflated num_mix-fold inside the mixture
loop; kappa lacked the sbeta^2 factor and lambda the baralpha-weighted
mu^2 term. Correct all four to amica17.f90 semantics and add the
positive-definiteness fallback (whole-model natural gradient when a pair
fails sk1*sk2>1), so the reference is a valid Newton parity target.

* Add Newton, rejection, lrate control to NG

Port the Fortran Newton preconditioner (per-source-pair 2x2 solve with
positive-definiteness fallback), the score-based curvature statistics
(sigma2/lambda/kappa), and outlier rejection (per-sample LL threshold,
one-directional good-sample mask, good-count normalization) into
AMICATorchNG. Replace the ad-hoc backtracking with Fortran's convergence
control (anneal lrate/rholrate on LL decrease; ratchet the lrate ceiling
and newtrate down after maxdecs consecutive decreases). Wire do_newton
through the public AMICA(backend='ng') interface.

Newton is unit-verified against the reference to ~1e-16 but does not yet
close the >0.95 correlation gate; the NG backend converges to a different
fixed point than Fortran (issue #21).

* Add Newton/rejection tests; mark gate xfail

Newton stat parity (sigma2/lambda/kappa vs NumPy reference), full
Newton M-step A-update parity, the Newton direction formula and its
positive-definiteness guard, and outlier-rejection sample shrinkage on
real data. Update the >0.95 end-to-end gate to xfail with an accurate
reason (fixed-point gap, issue #21) and enable Newton in it so it
exercises the full path.

* Address PR review: robustness + coverage

- Reject using the pre-update per-sample LL (Fortran order), not post-update.
- Guard empty/degenerate good sets: validate reject params at construction,
  raise a clear ValueError instead of a downstream None/TypeError crash.
- Port the dalpha epsilon floor from the NumPy reference (do_reject makes the
  zero-responsibility divide more likely).
- Expose Newton fallback observability: n_newton_fallbacks counter + warning
  (mirrors Fortran's print), stop_reason attribute, lrate-floor break promoted
  to warning; log the NumPy reference fallback too.
- Fix stale/overclaiming docstrings (lrate control, do_newton wiring, tests).
- Add tests: positive-definite Newton M-step composition, rho=1/2 boundary
  stat parity, multi-model finiteness, degenerate-LL rejection error, reject
  param validation, and LL good-count normalization.
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.
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.
Phase 4: natural-gradient A-update transpose fix + exact-EM M-step + review hardening. Single-model corr 0.997 vs Fortran; both backends validated.
AMICA(backend='ng') auto-selected MPS but AMICATorchNG defaults to
float64 (Fortran parity), which MPS rejects; the default config crashed
on Apple Silicon. Fall back to CPU when MPS is auto-selected for a
float64 NG run. Re-export AMICATorchNG, note it in the model_ docstring,
and add a real-data wrapper test (guards, save/load, device fallback).
Refs #29.
The two xfail tests blamed 'epic #9'; that epic is delivered. They are
independent legacy bugs: CLI save/load format mismatch (#30) and the
GaussianMixtureICA fit_em M-step LL descent (#31). Repoint the reasons.
Update AGENTS.md (backend map, completed UV migration, follow-ups),
FEATURE_PARITY.md and PROGRESS_SUMMARY.md (NG parity numbers, replace
stale pre-epic metrics), and accept ADR 0001. Point V2 removal at #32.
Refs #26 #27 #29 #30 #31 #32.
Silent-failure-hunter: emit the MPS->CPU downgrade via logger.warning
unconditionally (not just verbose print), matching the codebase's device
caveats; derive AMICATorchNG's default dtype from its signature instead of
duplicating the float64 literal; document the fallback on the device
parameter. Test-analyzer: add explicit device='mps'+float64 raise test
(no MPS needed) and the dtype=float32 MPS escape-hatch test (skipif), and
assert the fallback warning fires even with verbose=False.
…nups

Address PR #28 review: NG backend polish + doc coherence
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.

Epic: PyTorch backend parity with Fortran AMICA (natural-gradient EM rewrite)

1 participant