Skip to content

Phase 4: backend selection in AMICA and AMICAICA - #330

Merged
neuromechanist merged 26 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-313-phase4-backend-selection
Sep 23, 2026
Merged

neuromechanist merged 26 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-313-phase4-backend-selection

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Summary

AMICA and AMICAICA gain a backend parameter: "torch" (the default, AMICATorchNG, float64 Fortran parity) or "mlx" (AMICAMLXNG, Apple GPU, float32 only). Every wrapper feature now runs end to end on MLX: fit with any backend keyword (including pcakeep), from_params_file(..., backend="mlx"), the #50 degenerate-fit contract, save/load, the EEGLAB export and the MNE path (get_sources, apply with #322's residual restoration, ica.save/read_ica).

The constructor-keyword and params-file partition is computed per backend class from its own signature (one helper, _ctor_params), so the "not applied" warning names the selected backend's class and only the keys it lacks. The #50 contract uses each backend class's own _DEGENERATE_STOP_REASONS, and fit/load share one _mirror_backend that copies the fit record (ll_history_, final_ll_, stop_reason_, mir_history_, restart records, converged_/is_fitted_) identically for both backends.

AMICA.save writes format_version 2 with a required wrapper["backend"]. MLX params (numpy arrays) are stored as CPU tensors of the same dtype, so torch.load(weights_only=True) still works, and are converted back to numpy for AMICAMLXNG.from_state_dict (float32, int64, int32 and bool verified exact). Version 1 files, which by construction hold a torch state dict, still load; a pin test builds a v1 payload key for key from a real fit, written and verified against the pre-change code first.

