Skip to content

Phase 1: Validation harness & test repair - #14

Merged
neuromechanist merged 11 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-10-phase1-harness
Jul 2, 2026
Merged

neuromechanist merged 11 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-10-phase1-harness

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Foundation gate for epic #9. Makes the test suite trustworthy and gets validate_implementations.py producing a real parity baseline vs the Fortran binary.

Closes #10
Part of epic #9

Key fixes (root causes, not test edits)

  • EEGLAB/Fortran .fdt reshape bug: reshape((field_dim, data_dim), order='F').T silently scrambles non-square data. Fixed to reshape((data_dim, field_dim), order='F'). Verified on real data: lag-1 time autocorrelation 0.62 (scrambled) -> 0.90 (correct); per-channel std 14-39 uV. Affects every real-data test and the validation harness.
  • comp_list size-64 bug: Fortran writes that file with a real*8 record length, zero-padding int32 data to 2x; slice to [:nw*num_models] before reshape.
  • LL = read_binary_file(...) or np.array([0]) truthiness bug on multi-element arrays; AMICATorch.fit() forwarding unknown kwargs to preprocess_data(); Newton .view() -> .reshape() on non-contiguous tensors; compare_with_fortran() A-matrix 3D indexing.

Test/plumbing

  • Repaired stale-API tests (legacy class renamed AMICA -> AMICA_NumPy; load_data_file signature; CLI invoked via -m).
  • Added legacy-AMICA convenience API (from_json_file, get_weights, self-loading fit, input validation) to keep existing tests rather than delete them (no algorithm changes).
  • Declared torch in pyproject.toml + dev group; pinned Python 3.12 (advances the tracked UV migration).
  • Parity-gated tests marked xfail(strict=False) so they auto-flip when later phases land.

Baseline (real sample data, validate_implementations.py)

20 iters 100 iters
Fortran LL -3.4456 -3.4108
PyTorch LL -44.77 -43.80
LL ratio 13.0x 12.8x
Mean component corr 0.835 0.431

Correlation degrades with iterations (0.84 -> 0.43), corroborating ADR 0001 (Adam-on-reparameterized-surface diverges from the Fortran fixed point).

Test plan

  • PYTORCH_ENABLE_MPS_FALLBACK=1 uv run pytest pyAMICA/tests/ -q: 35 passed, 6 xfailed (verified by team lead)
  • uv run python validate_implementations.py --max-iter 100 --seed 42: runs Fortran binary via Rosetta, prints comparison
  • Reshape fix independently verified via autocorrelation on real data

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).
@neuromechanist
neuromechanist merged commit 08ceadf into feature/issue-9-epic-torch-parity Jul 2, 2026
@neuromechanist
neuromechanist deleted the feature/issue-10-phase1-harness 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