Skip to content

Phase 2: port share_comps to the MLX backend - #268

Merged
neuromechanist merged 9 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-263-phase2-mlx-sharing
Aug 23, 2026
Merged

neuromechanist merged 9 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-263-phase2-mlx-sharing

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Phase 2 of epic #260 ports the full share_comps mechanism from AMICATorchNG to AMICAMLXNG. The backend gains share_comps/share_start/share_iter/comp_thresh (same names, defaults and gated validation as torch, including share_iter > 6 because the post-merge A-freeze is 6 iterations long), the fit-time merge schedule with its mandatory W rebuild, _a_frozen() (a verbatim port of the share_start-anchored window), comp_used masking of the alpha/mu/beta/rho updates and of the ndtmpsum gradient norm, the post-merge A-freeze on the step and its lrate ramp, _pinv_sphere() over a retained float64 host sphere, and the comp_used / shared_components() accessors. Save/load, keep_best and outlier rejection are out of scope (absent from this backend entirely).

The merge scan is deliberately NOT reimplemented: _identify_shared_comps calls pamica.numpy_impl.utils.identify_shared_components on host float64 arrays (pinv(sphere) @ A, the sensor-space metric Phase 1 unified in #266), so there is no third copy of the decision to drift. comp_used is a cached mx.array here rather than a per-call derivation as in torch, for a simpler reason than the first draft of its docstring claimed (review item 9): the merge kernel already derives the mask host-side as part of the decision it returns, so caching that result is free and keeps the mask fixed for exactly the lifetime the M-step needs. The semantics are identical (the mask always tracks the merged comp_list, and it is reset all-True in _initialize_parameters so a re-fit cannot inherit a merged mask).

Sharing off is bit-identical, and that is the invariant the whole port rests on: the mx.where masks are all-True, the ndtmpsum mask selects nd unchanged and counts n_comps, the relocated lrate ramp still feeds only the step it now sits with, and gm_prev cancels against zeta for a disjoint comp_list. (One scoping correction from review item 10: that statement is about this code with sharing off versus scheduled-but-never-fired. Relative to the PREVIOUS release, only n_models=1 is byte-for-byte; a default multi-model fit is analytically unaffected by the gm_prev fix but rounds differently, at most 2.98e-8 in dAk / 3.7e-9 in A on the bundled sample, because the two gm snapshots genuinely differ. The changelog now says exactly that.) test_unscheduled_sharing_is_bit_identical enforces it for n_models 1 and 2 by comparing share_comps=False against share_comps=True, share_start=10**6: identical ll_history lists, and assert_array_equal on A, mu, gm and _ndtmpsum. Every pre-existing MLX test, including the multi-model-vs-torch LL comparison, passes unchanged; no pinned expectation shifted and no tolerance was touched.

The gm_prev change is a deliberate bug fix (the twin of torch issue #219): Fortran builds dAk in accum_updates_and_likelihood (amica15.f90:1749-1761) before update_params reassigns gm (:1788), and MLX was weighting with the just-updated gm. Measured discrimination, one iteration from a matched real-data state against a float64 AMICATorchNG twin holding the identical parameters and sphered data: on a merged (shared) column the max |dA| is 7.9e-7 with the fix and 9.9e-3 with the line locally reverted, a four-order separation, which the test's 1e-4 tolerance sits between; the revert was measured and discarded, not committed. On a DISJOINT comp_list the same revert leaves the gap at 4.6e-8, i.e. unchanged float32 noise, because gm[h] cancels against zeta[c] = gm[h] analytically when every column has one contributor. That is why the discrimination test runs on a shared column (see deviations); the disjoint parametrization is kept as the plain one-iteration cross-backend pin. The same test also pins the ndtmpsum masking cross-backend: dropping the mask on the merged state divides by n_comps instead of n_comps - 1, a 0.8% shift that fails the rel=1e-4 comparison against torch's own masked norm. Behavior change for n_models >= 2 is limited to fits that actually share components; single-model and default multi-model fits are unchanged.

Cross-backend merge decision (acceptance test, test_merge_decision_matches_the_torch_backend): from one real fitted 2-model MLX state with one cross-model column perturbed into near-collinearity, A / the float64 _sphere_np / comp_list are copied into an AMICATorchNG and both backends run their own _identify_shared_comps. The threshold is read off the data (midway between the top cross-model cosine, 0.99999, and the runner-up, 0.99978) so exactly one pair is above it. Result: the resulting comp_list arrays are equal element-for-element, the unique count drops by exactly 1 (non-vacuous), and MLX's cached comp_used equals torch's derived mask.

Deviations from the approved plan, all listed:

  • Test (f) as written in the plan ("run ONE iteration of both backends on the same real X with n_models=2 (sharing off), assert A agrees to float32 tolerance") cannot discriminate the gm_prev fix, and no iteration count fixes that: with a disjoint comp_list the weight cancels analytically, so reverting the line changes A only by float32 rounding (4.557e-8 reverted versus 4.579e-8 with the fix, i.e. the same noise floor). Rather than pin noise amplification, the test keeps the plan's structure, oracle and assertion and is parametrized over the state it runs on: merged=False is the plan's literal case (kept as a cross-backend pin) and merged=True adds one forced merged column, which is the only place the weighting is observable. The plan's fallback ("use the earliest iteration count that does") was not usable for the reason above.
  • The plan's freeze test (e) asserts the lrate ramp is held with the step. The MLX ramp is min(lrate_cap, lrate + min(1/newt_ramp, lrate)) and lrate_cap == lrate0, so it saturates on the first iteration and never moves again in a hand-driven loop. The test therefore starts the window from 0.25 * lrate_cap (the state fit's LL-decrease branch leaves behind), which is what makes "held during the window, ramps at +6" observable at all; the reason is in a comment.
  • Two small additions beyond the plan's list: pamica/mlx_impl/__init__.py's docstring still said sharing was a fast-follow, and _pinv_sphere() raises a RuntimeError when called before _preprocess (the plan named only the non-finite guard); both are covered by tests.
  • The plan's docs list is done as specified (capability table row, changelog, AGENTS.md line 71), plus one sentence appended to the existing "Component sharing on rank-reduced fits" section so its "the two backends therefore agree" claim is not left stale.

Review response

All 19 findings from the four specialist reviewers and the deep-dive panel are addressed. Code: the ndtmpsum mask is now a mx.where select rather than a multiply, because 0*NaN is NaN and a NaN gradient norm silently disables BOTH grad-norm stops (NaN <= min_nd is False) — unreachable today, since a merged-away column's dAk is exactly zero, but Phase 3's Newton direction feeds the same dAk; fit's finiteness guard now also covers _nd_arr and names which tensors went non-finite (the MLX stand-in for torch's inline mu/beta/alpha canary, which MLX cannot afford mid-graph); comp_used raises RuntimeError before a fit in both backends (the PyTorch side used a bare assert, stripped under python -O); and the rho update carries a comment recording that torch's all-1.0/all-2.0 early-exit is deliberately NOT ported, since it needs a per-iteration host sync while mx.clip already yields identical results.

