Repository navigation
Phase 2: port share_comps to the MLX backend - #268
Merged
neuromechanist merged 9 commits intoAug 23, 2026
Merged
neuromechanist merged 9 commits into
neuromechanist merged 9 commits into
Conversation
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
merged commit Aug 23, 2026
a0e95c4
into
feature/issue-260-epic-mlx-parity
8 checks passed
This was referenced Aug 23, 2026
Merged
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.
Phase 2 of epic #260 ports the full
share_compsmechanism fromAMICATorchNGtoAMICAMLXNG. The backend gainsshare_comps/share_start/share_iter/comp_thresh(same names, defaults and gated validation as torch, includingshare_iter > 6because 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_usedmasking of the alpha/mu/beta/rho updates and of thendtmpsumgradient norm, the post-merge A-freeze on the step and its lrate ramp,_pinv_sphere()over a retained float64 host sphere, and thecomp_used/shared_components()accessors. Save/load,keep_bestand outlier rejection are out of scope (absent from this backend entirely).The merge scan is deliberately NOT reimplemented:
_identify_shared_compscallspamica.numpy_impl.utils.identify_shared_componentson 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_usedis a cachedmx.arrayhere 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 mergedcomp_list, and it is reset all-True in_initialize_parametersso 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.wheremasks are all-True, the ndtmpsum mask selectsndunchanged and countsn_comps, the relocated lrate ramp still feeds only the step it now sits with, andgm_prevcancels againstzetafor a disjointcomp_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, onlyn_models=1is byte-for-byte; a default multi-model fit is analytically unaffected by thegm_prevfix but rounds differently, at most 2.98e-8 indAk/ 3.7e-9 inAon the bundled sample, because the twogmsnapshots genuinely differ. The changelog now says exactly that.)test_unscheduled_sharing_is_bit_identicalenforces it forn_models1 and 2 by comparingshare_comps=Falseagainstshare_comps=True, share_start=10**6: identicalll_historylists, andassert_array_equalon 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_prevchange is a deliberate bug fix (the twin of torch issue #219): Fortran buildsdAkinaccum_updates_and_likelihood(amica15.f90:1749-1761) beforeupdate_paramsreassignsgm(:1788), and MLX was weighting with the just-updatedgm. Measured discrimination, one iteration from a matched real-data state against a float64AMICATorchNGtwin 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 DISJOINTcomp_listthe same revert leaves the gap at 4.6e-8, i.e. unchanged float32 noise, becausegm[h]cancels againstzeta[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 byn_compsinstead ofn_comps - 1, a 0.8% shift that fails therel=1e-4comparison against torch's own masked norm. Behavior change forn_models >= 2is 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_listare copied into anAMICATorchNGand 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 resultingcomp_listarrays are equal element-for-element, the unique count drops by exactly 1 (non-vacuous), and MLX's cachedcomp_usedequals torch's derived mask.Deviations from the approved plan, all listed:
comp_listthe 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=Falseis the plan's literal case (kept as a cross-backend pin) andmerged=Trueadds 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.min(lrate_cap, lrate + min(1/newt_ramp, lrate))andlrate_cap == lrate0, so it saturates on the first iteration and never moves again in a hand-driven loop. The test therefore starts the window from0.25 * lrate_cap(the statefit'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.pamica/mlx_impl/__init__.py's docstring still said sharing was a fast-follow, and_pinv_sphere()raises aRuntimeErrorwhen called before_preprocess(the plan named only the non-finite guard); both are covered by tests.Review response
All 19 findings from the four specialist reviewers and the deep-dive panel are addressed. Code: the
ndtmpsummask is now amx.whereselect rather than a multiply, because0*NaNisNaNand a NaN gradient norm silently disables BOTH grad-norm stops (NaN <= min_ndis False) — unreachable today, since a merged-away column'sdAkis exactly zero, but Phase 3's Newton direction feeds the samedAk;fit's finiteness guard now also covers_nd_arrand 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_usedraisesRuntimeErrorbefore a fit in both backends (the PyTorch side used a bareassert, stripped underpython -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 whilemx.clipalready yields identical results.Comments and docs: every
torch_implcross-reference inmlx_impl/core.pywas 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); thedAk/zetaFortran citation isamica15.f90:1749-1761, corrected here and in the one authorizedtorch_implcomment; the merged-away-column note no longer claims the column is zero-norm and skipped bydoscaling(it is rescaled like any other, by its own retained ~unit norm, which is why the freeze test disablesdoscaling); issue #219 is now cited as the origin of thegmordering question rather than as a PyTorch fix; thecomp_usedcaching 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 theAMICAMLXNGclass docstring.Tests: the two cross-backend tests and the
_torch_twinhelper moved topamica/tests/test_mlx_sharing_cross_backend.py, outside any one backend's subdirectory per.rules/backend_parity.md(thetest_mlx_convergence_stops.pyprecedent), leaving the MLX-only mechanics inmlx_tests/. Five tests were added: a merge landing on the final iteration, a convergence stop firing whileAis frozen (reproduced exactly as the reviewer described —stop_reason="grad_norm"at itf=2 withndtmpsum=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-squarepinv(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
rhoevery 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, andfinal_ll_deliberately trailing a merge that lands on the last iteration (Fortran runsidentify_shared_compsafter 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-covgives 82 passed;pytest -m "not slow" -n autogives 455 passed, 15 skipped, 1 xfailed;ruff check .,ruff format --check .andty 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