Repository navigation
Phase 11: follow the reference's iteration order - #348
Merged
neuromechanist merged 19 commits intoSep 23, 2026
Merged
neuromechanist merged 19 commits into
neuromechanist merged 19 commits into
Conversation
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
merged commit Sep 23, 2026
027cb07
into
feature/issue-324-epic-mlx-first-class
8 checks passed
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
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
Aand its norm; then the non-finite check, the likelihood-decrease response (halvelrate, scale the working rho rate, countnumdecs, ratchet the ceilings atmaxdecsthroughschedule),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_parametersis split into_update_direction(direction and norms) and the update that applies it, sharing one set of intermediates (issue #339).The reference holds the
Aupdate, itslrateramp and its reset of the working rho rate on every iteration withiter >= share_startandmod(iter, share_iter) <= 5(amica15.f90:1803), whether or notshare_compsis on. All three backends now apply exactly that throughschedule.share_freeze, replacing the anchored window that applied only undershare_compswith two or more models, and every backend rejectsshare_iter(NumPyshare_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_startis now validated (>= 1) on every fit, theshare_itermessage says why, saved learning rates are validated on load, and NumPy's restart clearsnumincsas the reference does.Part of epic #324; resolves #339 and #345 (closes when the epic merges to dev).
Behavior change
min_dll,grad_norm,grad_norm_floor,lrate_floor) returns the parameters whose log-likelihood isll_history[-1];final_ll_(without a keep-best restore) is exactly their log-likelihood. Amax_iterfit still updates on its last iteration, as the reference does.share_start(iteration 100 by default) holdsAon the reference's iterations (100-105, 200-205, ... with the defaults).nan_direction/nan_params) instead of being applied or returned; a PyTorch corruption on the last iteration used to end asmax_iter.share_startiterations 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.lrate=0.5,doscalingon)Agapmaxdecsratchet: pre-changemaxdecsratchet: PyTorch aftermaxdecsratchet: NumPy aftermaxdecsratchet: binary floorEvery 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 atrho=1amplifies round-off, as recorded in Phase 9).share_compsoff,share_start=3,share_iter=10)Agapdoscalingon/off)doscalingon: PyTorch / NumPy / binary floordoscalingoff: PyTorch / NumPy / binary floorThe held iterations read from the binary's own per-iteration
Ahistory are exactly the reference arithmetic's (3-5, 10-15). On them the binary'sAis unchanged exactly withdoscalingoff, 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):(The final LL is unchanged; the reference holds
Aon its 100th iteration, which the returned parameters now match.)Against the bundled 200-iteration
amicaoutfixture (input.paramsettings):docs/guides/validation.mdparity rows are not edited here.Public-semantics changes
iterationstays the 0-based index of the last iteration whose E-step ran, andll_historyhasiteration + 1entries (one fewer after anan_ll/singular_llstop, whose non-finite likelihood is never recorded, now in NumPy'sself.lltoo). On a convergence stop,iterationupdates were applied (wasiteration + 1).final_ll_is exactly the returned parameters' log-likelihood on a convergence stop and after akeep_bestrestore (then it is an earlierll_historyentry, not the last); atmax_iterit is still one update behind them, as in the reference. The exportedLLtfollows the same rule."nan_direction"(all three backends) and"nan_params"(now also PyTorch and NumPy), in every_DEGENERATE_STOP_REASONS; theAMICAwrapper 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>") withconverged=False; inside its restart window it defers only anA/W-only corruption to restart-on-NaN, which redrawsA. The PyTorch inline mu/beta/alpha warning in_update_parametersis replaced by the post-update guard; MLX's guard no longer listsndtmpsum(caught before the update now).mir_history_waypoint or rejection pass on its stopping iteration.nan_paramsstop now records that iteration's (finite) log-likelihood inll_history.numincs(the reference's NaN comparison zeroes it;numdecsis 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 thelratethe previous update used, not the rate after this iteration's decrease response._update_directionno longer records anything; only the loop appendsself.ll/self.nd.n_iter_is nowiteration + 1, the number of E-steps (wasmax(iteration, 1)).rholrate(scaled on each decrease, reset to the ceiling by eachAupdate) and the new ceilingrholrate_cap(ratcheted atmaxdecs). PyTorchstate_dictand MLX saves carryrholrate_capadditively; a save without it loads with the ceiling equal to itsrholrate. No format-version bump.share_iter/share_intmust be an integer >= 7, andshare_startan integer >= 1, on every backend whether or notshare_compsis on (theshare_itermessage says a smaller value would hold A permanently fromshare_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.state_dictor an MLX save refuses a missing or non-finitelrate/lrate_cap/newtrate/rholrate/rholrate_capwith aValueErrornaming the field (a missingrholratewas a bareKeyErroron PyTorch).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_restoreexpects 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=1forced-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_dllstop at 19, 0.26 below the peak).test_component_rows.py: byte-identity Newton configurations usenewtrate=0.1so the ramp stays saturated and apdftype=1switch decrease steps the same in either order (the comparison is a layout check against pre-change code);m2-keepbest-restoreslrate1.5 -> 0.5 (its one decrease is on the last iteration, discarded by the restore); the merged-state driver setsrholrate_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_fitshare_start 2 -> 8 (so short sharing-off fits still moveA); MLX mixture-keeps-moving test 4/20 -> 7/7; MLX "not validated when sharing is off" now expectsshare_iter=1to raise.test_schedule_gates.py:share_freezeexpectations follow the reference; the rho-rate probe readsrholrate_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 readrholrate_cap(they had passed only because the last update resets the working rate); round-trip list includesrholrate_cap.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.pygoes back to seed 0 (MIR step change 8.2e-4 to 1.1e-3 relative across 8 perturbations, above its 1e-4 margin). Thepdftype=1recipe keeps its stop: its overshoot is the 0.26 drop at the density switch, identical in all 12 perturbations.test_schedule_gates.pyrestart-window test expects the poisoned likelihood unrecorded (len(ll) == nan_iter);test_sample_data.pymaxrestarts test expects an empty history and the NaN reason;test_numpy_share_comps.pynon-finite reporting now expects the post-update stop (nan_paramsreason namingmu) 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.pyand thetest_component_rows.pyseeded driver read the norm/likelihood from_update_direction/the E-step instead ofself.nd/self.llafter a direct_update_parameterscall;mlx_tests/test_mlx_sharing.pyexpectsshare_start=0to raise with sharing off.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 copyrholrate_cap.Test plan
pamica/tests/test_iteration_order.py: A held on exactly the reference's iterations without sharing (bit-for-bit withdoscalingoff, 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) reproducesfinal_ll_exactly from its returned parameters; a keep-best restore does too;share_iterbelow 7 rejected on every backend, also through a params file withshare_startbelow 1;rholrate_capround-trips and a missing or non-finite saved rate is refused by namepamica/tests/test_nonfinite_stops.py(14 tests, injection on every backend): same finite history after a NaN likelihood,nan_directionfor a NaN step or norm,nan_paramsafter the last update, wrapper refusal, NumPy restart-window deferral only forA/Wtest_schedule_gates.py: NumPy restart applies no update on the restarting iteration (pass-through recorder; the pre-change code, loaded throughpre_change.pyas a control, updated on it) and clearsnumincs(stops at index 8; 6 without the fix);share_startin the validation matrixmne_tests/test_mne_backends.py:n_iter_ == iteration + 1 == len(ll_history)after amin_dllstop and amax_iterfit, PyTorch and MLXAMICA_RUN_FORTRAN=1: this phase's plus Phases 7, 8 and 9 (236 passed before and after the merge, and after the review round)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 --strictgit rev-parse --is-shallow-repositoryprintsfalse