Comments and docs: every torch_impl cross-reference in mlx_impl/core.py was re-verified against the current file and re-pointed (seven were named in review, four more of the same class were found and fixed in the same pass: _initialize_parameters, _forward, _get_block_updates, _log_pdf_only); the dAk/zeta Fortran citation is amica15.f90:1749-1761, corrected here and in the one authorized torch_impl comment; the merged-away-column note no longer claims the column is zero-norm and skipped by doscaling (it is rescaled like any other, by its own retained ~unit norm, which is why the freeze test disables doscaling); issue #219 is now cited as the origin of the gm ordering question rather than as a PyTorch fix; the comp_used caching rationale is replaced with the real one; the row-8 reference names the "At a glance" table; and the four share parameters are documented in the AMICAMLXNG class docstring.

Tests: the two cross-backend tests and the _torch_twin helper moved to pamica/tests/test_mlx_sharing_cross_backend.py, outside any one backend's subdirectory per .rules/backend_parity.md (the test_mlx_convergence_stops.py precedent), leaving the MLX-only mechanics in mlx_tests/. Five tests were added: a merge landing on the final iteration, a convergence stop firing while A is frozen (reproduced exactly as the reviewer described — stop_reason="grad_norm" at itf=2 with ndtmpsum=0.0315 <= min_nd=0.04, inside the freeze window [1, 6], with a merge already applied), a 3-model sharing fit, a rank-reduced sharing fit through the non-square pinv(sphere) path, and a second merge scan that must not resurrect columns folded away by the first.

Two review suggestions were deliberately not taken. (a) An MLX test for multi-pair merges in a single scan: the count logic lives entirely in the shared NumPy kernel and is already pinned by the NumPy and PyTorch suites; MLX contributes no per-count code, so such a test would re-test someone else's module through a thin wrapper. (b) The literal port of torch's rho early-exit: it is replaced by the documented-divergence comment above, because the guard needs a host sync on rho every iteration and would break this backend's one-mx.eval-per-iteration graph for no change in results. Two design points also worth flagging rather than silently encoding: the rho divergence just described, and final_ll_ deliberately trailing a merge that lands on the last iteration (Fortran runs identify_shared_comps after the iteration's likelihood accumulation, so the merged model is never scored) — the new final-iteration test pins that as behavior, and issue #269 tracks documenting it across backends.

Gates, all run from the worktree after the review fixes: pytest pamica/tests/mlx_tests/ pamica/tests/test_mlx_sharing_cross_backend.py pamica/tests/torch_tests/test_ng_sharing.py pamica/tests/test_numpy_share_comps.py -q --no-cov gives 82 passed; pytest -m "not slow" -n auto gives 455 passed, 15 skipped, 1 xfailed; ruff check ., ruff format --check . and ty check . are clean with zero new diagnostics. The MLX tests really ran (Apple Silicon, MLX 0.32, GPU device), they are not skipped here.

Closes #263

Part of epic #260

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.
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.
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.
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.
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.
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.
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.
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/.
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).
@neuromechanist
neuromechanist merged commit a0e95c4 into feature/issue-260-epic-mlx-parity Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-263-phase2-mlx-sharing branch August 23, 2026 07:30
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