Skip to content

Phase 2: MLX keep_best - #310

Merged
neuromechanist merged 4 commits into
feature/issue-278-epic-mlx-parityfrom
feature/issue-288-phase2-mlx-keepbest
Sep 1, 2026
Merged

neuromechanist merged 4 commits into
feature/issue-278-epic-mlx-parityfrom
feature/issue-288-phase2-mlx-keepbest

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

  • Ports the Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51 best-iterate safeguard from AMICATorchNG onto AMICAMLXNG: 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 = True constructor parameter, same name/default/semantics as AMICATorchNG. _snapshot_params/_restore_params copy the 12 _PARAM_ARRAYS plus n_kurt_done (real mx.array copies, 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 excludes do_reject, which this backend does not have yet -- commented for Phase 3). A user enabling share_comps with keep_best on gets a one-time logger.warning explaining the safeguard is inactive.
  • ll_history is never rewritten; only final_ll_ and the fitted-parameter arrays roll back on a restore.
  • keep_best persists additively in state_dict()'s config dict -- no format_version bump (a payload without the key falls through cls(**config) to the constructor default True, same precedent as torch's min_dll convergence criterion missing from AMICATorchNG (present in numpy_impl and Fortran) #207).
  • Docs updated: docs/guides/amica-differences.md backend table + prose, docs/api/mlx-backend.md, AGENTS.md, .rules/backend_parity.md, docs/changelog.md Unreleased entry. Remaining MLX gap after this phase is do_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_params copy-not-alias roundtrip, a genuine forced-restore overshoot (measured on this machine: best_ll - last_ll = 0.00016760826110839844, recipe n_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=False on the first 4096 samples of the bundled 32-ch sample, max_iter=60), ll_history immutability across a restore, bit-identical truncated-refit comparison (max_iter=argmax reproduces the restored snapshot's 12 param arrays exactly -- verified empirically, not assumed, and documented as an off-by-one trap vs argmax+1), n_kurt_done/pdtype consistency under a pdftype=1 forced restore, the share_comps inactive warning + never-restores + bit-identical-to-off behavior, and state_dict persistence 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 the final_ll_ == max(ll_history) contract when keep_best is active, and both disable the safeguard identically under share_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 passed
  • uv 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 skipped
  • uv run ruff check . / uv run ruff format --check . / uv run ty check . -- all clean

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.
Backend table, gaps sentences (AGENTS.md, mlx-backend.md,
backend_parity.md) and changelog now reflect keep_best as
implemented on MLX; the remaining MLX gap is do_reject + LLt/MIR
(Phase 3).

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
neuromechanist merged commit c606f84 into feature/issue-278-epic-mlx-parity Sep 1, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-288-phase2-mlx-keepbest branch September 1, 2026 08:56
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