Both backends gain get_sphere(), get_mean() and get_model_center(model_idx=0), float64 numpy arrays with the same names, shapes and "requires a fitted model" errors, exposed on AMICA behind _check_usable (with get_sensor_mixing_matrix, which the wrapper lacked). AMICAICA.fit/to_mne_ica (including the #322 _pca_basis) read the fit only through them, so mne_compat makes no backend-specific array calls.

Part of epic #324

Resolves #313 and the remaining bullet of #323; completes #304's MLX path (these close when the epic merges to dev)

Behavior changes

  • New backend parameter on AMICA(n_models, n_mix, device, verbose, backend="torch") and AMICAICA(n_models, n_mix, random_state, device, verbose, backend="torch"). Unknown name: ValueError listing 'torch', 'mlx'. backend="mlx" without MLX: ImportError at construction with the install hint (checked with importlib.util.find_spec; import pamica and a torch wrapper never import MLX, verified in a fresh interpreter). device with backend="mlx": ValueError at construction; fit(..., dtype=...) (or device=) on MLX: ValueError before anything is built. No "auto"; the default stays "torch".
  • AMICA.fit now validates **kwargs against the selected backend's constructor keywords and raises TypeError naming the backend class. Before, an unknown keyword raised TypeError from the backend constructor (and device=/n_channels= in fit kwargs raised "got multiple values").
  • Save format format_version 2 (records the backend); load reads 1 and 2. Loading an MLX file needs MLX (ImportError naming the backend) and device=None (ValueError otherwise). A malformed MLX payload (missing params, a non-tensor param) raises a named ValueError.
  • Fix (both backends): a numpy scalar in the backend's config or fit record, for example fit(X, seed=np.int64(42)), is now saved as the equivalent Python number. Before, AMICA.save wrote such a torch file and AMICA.load refused it (UnpicklingError: the weights_only unpickler rejects numpy scalars); reproduced on the base commit. Any other value weights_only could not read back raises TypeError at save time instead of writing an unloadable file.
  • AMICAICA after a degenerate fit leaves pca_components_/pca_explained_variance_ as None (the accessors refuse a degenerate fit; such a fit was never exportable).
  • MLX precision in the MNE path is documented in the AMICAICA docstring and docs/api/mne-compat.md: float32-consistent export, float64 round-off reconstruction.

Test plan

Real bundled sample EEG only (32 x 30504); MLX tests use pytest.importorskip plus an Apple-GPU guard and skip individually; the torch tests always run.

  • uv run ruff check --fix . && uv run ruff format .: clean. uv run ty check: all checks passed.
  • uv run pytest pamica/tests/test_wrapper_backends.py pamica/tests/test_backend_accessors.py pamica/tests/mne_tests -q --no-cov -n 4: 179 passed (after the review fix pass). With MLX made unimportable (sys.modules['mlx'] = None, as on the Linux runners), the three new files give 35 passed, 43 skipped, 0 failed.
  • uv run pytest pamica/tests -q --no-cov -n 4 -m "not slow" (CI subset): 1299 passed, 14 skipped, 1 xfailed, 0 failed (after the review fix pass).
  • mkdocs build --strict (docs extra in a scratch venv): built, no warnings. The backends.md end-to-end snippet was executed verbatim (external paths substituted with the bundled input.param and eeglab_data.set, X the bundled sample): runs in 42 s.
  • New tests against the pre-change code (base 91b8b60 with the three new test files copied in): 60 failed + 4 errors of 66; the 2 that pass are the v1 pin (by design) and the torch "not applied" warning guard.
  • Gate 1, wrapper end to end on both backends: fit, transform, save, load, transform bit-identical (torch and MLX); converged_/is_fitted_/stop_reason_/final_ll_/restart records round-trip; model_ is the right class; every delegating method (transform, mixing/unmixing/sensor maps, pdftype, rho, shared components, variance order, loglik, probability, MIR, PMI, EEGLAB export) matches the backend's own answer.
  • Gate 2, v1 pin: a v1 payload built exactly as the old save did loads, as torch, and transforms identically.
  • Gate 3, AMICA.from_params_file(input.param, backend="mlx") then fit(X, max_iter=3): AMICAMLXNG receives pcakeep=32, pcadb=30, block_size=512, do_newton, newt_start=50, newtrate=1.0, lrate=0.05, minlrate=1e-8, maxdecs=3, rholratefact=0.5, invsigmax=100, mineig=1e-12; the warning names AMICAMLXNG and exactly the file keys absent from its signature (data_dim, do_history, field_dim, files, histstep, num_samples, outdir, writestep).
  • Gate 4, AMICA(backend="mlx").fit(X, pcakeep=20): 20 components, sensor maps (32, 20), sphere (20, 32); mir_step=1 rejects pcakeep=20 up front (nothing published) and accepts pcakeep=32.
  • Gate 5, AMICAICA(backend="mlx") with pcakeep=20 (10 iterations): get_sources vs amica_.transform relative error 2.0e-7 (3.0e-7 full rank; bar 1e-5); apply() with nothing excluded reproduces the input to 1.4e-15 (2.5e-15 full rank; bar 1e-10); exclude=[0] vs its float32 backend oracle 1.9e-7 (bar 1e-5), residual-subspace leak 1.8e-15 (bar 1e-10); ica.save/read_ica gives bit-identical apply output with and without exclusion; torch and MLX export the same PCA basis (projectors within 1e-10, variances rtol 1e-8).
  • Gate 6, MLX write_amica_output through the wrapper reloads with loadmodout, full rank and pcakeep=20: W (n, n, 1), S (32, 32) with exact sphere rows and zero padding, A (32, n, 1), mean and LL exact; sources and sensor maps equal the live ones up to origord and per-component scale (residual 2.8e-7 / 9.4e-8 full rank, bar 1e-5).
  • Gate 7, torch vs MLX through the wrapper (full sample, seed 42, 10 iterations): same component count (32 and 20); Hungarian-matched source |corr| min 0.99999996 full rank and 0.99999993 at pcakeep=20 (bar 0.999, reusing _matched_abs_corr from test_pca_reduction_cross_backend.py), identity matching; LL difference 1.3e-6 and 4.8e-6 (bar 1e-2).
  • Gate 8, accessors on both backends: shapes (n_kept, 32) / (32,) / (n_kept,), float64, exact copies of the stored state, independent of the model, index validation, unfitted RuntimeError; MLX vs torch: sphere 1.4e-14 relative (3.0e-14 reduced), mean 4.0e-8, two-model centers 4.7e-6 of their largest entry after one iteration; same through the wrapper.
  • Gate 9, error paths: bad backend name, mlx + device, mlx + dtype, MLX payload loaded with a device, MLX payload or backend="mlx" without MLX (via Python's sys.modules[name] = None unimportable marker, so the real find_spec check runs), unknown format version, v2 without a backend.
  • Degenerate AMICAICA fit, real divergence through fit keywords (invsigmin=1e6, invsigmax=1e7 forces every density's inverse scale to at least 1e6 on unit-variance sphered data): torch nan_ll at iteration 3 and MLX nan_params at iteration 2 in 16/16 runs (seeds 0/1/2/42, 4096 samples and full recording, with and without pcakeep=20); converged_ False, no PCA basis built, to_mne_ica/get_sources refuse, repr labels it degenerate.
  • AMICA.__repr__ and AMICAICA.__repr__ name the backend (unfitted, fitted and degenerate forms tested on both backends).
  • AMICA.from_params_file(sample_params.json, backend="mlx") builds AMICAMLXNG with the file's settings (including the JSON-only max_decs/min_grad_norm/share_int spellings) and the warning names AMICAMLXNG.

@neuromechanist
neuromechanist merged commit 4324333 into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-313-phase4-backend-selection branch September 23, 2026 01:03
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