Repository navigation
Phase 4: backend selection in AMICA and AMICAICA - #330
Merged
neuromechanist merged 26 commits intoSep 23, 2026
Merged
neuromechanist merged 26 commits into
neuromechanist merged 26 commits into
Conversation
neuromechanist
merged commit Sep 23, 2026
4324333
into
feature/issue-324-epic-mlx-first-class
8 checks passed
neuromechanist
deleted the
feature/issue-313-phase4-backend-selection
branch
September 23, 2026 01:03
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
AMICAandAMICAICAgain abackendparameter:"torch"(the default,AMICATorchNG, float64 Fortran parity) or"mlx"(AMICAMLXNG, Apple GPU, float32 only). Every wrapper feature now runs end to end on MLX:fitwith any backend keyword (includingpcakeep),from_params_file(..., backend="mlx"), the #50 degenerate-fit contract,save/load, the EEGLAB export and the MNE path (get_sources,applywith #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, andfit/loadshare one_mirror_backendthat copies the fit record (ll_history_,final_ll_,stop_reason_,mir_history_, restart records,converged_/is_fitted_) identically for both backends.AMICA.savewritesformat_version2 with a requiredwrapper["backend"]. MLX params (numpy arrays) are stored as CPU tensors of the same dtype, sotorch.load(weights_only=True)still works, and are converted back to numpy forAMICAMLXNG.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()andget_model_center(model_idx=0), float64 numpy arrays with the same names, shapes and "requires a fitted model" errors, exposed onAMICAbehind_check_usable(withget_sensor_mixing_matrix, which the wrapper lacked).AMICAICA.fit/to_mne_ica(including the #322_pca_basis) read the fit only through them, somne_compatmakes 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
backendparameter onAMICA(n_models, n_mix, device, verbose, backend="torch")andAMICAICA(n_models, n_mix, random_state, device, verbose, backend="torch"). Unknown name:ValueErrorlisting'torch', 'mlx'.backend="mlx"without MLX:ImportErrorat construction with the install hint (checked withimportlib.util.find_spec;import pamicaand a torch wrapper never import MLX, verified in a fresh interpreter).devicewithbackend="mlx":ValueErrorat construction;fit(..., dtype=...)(ordevice=) on MLX:ValueErrorbefore anything is built. No"auto"; the default stays"torch".AMICA.fitnow validates**kwargsagainst the selected backend's constructor keywords and raisesTypeErrornaming the backend class. Before, an unknown keyword raisedTypeErrorfrom the backend constructor (anddevice=/n_channels=in fit kwargs raised "got multiple values").format_version2 (records the backend);loadreads 1 and 2. Loading an MLX file needs MLX (ImportErrornaming the backend) anddevice=None(ValueErrorotherwise). A malformed MLX payload (missing params, a non-tensor param) raises a namedValueError.fit(X, seed=np.int64(42)), is now saved as the equivalent Python number. Before,AMICA.savewrote such a torch file andAMICA.loadrefused it (UnpicklingError: theweights_onlyunpickler rejects numpy scalars); reproduced on the base commit. Any other valueweights_onlycould not read back raisesTypeErrorat save time instead of writing an unloadable file.AMICAICAafter a degenerate fit leavespca_components_/pca_explained_variance_asNone(the accessors refuse a degenerate fit; such a fit was never exportable).AMICAICAdocstring anddocs/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.importorskipplus 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. Thebackends.mdend-to-end snippet was executed verbatim (external paths substituted with the bundledinput.paramandeeglab_data.set,Xthe bundled sample): runs in 42 s.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.savedid loads, as torch, and transforms identically.AMICA.from_params_file(input.param, backend="mlx")thenfit(X, max_iter=3):AMICAMLXNGreceives 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 namesAMICAMLXNGand exactly the file keys absent from its signature (data_dim, do_history, field_dim, files, histstep, num_samples, outdir, writestep).AMICA(backend="mlx").fit(X, pcakeep=20): 20 components, sensor maps (32, 20), sphere (20, 32);mir_step=1rejects pcakeep=20 up front (nothing published) and accepts pcakeep=32.AMICAICA(backend="mlx")with pcakeep=20 (10 iterations):get_sourcesvsamica_.transformrelative 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_icagives bit-identicalapplyoutput with and without exclusion; torch and MLX export the same PCA basis (projectors within 1e-10, variances rtol 1e-8).write_amica_outputthrough the wrapper reloads withloadmodout, 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 toorigordand per-component scale (residual 2.8e-7 / 9.4e-8 full rank, bar 1e-5)._matched_abs_corrfromtest_pca_reduction_cross_backend.py), identity matching; LL difference 1.3e-6 and 4.8e-6 (bar 1e-2).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.backend="mlx"without MLX (via Python'ssys.modules[name] = Noneunimportable marker, so the realfind_speccheck runs), unknown format version, v2 without a backend.AMICAICAfit, real divergence through fit keywords (invsigmin=1e6, invsigmax=1e7forces every density's inverse scale to at least 1e6 on unit-variance sphered data): torchnan_llat iteration 3 and MLXnan_paramsat iteration 2 in 16/16 runs (seeds 0/1/2/42, 4096 samples and full recording, with and withoutpcakeep=20);converged_False, no PCA basis built,to_mne_ica/get_sourcesrefuse, repr labels it degenerate.AMICA.__repr__andAMICAICA.__repr__name the backend (unfitted, fitted and degenerate forms tested on both backends).AMICA.from_params_file(sample_params.json, backend="mlx")buildsAMICAMLXNGwith the file's settings (including the JSON-onlymax_decs/min_grad_norm/share_intspellings) and the warning namesAMICAMLXNG.