Skip to content

Phase 11: follow the reference's iteration order - #348

Merged
neuromechanist merged 19 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-339-phase11-loop-order
Sep 23, 2026
Merged

neuromechanist merged 19 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-339-phase11-loop-order

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Every backend (PyTorch, NumPy and MLX) now runs each iteration in the reference's order (amica15.f90:949-1142): the E-step computes the log-likelihood, the sufficient statistics, the step for A and its norm; then the non-finite check, the likelihood-decrease response (halve lrate, scale the working rho rate, count numdecs, ratchet the ceilings at maxdecs through schedule), min_dll, the gradient-norm stop and the Newton-switch reset run; a fit that stops leaves before any parameter moves (:1111); otherwise the parameters are updated with the rates just set (:1122), then checkpoints are written, then outlier rejection runs (:1136). _update_parameters is split into _update_direction (direction and norms) and the update that applies it, sharing one set of intermediates (issue #339).

The reference holds the A update, its lrate ramp and its reset of the working rho rate on every iteration with iter >= share_start and mod(iter, share_iter) <= 5 (amica15.f90:1803), whether or not share_comps is on. All three backends now apply exactly that through schedule.share_freeze, replacing the anchored window that applied only under share_comps with two or more models, and every backend rejects share_iter (NumPy share_int) below 7 whether or not sharing is on (issue #345).

After review, every backend also meets a non-finite value the same way: a non-finite likelihood is never recorded in the history (NumPy used to record it), a non-finite step or gradient norm stops the fit before the update (new degenerate stop_reason "nan_direction"), and non-finite parameters right after an update stop PyTorch and NumPy as they already stopped MLX ("nan_params"). share_start is now validated (>= 1) on every fit, the share_iter message says why, saved learning rates are validated on load, and NumPy's restart clears numincs as the reference does.

Part of epic #324; resolves #339 and #345 (closes when the epic merges to dev).

Behavior change

  • A likelihood decrease takes effect in the same iteration's update (before: one iteration late).
  • A fit that stops on a convergence check (min_dll, grad_norm, grad_norm_floor, lrate_floor) returns the parameters whose log-likelihood is ll_history[-1]; final_ll_ (without a keep-best restore) is exactly their log-likelihood. A max_iter fit still updates on its last iteration, as the reference does.
  • Every fit that reaches share_start (iteration 100 by default) holds A on the reference's iterations (100-105, 200-205, ... with the defaults).
  • A non-finite step, gradient norm or post-update parameter ends the fit as degenerate (nan_direction/nan_params) instead of being applied or returned; a PyTorch corruption on the last iteration used to end as max_iter.
  • Fits with no decrease, no convergence stop and fewer than share_start iterations are byte-identical to before on every backend (checked on 8 configurations x 3 backends for the split, and for the reorder on fits without decreases or stops).

Oracle numbers (native binary, opt-in AMICA_RUN_FORTRAN=1)

pamica/tests/test_iteration_order_native_oracle.py. Noise floor = the larger deviation of a 2- or 4-thread binary run from the 1-thread run. The multi-threaded runs are not reproducible, so the floor varies from run to run; the ranges below are over three runs (the pamica numbers are reproducible). Gate: 10x that floor; the pre-change code (epic base 5b6ae4f) must be over 100x.

#339 run (30 iterations, seeded, no Newton, lrate=0.5, doscaling on) max LL gap max A gap
decreases: pre-change 1.39e-2 2.19e-1
decreases: PyTorch after 2.7e-5 8.1e-4
decreases: NumPy after 8.2e-5 6.8e-4
decreases: binary floor 4.1e-5 to 1.3e-4 5.3e-4 to 1.2e-3
maxdecs ratchet: pre-change 1.29e-2 1.41e-1
maxdecs ratchet: PyTorch after 6.6e-6 3.0e-4
maxdecs ratchet: NumPy after 8.6e-6 2.7e-4
maxdecs ratchet: binary floor 5.7e-6 to 9.6e-6 1.4e-4 to 4.2e-4

Every decrease falls on the binary's iterations (0-based [6, 7, 10, 13, 16, 23, 25, 28] and [6, 7, 15, 18]). No-decrease floor (lrate=0.05): PyTorch 3.7e-6 / 5.9e-5, NumPy 7.0e-6 / 1.1e-4, binary against itself 3.1e-6 / 4.2e-5 (one component at rho=1 amplifies round-off, as recorded in Phase 9).

#345 run (16 iterations, share_comps off, share_start=3, share_iter=10) max LL gap max A gap
pre-change (worst of doscaling on/off) 6.1e-3 1.9e-1
doscaling on: PyTorch / NumPy / binary floor 6.6e-7 / 4.4e-7 / 4.0e-7 to 4.3e-7 5.0e-6 / 5.6e-6 / 4.3e-6 to 7.5e-6
doscaling off: PyTorch / NumPy / binary floor 4.0e-7 / 8.0e-7 / 4.3e-7 to 6.1e-7 1.3e-5 / 1.2e-5 / 1.2e-5 to 1.5e-5

The held iterations read from the binary's own per-iteration A history are exactly the reference arithmetic's (3-5, 10-15). On them the binary's A is unchanged exactly with doscaling off, and changes by at most 3.3e-16 (the rescale) with it on.

Parity before and after

validate_implementations.py --backend all (100 iterations, seed 42):

backend LL gap before / after mean matched corr before / after min before / after Amari before / after
PyTorch 2.61e-4 / 2.61e-4 0.9988 / 0.9991 0.9891 / 0.9921 0.0044 / 0.0038
NumPy 2.62e-4 / 2.62e-4 0.9988 / 0.9991 0.9890 / 0.9920 0.0044 / 0.0038
MLX 2.67e-4 / 2.67e-4 0.9988 / 0.9991 0.9889 / 0.9919 0.0044 / 0.0038

(The final LL is unchanged; the reference holds A on its 100th iteration, which the returned parameters now match.)

Against the bundled 200-iteration amicaout fixture (input.param settings):

backend abs. LL gap before / after mean matched corr before / after min before / after Amari before / after
PyTorch 2.34e-4 / 1.31e-4 0.99730 / 0.99831 0.9700 / 0.9820 6.29e-3 / 4.76e-3
NumPy 2.25e-4 / 1.24e-4 0.99724 / 0.99824 0.9692 / 0.9814 6.35e-3 / 4.85e-3
MLX 2.22e-4 / 1.21e-4 0.99728 / 0.99828 0.9701 / 0.9817 6.32e-3 / 4.79e-3

docs/guides/validation.md parity rows are not edited here.

Public-semantics changes

  • iteration stays the 0-based index of the last iteration whose E-step ran, and ll_history has iteration + 1 entries (one fewer after a nan_ll/singular_ll stop, whose non-finite likelihood is never recorded, now in NumPy's self.ll too). On a convergence stop, iteration updates were applied (was iteration + 1).
  • final_ll_ is exactly the returned parameters' log-likelihood on a convergence stop and after a keep_best restore (then it is an earlier ll_history entry, not the last); at max_iter it is still one update behind them, as in the reference. The exported LLt follows the same rule.
  • New degenerate stop reasons "nan_direction" (all three backends) and "nan_params" (now also PyTorch and NumPy), in every _DEGENERATE_STOP_REASONS; the AMICA wrapper treats both as degenerate. NumPy names them in its prose vocabulary ("Non-finite update direction (NaN/inf) encountered", "Non-finite parameters after an update: <names>") with converged=False; inside its restart window it defers only an A/W-only corruption to restart-on-NaN, which redraws A. The PyTorch inline mu/beta/alpha warning in _update_parameters is replaced by the post-update guard; MLX's guard no longer lists ndtmpsum (caught before the update now).
  • A convergence stop runs no share scan, kurtosis switch, mir_history_ waypoint or rejection pass on its stopping iteration.
  • MLX: a nan_params stop now records that iteration's (finite) log-likelihood in ll_history.
  • NumPy: restart-on-NaN runs before the update and clears numincs (the reference's NaN comparison zeroes it; numdecs is kept, as there); rejection runs after the checkpoint writes. The per-iteration log line is printed before the checks, as the reference prints it (amica15.f90:1005-1014), so it reports the lrate the previous update used, not the rate after this iteration's decrease response. _update_direction no longer records anything; only the loop appends self.ll/self.nd.
  • MNE export: n_iter_ is now iteration + 1, the number of E-steps (was max(iteration, 1)).
  • The rho learning rate is two values on every backend: the working rholrate (scaled on each decrease, reset to the ceiling by each A update) and the new ceiling rholrate_cap (ratcheted at maxdecs). PyTorch state_dict and MLX saves carry rholrate_cap additively; a save without it loads with the ceiling equal to its rholrate. No format-version bump.
  • share_iter/share_int must be an integer >= 7, and share_start an integer >= 1, on every backend whether or not share_comps is on (the share_iter message says a smaller value would hold A permanently from share_start; NumPy's names both of its spellings). Both are reached through a Fortran params file. No bundled configuration or parameter file used a smaller value; only validation tests did.
  • Loading a PyTorch state_dict or an MLX save refuses a missing or non-finite lrate/lrate_cap/newtrate/rholrate/rholrate_cap with a ValueError naming the field (a missing rholrate was a bare KeyError on PyTorch).
  • The A-freeze applies to every fit, at the reference's iterations.

Retuned existing tests

  • torch_tests/test_ng_convergence.py: the norm spy moved to _update_direction (split); frozen-window spy takes the step; test_mir_history_survives_keep_best_restore expects no waypoint on a stop iteration (no update runs there).
  • mlx_tests/test_mlx_mir.py: same waypoint rule; seed 1 -> 2 (seed 1's MIR step change fell to 2.5e-5, under the 1e-4 float32 margin; seed 2 gives 7.8e-4, the only seed of 0-7 above it).
  • mlx_tests/test_mlx_keepbest.py: pdftype=1 forced-restore recipe seed 2/kurt_start=6 -> seed 3/kurt_start=7; the earlier decrease response no longer lets the old run overshoot (new: peak at ll index 6, min_dll stop at 19, 0.26 below the peak).
  • test_component_rows.py: byte-identity Newton configurations use newtrate=0.1 so the ramp stays saturated and a pdftype=1 switch decrease steps the same in either order (the comparison is a layout check against pre-change code); m2-keepbest-restores lrate 1.5 -> 0.5 (its one decrease is on the last iteration, discarded by the restore); the merged-state driver sets rholrate_cap; collapse recipe seed 7/share_start=8/share_iter=10 -> seed 20/share_start=share_iter=11 (with the reference freeze the old recipe went non-finite at iteration 18, before its second scan).
  • torch_tests/test_ng_sharing.py, test_numpy_share_comps.py, mlx_tests/test_mlx_sharing.py: freeze-window tests use the reference arithmetic and run with sharing off and on; the "no freeze for one model" tests now assert the freeze applies; _shared_fit share_start 2 -> 8 (so short sharing-off fits still move A); MLX mixture-keeps-moving test 4/20 -> 7/7; MLX "not validated when sharing is off" now expects share_iter=1 to raise.
  • test_schedule_gates.py: share_freeze expectations follow the reference; the rho-rate probe reads rholrate_cap; default gate seed 1 -> 3 (seed 1 now ratchets at [8, 16]; seed 3 at [8, 20] on every backend).
  • test_sample_data.py, test_numpy_restarts.py: assert the ceiling and the working rate separately.
  • torch_tests/test_ng_backend.py, mlx_tests/test_mlx_backend.py: rho-ratchet tests read rholrate_cap (they had passed only because the last update resets the working rate); round-trip list includes rholrate_cap.
  • keep_best overshoot recipes (test_ng_convergence.py, test_ng_backend.py, test_llt_stash.py, test_amica_ng_wrapper.py, mlx_tests/test_mlx_reject.py, test_mlx_keepbest.py, test_mlx_llt_stash.py, test_mlx_mir.py, test_mlx_export.py, test_mlx_keepbest_cross_backend.py): min_dll=1e-4/maxincs=2 -> min_dll=1e-8/maxincs=0, which stops each run on its first likelihood decrease (iteration 14, 1.6e-3 below the peak at 13). Under the new order the old stop ended at the peak or below it depending on round-off: it ended at the peak on the macOS CI runner (7 failures on the first CI run), and in 1 of 12 relative data perturbations locally (1e-13 PyTorch, 1e-6 MLX; 2 of 12 for MLX with rejection). The new stop overshoots in all 12 on both backends, with and without rejection. test_mlx_mir.py goes back to seed 0 (MIR step change 8.2e-4 to 1.1e-3 relative across 8 perturbations, above its 1e-4 margin). The pdftype=1 recipe keeps its stop: its overshoot is the 0.26 drop at the density switch, identical in all 12 perturbations.
  • Review round: test_schedule_gates.py restart-window test expects the poisoned likelihood unrecorded (len(ll) == nan_iter); test_sample_data.py maxrestarts test expects an empty history and the NaN reason; test_numpy_share_comps.py non-finite reporting now expects the post-update stop (nan_params reason naming mu) before the checkpoint, with the checkpoint's own refusal exercised directly, and its freeze test reads the norm from the returned step; test_numpy_grad_norm.py and the test_component_rows.py seeded driver read the norm/likelihood from _update_direction/the E-step instead of self.nd/self.ll after a direct _update_parameters call; mlx_tests/test_mlx_sharing.py expects share_start=0 to raise with sharing off.
  • Cross-backend state copies (test_mlx_newton_cross_backend.py, test_mlx_pdf_families_cross_backend.py, test_mlx_sharing_cross_backend.py, test_numpy_share_comps.py) also copy rholrate_cap.

Test plan

  • pamica/tests/test_iteration_order.py: A held on exactly the reference's iterations without sharing (bit-for-bit with doscaling off, rescale only with it on) and on 100-105 for a default fit; the step after a decrease uses the halved rate; every convergence stop (min_dll, grad_norm, grad_norm_floor, lrate_floor, 12 cases) reproduces final_ll_ exactly from its returned parameters; a keep-best restore does too; share_iter below 7 rejected on every backend, also through a params file with share_start below 1; rholrate_cap round-trips and a missing or non-finite saved rate is refused by name
  • pamica/tests/test_nonfinite_stops.py (14 tests, injection on every backend): same finite history after a NaN likelihood, nan_direction for a NaN step or norm, nan_params after the last update, wrapper refusal, NumPy restart-window deferral only for A/W
  • test_schedule_gates.py: NumPy restart applies no update on the restarting iteration (pass-through recorder; the pre-change code, loaded through pre_change.py as a control, updated on it) and clears numincs (stops at index 8; 6 without the fix); share_start in the validation matrix
  • mne_tests/test_mne_backends.py: n_iter_ == iteration + 1 == len(ll_history) after a min_dll stop and a max_iter fit, PyTorch and MLX
  • Gated native oracles with AMICA_RUN_FORTRAN=1: this phase's plus Phases 7, 8 and 9 (236 passed before and after the merge, and after the review round)
  • Full non-slow suite with CI=1, -n auto --cov-fail-under=80, after the review round: 1858 passed, 31 skipped, 1 xfailed, coverage 91.32%
  • -m slow: 10 passed, 2 xfailed (after the review round)
  • ruff check, ruff format --check, ty check, typos, mkdocs build --strict
  • git rev-parse --is-shallow-repository prints false
  • Docs: ADR 0008, changelog, differences guide

Compute the natural-gradient/Newton step and its norm (the reference's
dAk and ndtmpsum) in _update_direction and apply it in
_update_parameters, in all three backends, sharing one set of
intermediates. The fit loops call both back to back, so every fit is
byte-identical (checked on 8 configurations per backend).
Run the likelihood-decrease response and the stopping checks before the
parameter update, and exit on a stop before any parameter moves, as
amica15.f90:1015-1122 does, in all three backends. The step taken right
after a decrease now uses the halved rate, and a stopped fit returns the
parameters whose likelihood is ll_history[-1]. Keep the reference's
working rho rate and its ceiling apart (rholrate, rholrate_cap), reset
inside the A-update branch. Fits without decreases or stops are
byte-identical; seeded oracle deviations drop from 1.4e-2 to 2.7e-5.
Apply the reference's A-update guard (iter >= share_start and
mod(iter, share_iter) <= 5, amica15.f90:1803) in every fit, share_comps
on or off, through schedule.share_freeze, replacing the anchored
post-merge window. Every backend now rejects share_iter < 7 (NumPy:
share_int) whether or not sharing is on, since a shorter cycle would
never update A again. Default fits of 100 or more iterations change.
Always-on cross-backend tests for the freeze iterations, the decrease
timing, stop semantics, keep_best pairing and share_iter validation, plus
an opt-in comparison against the native binary (AMICA_RUN_FORTRAN=1).
All pass; the native comparison fails on the pre-change code.
Existing tests that pinned the old order (update before the checks, a
freeze gated on share_comps and anchored on share_start, one rho rate) now
pin the reference's, or use recipes that still exercise what they test.
Full non-slow suite and the gated native oracles pass.
ADR 0008, changelog entry with oracle and parity numbers, and the
differences guide: the A-freeze is now the reference's arithmetic, and
convergence stops return the parameters final_ll_ describes.
mkdocs build --strict passes.
Rate tests that read rholrate as the ceiling now read rholrate_cap, the
cross-backend state copies carry it, and a new test round-trips it through
state_dict on PyTorch and MLX, including a save without the key.
Affected tests pass, including the slow torch ratchet test.
…-class' into feature/issue-339-phase11-loop-order

# Conflicts:
#	docs/changelog.md
#	pamica/numpy_impl/core.py
The keep_best overshoot recipes stopped via min_dll=1e-4/maxincs=2,
which under the reference order ended at the peak or below it depending on
round-off: at the peak on the macOS CI runner, and in 1 to 2 of 12 data
perturbations locally. maxincs=0 with min_dll=1e-8 stops them on their
first likelihood decrease instead, which held in all 12 perturbations on
PyTorch and MLX, with and without rejection. Affected tests pass.
Every backend now keeps a non-finite likelihood out of its history (NumPy
recorded it), stops before applying a non-finite step or gradient norm
(new degenerate stop_reason nan_direction), and stops on non-finite
parameters right after an update (nan_params, now also in PyTorch and
NumPy). NumPy defers only an A/W corruption inside its restart window to
restart-on-NaN, which can repair it. Cross-backend injection tests pass.
The reference's min_dll comparison with the NaN likelihood of its restart
iteration is false, so it zeroes numincs (numdecs is left as it was).
NumPy's restart carried the small-gain count across; it now clears it.
The new test stops at index 8 as expected and at 6 without the fix.
from_state_dict (and the MLX file load) now refuses a missing or
non-finite lrate, lrate_cap, newtrate, rholrate or rholrate_cap with a
ValueError naming the field; a missing rholrate no longer surfaces as a
bare KeyError on PyTorch. Tested on PyTorch and MLX.
The A-freeze reads share_start whether or not share_comps is on, so every
backend now requires an integer share_start >= 1 always. The share_iter
message now says why a value below 7 is refused (A held permanently from
share_start), and NumPy's names both of its spellings. Both checks are
reached through a Fortran params file on all backends; tests pass.
The stop test now runs min_dll, grad_norm, grad_norm_floor and lrate_floor
on every backend, each with a precondition on its stop_reason and a twin
that runs the same iterations to max_iter. All 12 cases pass.
A pass-through recorder on _update_parameters shows the restarting
iteration applies no update; the same fit of the pre-change code, loaded
through pre_change.py as a control, updated on it. Passes.
to_mne_ica().n_iter_ equals iteration + 1 and len(ll_history) after a
min_dll stop and after a max_iter fit, on PyTorch and MLX. Passes.
The reference noise floor is now the larger deviation of a 2- or 4-thread
binary run from the 1-thread run. The multi-threaded runs are not
reproducible, so the docstring gives each floor's range over three runs.
All four gated oracle cases pass in each run.
mir_history_ records no waypoint on a stopping iteration; MLX documents
its rholrate/rholrate_cap pair as PyTorch does; NumPy fit() gets the
iteration-order notes. Rejection is cited as amica15.f90:1136-1140 and the
check ranges start at 1056 and 1019. Docstring and comment changes only.
ADR 0008 states the final_ll_ invariant with its keep_best qualifier and
the review's changes; the changelog and differences guide cover the
non-finite stops, share_start validation and saved-rate checks, with the
two-pair oracle floors. AGENTS.md and the context notes describe the
unconditional A-freeze. mkdocs build --strict passes.
@neuromechanist
neuromechanist merged commit 027cb07 into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-339-phase11-loop-order branch September 23, 2026 15:42
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