Repository navigation
Add convergence stops to the MLX backend - #255
Merged
Merged
Conversation
Port the Fortran/PyTorch stops to AMICAMLXNG (amica15.f90:1033-1097): use_min_dll/min_dll/maxincs, use_grad_norm/min_nd, and the likelihood-decrease branch's ndtmpsum <= min_nd half. Same parameter names, defaults and stop_reason strings as AMICATorchNG, so a config moved between the backends stops the same way instead of always running to max_iter. The gradient norm ndtmpsum (amica15.f90:1742-1743) is computed every iteration from the pre-step direction dAk; it is held as an unevaluated MLX scalar and materialized by fit()'s existing single per-iteration mx.eval, so the stops add no extra device sync.
Assert AMICAMLXNG stops at the same iteration, with the same stop_reason, as AMICATorchNG at a matched float32 config on the bundled sample EEG, for both min_dll and grad_norm. Thresholds are coarse (7e-4, 1.02e-2) so the ~1e-6 float32 backend difference cannot flip the trigger where the ~1e-4 crossing margin decides it. Also covers: ndtmpsum equals the norm of the step actually taken (recomputed from A before/after an M-step), the grad_norm_floor decrease-branch half and its shadowing under the shipped defaults, lrate_floor still firing on its own, the iter>1 guard on both stops, and a regression that the default thresholds leave a 100-iteration fit bit-identical to one with the stops disabled.
The backend table rows for min_dll and min_nd are now yes for MLX, and the section explaining the gap is replaced by what the backends now share.
neuromechanist
force-pushed
the
248-mlx-convergence-stops
branch
from
August 22, 2026 23:03
468dc7c to
e114ce7
Compare
Correct the amica15.f90 line numbers in the new MLX convergence-stop docstrings and comments (they were inherited off by ~18-20 lines): outer iter>1 gate 1051, decrease-branch ndtmpsum disjunct 1058, use_min_dll 1078-1090, use_grad_norm 1091-1097, ndtmpsum accumulation 1749-1761, update_params A step 1803-1815. Torch line references are now by method name so they cannot drift the same way. validation.md gains an MLX column in the stop-defaults table and now says min_nd is unreachable in any of the four implementations, matching the cross-reference in amica-differences.md. Changelog entry for issue #248.
# Conflicts: # docs/changelog.md # docs/guides/amica-differences.md
# Conflicts: # docs/changelog.md
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.
Closes #248.
What
AMICAMLXNGimplemented neither convergence stop, so an MLX fit always spent the whole iteration budget while every other backend stopped on likelihood stagnation. It now carries the full Fortran set, ported fromAMICATorchNGwith identical parameter names, defaults, semantics andstop_reasonstrings:stop_reasonuse_min_dll(True),min_dll(1e-9),maxincs(5)min_dlluse_grad_norm(True),min_nd(1e-7)grad_normmin_nd(runs regardless ofuse_grad_norm)grad_norm_floorThe gradient norm
ndtmpsum(amica15.f90:1742-1743) is now computed every iteration from the pre-step directiondAk, before thelratescaling and before the A update applies it, exactly where Fortran computes it. There is nocomp_usedmask: component sharing is absent from this backend, so every column is used and Fortran's mask is all-True.The three checks are structured exactly as in
AMICATorchNGand Fortran: independent blocks with no declared precedence, aleaveflag, and theiter > 1guard (amica15.f90:1033) so none can fire on the first iteration. The pre-existinglrate_floorstop keeps its behaviour and gains the.or. (ndtmpsum .le. min_nd)disjunct alongside it.Item 3 of the issue's scope: yes,
grad_norm_floorcomes alongThe issue left open whether the decrease branch's missing
.or. (ndtmpsum .le. min_nd)half should ship with the gradient norm.AMICATorchNGimplements it (torch_impl/core.py:2125,stop_reason="grad_norm_floor", issue #207 gap 3), so MLX mirrors it rather than diverging. Under the shippeduse_grad_norm=Truedefault the standalonegrad_normcheck shadows it, as it does on PyTorch; both behaviours are tested.Diagnostic attribute
AMICATorchNGstores only the latest value, in_ndtmpsum(no per-iteration history; its own convergence tests spy on_update_parametersto build one). MLX mirrors that name and scope. It differs in one mechanical detail, documented at the definition: the value is held as an unevaluated MLX scalar and materialized byfit's existing single per-iterationmx.eval, so the stops add no extra device sync, with_ndtmpsumas the host-float property the checks read. A default 100-iteration fit measures 15.7 ms/it after versus 16.1 ms/it before (noise), and reaches a bit-identicalfinal_ll_.Tests
New
pamica/tests/test_mlx_convergence_stops.py(10 tests, real bundled sample EEG only, no synthetic data or mocks), placed inpamica/tests/rather thanmlx_tests/per.rules/backend_parity.mdbecause the core assertions are cross-backend.test_min_dll_stops_at_the_same_iteration_as_torchandtest_grad_norm_stops_at_the_same_iteration_as_torchfit MLX andAMICATorchNGat a matched float32 configuration (same seed,block_size, thresholds) and require the same stop iteration and the samestop_reason. Exact equality, no tolerance window: thresholds are chosen coarse (min_dll=7e-4,min_nd=1.02e-2) so that at the crossing the two backends differ by about 1e-6 while the margin to the threshold is about 1e-4, a ~100x cushion. The shipped defaults cannot exercise either path on a recording this size (issue Document that min_nd is unreachable on small datasets in all three implementations #218), which is why the test values are not the defaults.test_grad_norm_is_the_norm_of_the_step_actually_takenis the independent oracle for the new quantity: with rescaling off and one model the applied step islrate * dAk, sodAkis recovered from A before and after an M-step and the Fortran formula recomputed from it. This is the check that would have caught the NumPy bug of issue numpy_impl log-likelihood is un-normalized, so min_dll can never fire #212.test_grad_norm_floor_fires_on_a_likelihood_decrease,test_grad_norm_shadows_grad_norm_floor_under_shipped_defaultsandtest_lrate_floor_still_fires_when_grad_norm_cannotcover the decrease branch from both sides of Fortran'sor.test_min_dll_never_fires_before_two_likelihoodsandtest_grad_norm_never_fires_before_two_likelihoodspin theiter > 1guard;test_negative_maxincs_is_rejectedpins the constructor validation.test_shipped_defaults_are_inert_on_a_100_iteration_fitis the regression guard: at the documented budget a default fit is bit-identical, iteration for iteration, to one with both stops disabled, so turning the stops on by default changes nothing that already worked.Gates
uv run ruff check .,uv run ruff format --check .,uv run ty check .all clean.uv run pytest -m "not slow" -n auto: 408 passed, 14 skipped, 1 xfailed. With themlxextra installed on Apple Silicon:pamica/tests/test_mlx_convergence_stops.py10 passed, and the pre-existingpamica/tests/mlx_tests/11 passed (including the 400-iterationrholratetests, which the now-default-on stops leave untouched).Note for follow-up
docs/guides/validation.mdstill saysmin_ndis unreachable "in any of the three implementations" and its defaults table has three columns. That statement is still true and now also true of MLX; adding the fourth column was left out of this PR to keep the doc edit scoped to theamica-differences.mdentry the issue named.