Repository navigation
Phase 2: MLX keep_best - #310
Merged
neuromechanist merged 4 commits intoSep 1, 2026
Merged
neuromechanist merged 4 commits into
neuromechanist merged 4 commits into
Conversation
Ports #51's snapshot/restore mechanism from AMICATorchNG onto AMICAMLXNG: fit() tracks the highest-LL iterate and restores it when the run ends more than _KEEP_BEST_TOL below that peak. Inactive under share_comps (a merge changes the parameter count, so an earlier snapshot cannot be reverted to without undoing it). Persisted additively in state_dict's config; ll_history is never rewritten. Epic #278 Phase 2, issue #288.
Covers the monotone no-op pin, a genuine forced-restore overshoot (measured, not assumed), ll_history immutability, bit-identical truncated-refit comparison, n_kurt_done/pdtype consistency under pdftype=1, the share_comps disable, and state_dict persistence (including additive-compat for a payload missing the key). All bit-identity checks run within a single test process to stay safe against MLX's cross-GPU float32 non-reproducibility. A cross-backend companion asserts the shared restore CONTRACT (final_ll_ == max(ll_history) when active) without asserting decision equality between PyTorch's float64 and MLX's float32 trajectories. Epic #278 Phase 2, issue #288.
PR #310 review additions: the restore guard's refusal to rescue a diverged fit that peaked earlier is now pinned in both the MLX and torch backends via the sanctioned error-injection subclass (real iterations, then a forced nan_ll, asserting no restore and bit- identity with keep_best=False); and the keep_best x n_restarts composition is pinned (restart_lls_ reports the restored iterate, bit-identical to a standalone fit's final_ll_). The grad_norm-stop recipe variant is deliberately skipped: the guard is a set-membership test on stop_reason, so nan_ll alone covers the branch. Tested: 13 keepbest tests + torch twin pass; ruff and ty clean.
neuromechanist
merged commit Sep 1, 2026
c606f84
into
feature/issue-278-epic-mlx-parity
8 checks passed
This was referenced Sep 1, 2026
Closed
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
AMICATorchNGontoAMICAMLXNG:fit()now tracks the highest-log-likelihood iterate across an EM run and, when the run ends more than_KEEP_BEST_TOL(1e-9, same constant as torch) below that peak, restores the peak's parameters instead of returning the last iterate.keep_best: bool = Trueconstructor parameter, same name/default/semantics asAMICATorchNG._snapshot_params/_restore_paramscopy the 12_PARAM_ARRAYSplusn_kurt_done(realmx.arraycopies, not aliases). No LLt stash (MLX has none until epic Epic: MLX backend non-fitting parity #278 Phase 3; the snapshot docstring marks the spot to extend then).track_best = self.keep_best and not self.share_comps(torch also excludesdo_reject, which this backend does not have yet -- commented for Phase 3). A user enablingshare_compswithkeep_beston gets a one-timelogger.warningexplaining the safeguard is inactive.ll_historyis never rewritten; onlyfinal_ll_and the fitted-parameter arrays roll back on a restore.keep_bestpersists additively instate_dict()'sconfigdict -- noformat_versionbump (a payload without the key falls throughcls(**config)to the constructor defaultTrue, same precedent as torch's min_dll convergence criterion missing from AMICATorchNG (present in numpy_impl and Fortran) #207).docs/guides/amica-differences.mdbackend table + prose,docs/api/mlx-backend.md,AGENTS.md,.rules/backend_parity.md,docs/changelog.mdUnreleased entry. Remaining MLX gap after this phase isdo_reject+ LLt/MIR (Phase 3, Phase 3: MLX outlier rejection and LLt/MIR #289).Closes #288
Part of epic #278
Test plan
pamica/tests/mlx_tests/test_mlx_keepbest.py(new, 14 tests): monotone no-op bit-identity (keep_best on vs off, same process),_snapshot_params/_restore_paramscopy-not-alias roundtrip, a genuine forced-restore overshoot (measured on this machine:best_ll - last_ll = 0.00016760826110839844, recipen_models=2, n_mix=3, seed=0, block_size=1024, do_newton=True, newt_start=1, lrate=0.5, use_min_dll=True, min_dll=1e-4, maxincs=2, use_grad_norm=Falseon the first 4096 samples of the bundled 32-ch sample,max_iter=60),ll_historyimmutability across a restore, bit-identical truncated-refit comparison (max_iter=argmaxreproduces the restored snapshot's 12 param arrays exactly -- verified empirically, not assumed, and documented as an off-by-one trap vsargmax+1),n_kurt_done/pdtypeconsistency under apdftype=1forced restore, theshare_compsinactive warning + never-restores + bit-identical-to-off behavior, andstate_dictpersistence including additive-compat for a payload with the key deleted.pamica/tests/test_mlx_keepbest_cross_backend.py(new, 3 tests): both backends independently satisfy thefinal_ll_ == max(ll_history)contract whenkeep_bestis active, and both disable the safeguard identically undershare_comps-- no decision-equality assertion across the float64/float32 trajectories, per the epic's backend-parity rules.uv run pytest pamica/tests/mlx_tests/ -q-- 187 passeduv run pytest pamica/tests/test_restart_policy.py pamica/tests/test_mlx_transform_cross_backend.py -q-- 42 passed, 1 skipped (pre-existing, unrelated NumPy skip)uv run pytest pamica/tests/mlx_tests/ pamica/tests/test_restart_policy.py pamica/tests/test_mlx_transform_cross_backend.py pamica/tests/test_mlx_keepbest_cross_backend.py -q-- 232 passed, 1 skippeduv run ruff check ./uv run ruff format --check ./uv run ty check .-- all clean