Skip to content

Add convergence stops to the MLX backend - #255

Merged
neuromechanist merged 6 commits into
devfrom
248-mlx-convergence-stops
Aug 23, 2026
Merged

neuromechanist merged 6 commits into
devfrom
248-mlx-convergence-stops

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #248.

What

AMICAMLXNG implemented 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 from AMICATorchNG with identical parameter names, defaults, semantics and stop_reason strings:

stop parameters stop_reason Fortran
consecutive small likelihood gain use_min_dll (True), min_dll (1e-9), maxincs (5) min_dll amica15.f90:1060-1072
weight-gradient norm use_grad_norm (True), min_nd (1e-7) grad_norm amica15.f90:1073-1079
gradient-norm half of the likelihood-decrease branch min_nd (runs regardless of use_grad_norm) grad_norm_floor amica15.f90:1040

The gradient norm ndtmpsum (amica15.f90:1742-1743) is now computed every iteration from the pre-step direction dAk, before the lrate scaling and before the A update applies it, exactly where Fortran computes it. There is no comp_used mask: 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 AMICATorchNG and Fortran: independent blocks with no declared precedence, a leave flag, and the iter > 1 guard (amica15.f90:1033) so none can fire on the first iteration. The pre-existing lrate_floor stop keeps its behaviour and gains the .or. (ndtmpsum .le. min_nd) disjunct alongside it.

Item 3 of the issue's scope: yes, grad_norm_floor comes along

The issue left open whether the decrease branch's missing .or. (ndtmpsum .le. min_nd) half should ship with the gradient norm. AMICATorchNG implements it (torch_impl/core.py:2125, stop_reason="grad_norm_floor", issue #207 gap 3), so MLX mirrors it rather than diverging. Under the shipped use_grad_norm=True default the standalone grad_norm check shadows it, as it does on PyTorch; both behaviours are tested.

Diagnostic attribute

AMICATorchNG stores only the latest value, in _ndtmpsum (no per-iteration history; its own convergence tests spy on _update_parameters to 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 by fit's existing single per-iteration mx.eval, so the stops add no extra device sync, with _ndtmpsum as 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-identical final_ll_.

Tests

New pamica/tests/test_mlx_convergence_stops.py (10 tests, real bundled sample EEG only, no synthetic data or mocks), placed in pamica/tests/ rather than mlx_tests/ per .rules/backend_parity.md because the core assertions are cross-backend.

  • test_min_dll_stops_at_the_same_iteration_as_torch and test_grad_norm_stops_at_the_same_iteration_as_torch fit MLX and AMICATorchNG at a matched float32 configuration (same seed, block_size, thresholds) and require the same stop iteration and the same stop_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_taken is the independent oracle for the new quantity: with rescaling off and one model the applied step is lrate * dAk, so dAk is 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_defaults and test_lrate_floor_still_fires_when_grad_norm_cannot cover the decrease branch from both sides of Fortran's or.
  • test_min_dll_never_fires_before_two_likelihoods and test_grad_norm_never_fires_before_two_likelihoods pin the iter > 1 guard; test_negative_maxincs_is_rejected pins the constructor validation.
  • test_shipped_defaults_are_inert_on_a_100_iteration_fit is 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 the mlx extra installed on Apple Silicon: pamica/tests/test_mlx_convergence_stops.py 10 passed, and the pre-existing pamica/tests/mlx_tests/ 11 passed (including the 400-iteration rholrate tests, which the now-default-on stops leave untouched).

Note for follow-up

docs/guides/validation.md still says min_nd is 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 the amica-differences.md entry the issue named.

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
neuromechanist force-pushed the 248-mlx-convergence-stops branch from 468dc7c to e114ce7 Compare August 22, 2026 23:03
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
@neuromechanist
neuromechanist merged commit d89f336 into dev Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the 248-mlx-convergence-stops branch August 23, 2026 00:32
@neuromechanist neuromechanist mentioned this pull request Aug 25, 2026
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.

MLX backend has no convergence stops: every fit runs to max_iter

1 participant