Skip to content

Phase 1: shared pcakeep/pcadb policy and MLX support - #326

Merged
neuromechanist merged 12 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-323-phase1-pca-policy
Sep 22, 2026
Merged

neuromechanist merged 12 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-323-phase1-pca-policy

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Makes the explicit PCA-reduction request (pcakeep/pcadb) one shared decision across the three array backends. pamica/rank.py gains validate_pca_reduction (pcakeep must be an integer >= 1, pcadb a finite real > 0, bool rejected for both; both set is allowed, pcakeep wins and one INFO line says pcadb is ignored, as in the reference) and pca_reduction_requested (the config-only predicate for the upfront mir_step gate: pcakeep < n_channels, or any pcadb). numerical_rank re-validates at fit time, and all three constructors validate up front.

AMICAMLXNG gains pcakeep/pcadb (same position, semantics and docs as AMICATorchNG), passes them to numerical_rank, gains _pca_reduction_requested and the same upfront mir_step gate and message as torch, and persists both additively in state_dict()["config"] (a payload without the keys loads with None; no format_version bump). Every MLX docstring, comment and error message that said MLX has no explicit pcakeep/pcadb now describes the new reality.

AMICATorchNG._pca_reduction_requested delegates to the shared predicate with the fitted data's channel count, so the gate no longer rejects pcakeep >= n_channels (the bundled input.param sets pcakeep 32 on the 32-channel sample). Both state_dicts store the request as plain int/float, because the validator accepts numpy scalars, which MLX's JSON config and torch's weights_only load both refuse.

Review round: _preprocess shrinks n_channels to the kept rank, and torch/MLX validated the next fit's X against that shrunk count, so 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. pcakeep/pcadb with do_sphere=False (which no backend, and not the reference, ever reduces: amica15.f90:527) now log one WARNING at construction and no longer trip the mir_step gate; the shared predicate takes do_sphere and validates first, and a new log_ignored_pca_request carries both log notes so validate_pca_reduction is validation only. Every torch_impl/core.py:<lines> citation in mlx_impl/core.py now names the symbol instead.

Docs: the differences guide gains the backend-table row "Explicit pcakeep/pcadb", an at-a-glance row recording pcadb as a pamica extension (the reference parses it at amica15.f90:3459-3461 and never uses it) and pcakeep's precedence, a pcakeep/pcadb section, 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 pcakeep through the AMICA wrapper for MLX) lands with Phase 4 (#313), which adds backend selection to the wrapper.

Behavior changes

  • Invalid pcakeep/pcadb now raise ValueError at construction on torch, NumPy and MLX. Previously torch and NumPy accepted them silently: pcakeep=-3 fitted 29 of 32 sources (negative slice), pcakeep=2.7 truncated to 2, and pcakeep=0 or pcadb <= 0 ended in nan_ll.
  • fit(mir_step > 0) no longer rejects pcakeep >= n_channels (torch). AMICA.from_params_file("input.param").fit(X, mir_step=1) used to raise; it now runs.
  • MLX accepts pcakeep/pcadb (previously a TypeError for an unknown keyword).
  • Setting both logs one INFO line at construction; the fit-time re-check is silent.
  • pcakeep/pcadb with do_sphere=False log one WARNING that they are ignored, and the mir_step gate no longer rejects them.
  • Refit and n_restarts > 1 after a rank reduction work on torch and MLX (previously ValueError: X has 32 channels, model expects 20).
  • A saved torch model whose config carries an invalid pcakeep/pcadb (only possible before this change) now fails to load with the validator's ValueError.
  • Default paths (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 .: clean
  • uv run ty check: all checks passed
  • pamica/tests/test_rank_policy.py: validator accept/reject table (including True, 2.7, 0, -3, "20", np.int64(5), nan/inf/0/-5 pcadb), predicate truth table, numerical_rank rejects invalid input, precedence logged once
  • New pamica/tests/test_pca_reduction_cross_backend.py on the real sample (torch and NumPy unconditional, MLX per-test importorskip); 53 of its original 61 tests fail on the pre-change sources (the module now has 95 tests):
    • (a) 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; asserted rtol=1e-10, atol=1e-13); torch vs MLX float32 sphere 3.6e-9, MLX float64 host sphere 3.5e-15; sldet agrees to 7e-15
    • (b) pcadb=18.5 keeps 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-16
    • (c) pcakeep=20, pcadb=30 gives the pcakeep-only sphere bit for bit on every backend (pcadb=30 alone keeps 26)
    • (d) 11 invalid requests raise ValueError at construction on all three backends
    • (e) torch and MLX both reject pcakeep=20, 31, pcadb=18.5, pcakeep=20+pcadb=30 up front (no sphere built) and accept pcakeep=32, 64, 32+pcadb=30 (fit completes, mir_history_ populated)
    • (f) torch float64 vs MLX float32, same seed, pcakeep=20, 10 iterations: min Hungarian-matched source |corr| 0.99999994 (threshold 0.999), identity matching, LL difference 1.9e-7 (threshold 1e-2, from test_mlx_backend.py). The test_mlx_*_cross_backend.py suites 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 gate
    • (g) MLX save/load keeps pcakeep/pcadb (as plain int/float from numpy-scalar input) and the reduced sphere; a state dict with both config keys deleted loads with None; torch AMICA.save/load round-trips a numpy-scalar request
  • Regression: AMICA.from_params_file(input.param).fit(X, max_iter=2, mir_step=1) passes (fails before the fix)
  • Review round, real sample, torch/NumPy/MLX (NumPy as control):
    • refit after pcakeep=20 and after automatic reduction (sample projected to rank 20) keeps (n, n_in) = (20, 32); torch and MLX reproduce the first fit's ll_history exactly (NumPy warm-starts from its fitted A, so only geometry is compared)
    • n_restarts=2, restart_seeds=[42, 43] with pcakeep=20 and with automatic reduction completes on all three: restart LLs [-3.989754, -3.98975], geometry (20, 32)
    • a wrong-width X after a reduced fit raises "X has 20 channels, model expects 32" (a 20-channel X used to be accepted)
    • torch state_dict and MLX save/load of a reduced model transform identically and refit
    • the 12 torch/MLX refit/restart/reload cases fail before the fix
    • do_sphere=False + pcakeep=20: all three fit full width with an identity sphere and warn once; torch and MLX accept mir_step=1 with it
    • pcakeep=-3/pcadb=-5.0 reassigned after construction raise at fit time on all three; a reassigned "20" raises the validator's ValueError at the torch/MLX mir_step gate
    • validator rejects numpy.bool_, accepts np.float32/np.float64 pcadb; torch payload without the two config keys loads with None
  • Review-round gate: uv 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 skipped
  • Full suite uv run pytest -q -n auto: 1126 passed, 14 skipped, 3 xfailed (27.6 min on a shared host)
  • mkdocs build --strict and typos pass

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.
@neuromechanist
neuromechanist merged commit 98e510e into feature/issue-324-epic-mlx-first-class Sep 22, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-323-phase1-pca-policy branch September 22, 2026 23:02
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