Repository navigation
Phase 1: shared pcakeep/pcadb policy and MLX support - #326
Merged
neuromechanist merged 12 commits intoSep 22, 2026
Merged
neuromechanist merged 12 commits into
neuromechanist merged 12 commits into
Conversation
validate_pca_reduction rejects non-integer or < 1 pcakeep and non-finite or <= 0 pcadb; pca_reduction_requested answers the upfront mir_step question; numerical_rank re-validates at fit time. Rank policy unit tests pass (44).
Both constructors call the shared validate_pca_reduction. The torch mir_step gate delegates to pca_reduction_requested with the fitted data's channel count, so pcakeep >= n_channels (the bundled input.param's pcakeep 32) is no longer rejected. New regression test fails before the fix and passes after; wrapper suite green.
The shared validator accepts numpy integers, which the weights_only torch.load in AMICA.load refuses to unpickle; state_dict now casts to int/float. None stays None, so default payloads are unchanged.
AMICAMLXNG takes pcakeep/pcadb with AMICATorchNG's position, semantics and shared validation, passes them to numerical_rank, gains the same upfront mir_step gate and message, and persists both in state_dict config (additive; older payloads load with None). Docstrings and the mir() error no longer claim MLX lacks explicit reduction. MLX mir/persistence/backend suites pass (68).
Real sample: torch/NumPy/MLX keep the same rank and sphere for pcakeep=20 and pcadb=18.5 (rank 10); pcakeep wins over pcadb; invalid values raise at construction; torch and MLX give the same mir_step gate verdict; torch vs MLX reduced fits match (min |corr| > 0.999); MLX and torch persistence round-trip the request. 61 passed; 53 of them fail on the pre-#323 sources.
Comment-only; full-repo typos check passes.
Differences guide: backend-table row, at-a-glance row 11 (pcadb is a pamica extension; pcakeep wins), a pcakeep/pcadb section, and the mir_step gate section rewritten for both backends. MLX API page and changelog entries. mkdocs build --strict passes.
No backend reduces when do_sphere=False (the reference sets numeigs = nx there, amica15.f90:527), yet the mir_step gate still fired. The shared predicate takes do_sphere and validates first; a new log_ignored_pca_request (called by all three constructors) warns once that the request is ignored, and carries the precedence INFO note, so validate_pca_reduction is now validation only. Rank policy and cross-backend tests pass (126).
_preprocess shrinks n_channels to the kept rank, and torch/MLX then validated the next fit's X against it: a refit, or the second of n_restarts under any rank reduction (explicit or automatic), raised 'X has 32 channels, model expects 20'. Both backends now keep the constructor's count in _n_input_channels, validate X against it, and reset n_channels/n_comps from it at the start of every _fit_once. _load_params derives it from the restored sphere's width, so a reloaded reduced model refits. 16 new cross-backend tests; the 12 torch/MLX cases fail before the fix, NumPy is the passing control.
A pcakeep/pcadb reassigned after construction raises the validator's ValueError at fit time on torch, NumPy and MLX (and at the mir_step gate on torch/MLX); the validator rejects numpy.bool_ and accepts numpy floats for pcadb; a torch state dict without the two config keys loads with None and keeps its reduced sphere. Rank policy and cross-backend suites: 160 passed.
Every torch_impl/core.py line citation in mlx_impl/core.py (about 50, many already stale and six shifted by this PR) now names the symbol (AMICATorchNG.<method> or pamica.torch_impl.core.<name>), which does not rot. Fortran line citations are unchanged. Comment-only.
Differences guide: backend-table intro describes the raw MLX backend accurately; PCA, MIR and PMI defined on first use; row 11 wording; the pcakeep/pcadb and mir_step sections cover do_sphere=False and fit-time checks. MLX API page and changelog use semantic line breaks and add the do_sphere, refit/restart and invalid-payload-load entries. mkdocs build --strict and typos pass.
3 tasks
neuromechanist
merged commit Sep 22, 2026
98e510e
into
feature/issue-324-epic-mlx-first-class
8 checks passed
This was referenced Sep 22, 2026
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
Makes the explicit PCA-reduction request (
pcakeep/pcadb) one shared decision across the three array backends.pamica/rank.pygainsvalidate_pca_reduction(pcakeepmust be an integer >= 1,pcadba finite real > 0,boolrejected for both; both set is allowed,pcakeepwins and one INFO line sayspcadbis ignored, as in the reference) andpca_reduction_requested(the config-only predicate for the upfrontmir_stepgate:pcakeep < n_channels, or anypcadb).numerical_rankre-validates at fit time, and all three constructors validate up front.AMICAMLXNGgainspcakeep/pcadb(same position, semantics and docs asAMICATorchNG), passes them tonumerical_rank, gains_pca_reduction_requestedand the same upfrontmir_stepgate and message as torch, and persists both additively instate_dict()["config"](a payload without the keys loads withNone; noformat_versionbump). Every MLX docstring, comment and error message that said MLX has no explicitpcakeep/pcadbnow describes the new reality.AMICATorchNG._pca_reduction_requesteddelegates to the shared predicate with the fitted data's channel count, so the gate no longer rejectspcakeep >= n_channels(the bundledinput.paramsetspcakeep 32on the 32-channel sample). Bothstate_dicts store the request as plainint/float, because the validator accepts numpy scalars, which MLX's JSON config and torch'sweights_onlyload both refuse.Review round:
_preprocessshrinksn_channelsto the kept rank, and torch/MLX validated the next fit's X against that shrunk count, so a refit or the second ofn_restartsunder any rank reduction (explicit or automatic) raised "X has 32 channels, model expects 20". Both backends now keep the constructor's count in_n_input_channels, validate X against it, and resetn_channels/n_compsfrom it at the start of every_fit_once;_load_paramsderives it from the restored sphere's width, so a reloaded reduced model refits.pcakeep/pcadbwithdo_sphere=False(which no backend, and not the reference, ever reduces: amica15.f90:527) now log one WARNING at construction and no longer trip themir_stepgate; the shared predicate takesdo_sphereand validates first, and a newlog_ignored_pca_requestcarries both log notes sovalidate_pca_reductionis validation only. Everytorch_impl/core.py:<lines>citation inmlx_impl/core.pynow names the symbol instead.Docs: the differences guide gains the backend-table row "Explicit
pcakeep/pcadb", an at-a-glance row recordingpcadbas a pamica extension (the reference parses it at amica15.f90:3459-3461 and never uses it) andpcakeep's precedence, apcakeep/pcadbsection, and the old "MLX has none" gate section rewritten to describe the gate on both backends. MLX API page and changelog updated.Closes #323
Part of epic #324
#323's third bullet (exposing
pcakeepthrough theAMICAwrapper for MLX) lands with Phase 4 (#313), which adds backend selection to the wrapper.Behavior changes
pcakeep/pcadbnow raiseValueErrorat construction on torch, NumPy and MLX. Previously torch and NumPy accepted them silently:pcakeep=-3fitted 29 of 32 sources (negative slice),pcakeep=2.7truncated to 2, andpcakeep=0orpcadb <= 0ended innan_ll.fit(mir_step > 0)no longer rejectspcakeep >= n_channels(torch).AMICA.from_params_file("input.param").fit(X, mir_step=1)used to raise; it now runs.pcakeep/pcadb(previously aTypeErrorfor an unknown keyword).pcakeep/pcadbwithdo_sphere=Falselog one WARNING that they are ignored, and themir_stepgate no longer rejects them.n_restarts > 1after a rank reduction work on torch and MLX (previouslyValueError: X has 32 channels, model expects 20).pcakeep/pcadb(only possible before this change) now fails to load with the validator'sValueError.pcakeep=pcadb=None) are numerically unchanged on every backend; the existing Fortran-parity suites pass unmodified.Test plan
uv run ruff check --fix . && uv run ruff format .: cleanuv run ty check: all checks passedpamica/tests/test_rank_policy.py: validator accept/reject table (includingTrue,2.7,0,-3,"20",np.int64(5),nan/inf/0/-5pcadb), predicate truth table,numerical_rankrejects invalid input, precedence logged oncepamica/tests/test_pca_reduction_cross_backend.pyon the real sample (torch and NumPy unconditional, MLX per-testimportorskip); 53 of its original 61 tests fail on the pre-change sources (the module now has 95 tests):pcakeep=20: all three fit 20 sources with a(20, 32)sphere; torch vs NumPy sphere max abs diff 2.2e-14 (max entrywise relative 2.0e-11; assertedrtol=1e-10, atol=1e-13); torch vs MLX float32 sphere 3.6e-9, MLX float64 host sphere 3.5e-15;sldetagrees to 7e-15pcadb=18.5keeps 10 (10th eigenvalue at -17.21 dB, 11th at -19.92 dB): torch vs NumPy 5.0e-16, torch vs MLX float32 1.9e-9, host 1.1e-16pcakeep=20, pcadb=30gives thepcakeep-only sphere bit for bit on every backend (pcadb=30alone keeps 26)ValueErrorat construction on all three backendspcakeep=20,31,pcadb=18.5,pcakeep=20+pcadb=30up front (no sphere built) and acceptpcakeep=32,64,32+pcadb=30(fit completes,mir_history_populated)pcakeep=20, 10 iterations: min Hungarian-matched source |corr| 0.99999994 (threshold 0.999), identity matching, LL difference 1.9e-7 (threshold 1e-2, fromtest_mlx_backend.py). Thetest_mlx_*_cross_backend.pysuites have no Hungarian-matched correlation bar, so the 0.999 is the suite's strictest one (test_amica_ng_wrapper.py), above the 0.95 cross-implementation gatesave/loadkeepspcakeep/pcadb(as plainint/floatfrom numpy-scalar input) and the reduced sphere; a state dict with both config keys deleted loads withNone; torchAMICA.save/loadround-trips a numpy-scalar requestAMICA.from_params_file(input.param).fit(X, max_iter=2, mir_step=1)passes (fails before the fix)pcakeep=20and after automatic reduction (sample projected to rank 20) keeps(n, n_in) = (20, 32); torch and MLX reproduce the first fit'sll_historyexactly (NumPy warm-starts from its fitted A, so only geometry is compared)n_restarts=2, restart_seeds=[42, 43]withpcakeep=20and with automatic reduction completes on all three: restart LLs [-3.989754, -3.98975], geometry (20, 32)state_dictand MLXsave/loadof a reduced model transform identically and refitdo_sphere=False+pcakeep=20: all three fit full width with an identity sphere and warn once; torch and MLX acceptmir_step=1with itpcakeep=-3/pcadb=-5.0reassigned after construction raise at fit time on all three; a reassigned"20"raises the validator'sValueErrorat the torch/MLXmir_stepgatenumpy.bool_, acceptsnp.float32/np.float64pcadb; torch payload without the two config keys loads withNoneuv run pytest pamica/tests/test_rank_policy.py pamica/tests/test_pca_reduction_cross_backend.py pamica/tests/torch_tests pamica/tests/mlx_tests -q --no-cov -n 4: 693 passed, 5 skipped; restart-policy and MLX cross-backend suites: 104 passed, 1 skippeduv run pytest -q -n auto: 1126 passed, 14 skipped, 3 xfailed (27.6 min on a shared host)mkdocs build --strictandtypospass