Skip to content

Epic: MLX backend feature parity - #276

Merged
neuromechanist merged 4 commits into
devfrom
feature/issue-260-epic-mlx-parity
Aug 23, 2026
Merged

neuromechanist merged 4 commits into
devfrom
feature/issue-260-epic-mlx-parity

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Brings the MLX backend (AMICAMLXNG) to feature parity with AMICATorchNG on the four gaps tracked by the epic: component sharing, Newton acceleration, and the non-GG source-density families, with the numpy sharing metric unified first so all backends share one merge-decision contract. Every phase was implemented against a lead-approved plan, reviewed by the pr-review-toolkit specialists with all findings addressed or explicitly rejected with reasons, and merged only on green CI (including the macOS Apple Silicon job, which runs the MLX suites on real GPU hardware).

Closes #260

Phases completed

  1. Phase 1 (share_comps similarity space differs: torch sensor-space, numpy sphered-space #258, PR Phase 1: sensor-space sharing similarity for numpy #266): sensor-space sharing similarity for numpy — both pre-existing backends now measure share_comps similarity on de-sphered sensor-space maps (pinv(sphere) @ A), the Fortran Spinv semantics, with a cross-backend merge-decision acceptance test.
  2. Phase 2 (Phase 2: Port share_comps to the MLX backend #263, PR Phase 2: port share_comps to the MLX backend #268): MLX share_comps — comp_used-masked M-step, gm_prev-weighted shared A-update (a latent multi-model bug fix), sensor-space merge scan reusing the shared numpy decision kernel, post-merge A-freeze, masked gradient norm; sharing-off path bit-identical.
  3. Phase 3 (Phase 3: Port Newton acceleration to the MLX backend #264, PR Phase 3: port Newton to the MLX backend #271): MLX Newton — curvature accumulators, closed-form GPU-resident direction, full newtrate schedule; pre-registered float32 go/no-go came back GO with 2-3 orders of margin (curvature ~4e-7 vs float64 torch, matched-budget LL within 1e-5, zero fallbacks, conditioning margin ~2.0); also fixes the numpy multi-model Newton broadcast crash (numpy Newton crashes when sharing collapses a whole model #267).
  4. Phase 4 (Phase 4: Port non-GG pdf families to the MLX backend #265, PR Phase 4: port non-GG pdf families to the MLX backend #275): MLX non-GG pdf families — all five pdftype families plus the ext-Infomax kurtosis switcher; fixed families match the literal-Fortran forms within float32 and the float64 torch LL to ~1e-7; pdftype=0 verified bit-identical; the switcher is behavior-validated (dead code in the reference binary, no bit oracle).

Test plan

  • All phase PRs individually reviewed (pr-review-toolkit panels) and gated: full non-slow suite green per phase (final: 519 passed), targeted MLX/cross-backend suites green on Apple GPU, ruff/ty clean.
  • CI green on every phase head, including Test (macOS 26, Apple Silicon) which executes the MLX tests on real hardware.
  • Gate evidence recorded in .context/issue-264/ (Newton go/no-go) and .context/issue-265/ (pdf families).

Merge note: this PR should be merged with a REGULAR merge commit (not squash) to preserve the four per-phase commits on dev.

* Port sensor-space sharing similarity to numpy (#258)

identify_shared_components now takes de-sphered sensor-space maps
(pinv(sphere) @ A), mirroring AMICATorchNG._identify_shared_comps and
the Fortran identify_shared_comps/Spinv back-map (amica15.f90:1916,
:568-578) exactly, instead of comparing raw sphered A columns. Adds a
cached, guarded _pinv_sphere() (mirrors AMICATorchNG._pinv_sphere),
invalidated wherever self.sphere is reassigned, also used to refactor
get_sensor_mixing_matrix. The merge log moves to the call site since
the function is now stateless.

Updates the two direct callers of the old 4-arg signature and adds
cross-backend and rank-reduced sharing tests.

* Document numpy sensor-space sharing change (#258)

The amica-differences guide's numpy-compares-in-sphered-space passage
(added with #256) is resolved: both backends now compare sensor-space
maps, so it is rewritten with the current state and a concrete cosine
example. Changelog gets one Unreleased bullet.

* Fix docstring test cross-reference
* Port share_comps to the MLX backend

AMICAMLXNG gains share_comps/share_start/share_iter/comp_thresh with
AMICATorchNG's names, defaults and validation: the merge schedule, the
6-iteration post-merge A-freeze, comp_used masking of the mixture updates
and the gradient norm, and comp_used/shared_components() accessors. The
merge decision reuses numpy_impl.utils.identify_shared_components on host
float64 pinv(sphere) @ A rather than adding a third copy of the scan.

The A-update now weights dAk with the previous iteration's gm (Fortran
builds dAk before update_params reassigns gm; the twin of issue #219),
which is observable only on a shared column. Sharing off is bit-identical:
all-True masks, nd * 1.0, and gm cancelling against zeta for a disjoint
comp_list.

Tested: pamica/tests/mlx_tests/ green on Apple Silicon.

* Add MLX component-sharing tests

Real sample EEG only, same Apple-GPU/sample-data guards as
test_mlx_backend.py. Covers the bit-identical unscheduled path (1 and 2
models), the cross-backend merge decision against AMICATorchNG, an
end-to-end sharing fit, merged-away column freezing, the A-freeze window,
constructor validation, and the degenerate-sphere guard.

The gm-weighting test runs both parametrizations: the disjoint comp_list
(where gm cancels analytically, so it cannot discriminate) and a merged
column, where reverting to the post-update gm moves A by 9.9e-3 against
7.9e-7 with the fix.

* Document MLX component sharing

amica-differences.md flips the MLX capability row and records that the
merge decision comes from the shared numpy kernel; changelog notes the
port and the gm_prev behavior change for n_models>=2; AGENTS.md drops
sharing from the MLX follow-up list.

* Harden the MLX sharing failure paths

The ndtmpsum comp_used mask becomes a where-select: 0*NaN is NaN, so a
multiply would let one non-finite column poison the whole reduction, and a
NaN ndtmpsum silently disables both grad-norm stops (NaN <= min_nd is
False). Unreachable today, but Phase 3's Newton direction feeds the same
dAk. Bit-identical when every column is used.

fit()'s finiteness guard now covers _nd_arr as well and names the tensors
that went non-finite, which is the MLX stand-in for the PyTorch backend's
inline mu/beta/alpha canary (MLX cannot afford that check mid-graph).
comp_used raises RuntimeError before a fit instead of returning None.

* Fix MLX sharing comments and citations

Every torch_impl cross-reference in this file was verified against the
current file and re-pointed; the dAk/zeta accumulation is amica15.f90
:1749-1761, not :1731-1743. The merged-away-column note claimed the column
is zero-norm and skipped by the rescale, which is wrong: it is rescaled
like any other, by its own retained ~unit norm, which is why the freeze
test disables doscaling.

Also records the deliberate divergence at the rho update (torch's
all-1.0/all-2.0 early-exit is skipped here because it needs a per-iteration
host sync; mx.clip gives identical results), replaces the comp_used caching
rationale with the real one, and documents the four share parameters in the
class docstring.

* Fix torch comp_used guard and dAk citation

comp_used raised through a bare assert, which python -O strips, turning a
pre-fit read into an obscure NoneType error; it now raises RuntimeError
like every other accessor. The gm_prev comment cited amica15.f90:1731-1743
for the dAk/zeta accumulation, which is :1749-1761, and attributed the fix
to issue #219 rather than the ordering question it raised.

* Scope the MLX gm claim in the changelog

Only single-model fits are byte-for-byte unchanged by the gm_prev fix: a
default disjoint multi-model fit is analytically unaffected but rounds
differently, up to 2.98e-8 in dAk on the bundled sample. Also re-attributes
issue #219 as the origin of the ordering question and points the row-8
reference at the At a glance table.

* Split out the cross-backend sharing tests

The merge-decision and gm-weighting tests pin MLX against AMICATorchNG, so
per .rules/backend_parity.md they belong in pamica/tests/ rather than one
backend's subdirectory (same placement as test_mlx_convergence_stops.py).
Adds a guard test that comp_used raises before a fit in both backends. The
MLX-only mechanics stay in mlx_tests/.

* Add MLX sharing edge-case tests

A merge landing on the final iteration (final_ll_ deliberately trails the
merge, as in Fortran; issue #269 tracks documenting that), a convergence
stop firing while A is frozen (the #207 design that ndtmpsum is computed
every iteration), a 3-model sharing fit, a rank-reduced fit through the
non-square pinv(sphere) path (#221/#253), and a second merge scan that must
not resurrect columns folded away by the first (#240).
* Fix multi-model Newton broadcast in numpy

* Port Newton to the MLX backend

* Test MLX Newton against torch and numpy

* Record the MLX Newton float32 gate evidence

* Document MLX Newton support

* Derive Newton schedule tests from the run

* Guard derived W and fix Newton citations

* Extend MLX Newton test coverage

* Correct stale cross-file citations
* feat: port non-GG pdf families to MLX backend

* test: add MLX pdf family test coverage

* docs: update for MLX pdf family support

* fix: validate pdtype codes, add PDFTYPE_NAMES

* test: close mutation-confirmed mlx pdf gaps

* docs: fix comment accuracy in pdf family port
@neuromechanist
neuromechanist merged commit f6cb1fa into dev Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-260-epic-mlx-parity branch August 23, 2026 16:58
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.

Epic: MLX backend feature parity

1 participant