Repository navigation
Phase 9: align iteration-schedule gates with the reference - #338
Merged
neuromechanist merged 20 commits intoSep 23, 2026
Merged
neuromechanist merged 20 commits into
neuromechanist merged 20 commits into
Conversation
Route every iteration-schedule gate in the torch, NumPy and MLX backends through a shared pamica/schedule.py. The Newton switch (iter .ge. newt_start), the numdecs reset on the switch-on iteration, the iter > newt_start ceiling ratchets, the outlier-rejection schedule and NumPy's restart-on-NaN window compared the 0-based loop index with the reference's 1-based setting and fired one iteration late. Share, kurtosis, A-freeze and writestep/histstep gates were already 1-based and now use the same helpers. Seeded against the v0.3.3 binary (newt_start=3, doscaling off, 6 iterations) the LL deviation drops from 1.2e-3 to 5.4e-11 (torch) and 2.1e-12 (NumPy).
Tests whose configurations or replays encoded the old 0-based newt_start/rejstart: the aggressive-Newton keep_best recipe moves from newt_start=1 to 2 (the exact pre-change trajectory its documented measurements came from), the LLt reject tests fire on iteration 6 of a 6-iteration fit, and the MLX ratchet/reset replays spell out the reference's 1-based arithmetic. Tested: the 11 affected files pass (179 passed, 1 skipped).
Cross-backend real-fit tests (torch, NumPy, MLX): the first Newton step is iteration newt_start, the rho-rate ceiling ratchet opens only after it, the switch-on counter reset follows the reference's replay, rejection first fires on iteration rejstart, and NumPy's restart-on-NaN window covers the first restartiter iterations. Tested: 15 passed; against the pre-fix backends 10 of them fail.
Seeds the pinned v0.3.3 binary with pamica's own init (indir/load_*), newt_start=3, doscaling off, single-threaded, 6 iterations. Torch and NumPy match its LL trajectory and A to round-off (torch LL 5.4e-11, A 4.2e-10; NumPy LL 2.1e-12, A 1.1e-10) where the pre-fix code deviated by 1.25e-3 and 3.1e-2. A no-Newton control shows the compared window is Newton-sensitive. Tested with AMICA_RUN_FORTRAN=1: 3 passed; 2 fail on the pre-fix backends.
Changelog entry for issue #335: which gates moved, the native-oracle numbers before and after, the default-path cases that change, and how to reproduce an old trajectory. No row in docs/guides/amica-differences.md changes: the anchored share A-freeze is already recorded there.
…-class' into feature/issue-335-phase9-newton-start # Conflicts: # docs/changelog.md # pamica/numpy_impl/core.py
One shared validator, schedule.validate_iteration_setting, called by all three constructors with identical messages: newt_start must be an integer >= 0 whether or not do_newton is on (it also gates the rho-rate ratchet), and rejstart an integer >= 1 when do_reject is on (with 1-based counting, rejstart <= 0 skipped the reference's unconditional first pass; NumPy accepted 0, torch and MLX any value). NumPy also validates restartiter >= 0, maxrestarts >= 0 and histstep >= 1 under do_history (histstep=0 was a bare ZeroDivisionError mid-fit), and documents that restartiter=0 disables restart-on-NaN. schedule.every and periodic_due raise ValueError for a non-positive interval. Docstrings: newton_active cites amica15.f90:1666, newt_start=0 and 1 are stated to fit identically, and the MLX newt_start/newtrate entries document the newtrate ratchet. Tested: the new validation, restart-window and interval tests pass (36 passed with the reject suites).
The share_start/share_iter and kurt_start entries no longer break mid-clause. No code change.
Row 14 of the differences guide: the reference allows maxrestarts+1 restarts and, because startover is never cleared (amica15.f90:1046), never calls update_params again after the first one (:1115-1122); the NumPy backend allows maxrestarts restarts and resumes fitting. PyTorch and MLX have no restart-on-NaN path and stop with nan_ll.
Use the measured pre-fix deviations (1.25e-3 over 6 iterations, 1.33e-3 over 100) in the changelog and the oracle test docstring, list restartiter among the settings that now count from 1, and add the new validation.
The arithmetic test gains the =1 rows for every helper (newton_switches_on at 1 and 0, past_newton_start at newt_start and newt_start+1, rejection with rejstart=1/rejint=1 through maxrej exhaustion, every/periodic_due at 1, the restart window at 1 and 0). The first-Newton-step test runs at newt_start 1 and 5, and a new real-fit test on every backend shows newt_start=0 and 1 give bit-identical trajectories on an overshooting run whose ratchets fire. Tested: 12 passed.
The replay-based reset tests passed with the reset one iteration late too. The cross-backend test now uses a searched configuration (4096 frames, lrate=0.8, newt_ramp=1, maxdecs=3, newt_start=3) whose likelihood decreases on iterations 2, 3 and 4, where the reference rule predicts no ratchet and the one-late rule predicts one; the fitted lrate ceiling must match the reference. It fails on all three backends with only newton_switches_on reverted and on the pre-fix backends. The MLX twin, which could not discriminate, is removed in favor of it. Tested: 3 passed; 3 failed with the reset reverted.
A searched natural-gradient configuration (4096 frames, seed 4, lrate 0.5, maxdecs 2) completes a maxdecs cycle on iteration 21 on all three backends, so the rho-rate ratchet gate is now pinned at the shipped default: open for newt_start=20, closed for 21. This is the one default-path change of issue #335. Tested: 3 passed; 3 fail on the pre-fix backends.
9 tasks done
States the full search that selected the switch-on reset configuration, including the two-model hit found after the first commit.
Conflicts: the differences table keeps Phase 7's scalestep row as 14 and renumbers the NumPy restart-on-NaN row to 15 (changelog reference updated); the NumPy constructor docs keep both the 1-based schedule paragraphs and Phase 7's doscaling paragraph; the four test files take Phase 7's retuned overshoot recipes (newtrate=3.0, 150-iteration budgets); paper.pdf takes the epic's build. The 1-based shift of those recipes and the scalestep helper follow in separate commits.
Phase 7 retuned its overshoot recipes under 0-based gating. With newt_start and rejstart counted from 1, n becomes n+1 so each documented trajectory reproduces bit for bit: the min_dll overshoot recipe (newt_start 2, newtrate 3.0) again peaks at 70 and stops at 71 on torch (1.9e-4 below the peak) and at 63/64 on MLX (4.2e-4); its do_reject variants move rejstart 5 to 6; the doscaling-rows NEWTON state uses newt_start=2; the min_dll-reachable test uses 6 and the slow rholrate ratchet test 51. Tested: the affected suites pass.
Phase 7's inline (iteration + 1) % scalestep rule becomes schedule.every in all three backends, and its scalestep check becomes schedule.validate_iteration_setting (same semantics and message; still only when doscaling is on), which drops the numbers imports it needed. Tested: test_doscaling_rows passes.
Phase 7's component-row doscaling moved the old configuration's second ratchet off iteration 21, and the test's precondition guard failed as intended. The re-searched configuration (4096 frames, seed 1, lrate 0.6, maxdecs 3, newt_ramp 1) decreases at ll indices 4, 5, 8 and 9, 19, 20 on all three backends (smallest decrease 4.7e-4), ratcheting at 8 and 20. Tested: 3 passed.
13 tasks done
neuromechanist
merged commit Sep 23, 2026
0930c0e
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
The reference counts its iterations from 1 (
iter = 1before the main loop, amica15.f90:949) and states every schedule against that counter, while pamica's fit loops count from 0.The PyTorch, NumPy and MLX backends compared the 0-based loop index with 1-based settings at five gates, so each fired one iteration late:
the Newton switch (
iter .ge. newt_start), the decrease-counter reset on the switch-on iteration (iter == newt_start), themaxdecsratchet of the rho-rate ceiling andnewtrate(iter > newt_start), the outlier-rejection schedule (iter == rejstart), and NumPy's restart-on-NaN window (iter .le. restartiter).Every iteration-schedule gate now goes through one shared module,
pamica/schedule.py, called by all three backends (.rules/backend_parity.md), so they cannot drift and no gate compares the 0-based index with a 1-based setting again.The share-merge, A-freeze, kurtosis-switch and
writestep/histstepgates were already 1-based and keep their behavior; they use the same helpers now.iteration,ll_historyandmir_history_keep their 0-based indexing.Against the pinned v0.3.3 native binary, seeded with pamica's own initialization (
newt_start=3,doscalingoff, single-threaded, 6 iterations), torch and NumPy now match the reference's LL trajectory andAto round-off, where they deviated by 1.25e-3 and 3.1e-2.Default fits (
do_newton=False,do_reject=False) change in two narrow cases only: amaxdecsratchet that completes on exactly iterationnewt_start + 1(21 by default) now tightens the rho-rate ceiling as the reference's does, and on NumPy a non-finite LL on iterationrestartiter + 1(11 by default) now ends the fit instead of restarting it.A pre-change trajectory is reproduced by adding 1 to
newt_start,rejstart(andrestartiteron NumPy).The settings these gates read are now validated by one shared function,
schedule.validate_iteration_setting, with the same message on every backend:newt_startmust be an integer >= 0 whether or notdo_newtonis on (it also gates the rho-rate ratchet), andrejstartan integer >= 1 whendo_rejectis on (with 1-based counting,rejstart <= 0would silently skip the reference's unconditional first pass).NumPy also requires
restartiter >= 0,maxrestarts >= 0and, underdo_history,histstep >= 1(histstep=0was a bareZeroDivisionErrormid-fit);schedule.everyandschedule.periodic_dueraiseValueErrorfor a non-positive interval.docs/guides/amica-differences.mdgains row 15 for NumPy's restart-on-NaN recovery, which differs from the reference's in count and in resuming the fit.Part of epic #324; resolves #335 (closes when the epic merges to dev).
Site-by-site verification
itis pamica's 0-based loop index;iteris the reference's 1-based counter. Line numbers are amica15.f90 and the pre-change pamica sources (torchtorch_impl/core.py, MLXmlx_impl/core.py, NumPynumpy_impl/core.py).iter .ge. newt_start(1498, 1651, 1666, 1719, 1739, 1804)iteration >= newt_start(torch 1660, MLX 1660, NumPy 2038)schedule.newton_activenewt_ramplrate rampnewtratewhen Newton is active and positive definite, else towardlrate0(1804-1815)do_newton .and. iter == newt_start(1099)it == newt_start(torch 2798, MLX 2974, NumPy 2351)schedule.newton_switches_onmaxdecsiter > newt_start(1067), independent ofdo_newtonit > newt_start(torch 2749, MLX 2917, NumPy 2535)schedule.past_newton_startnewtrateratchet atmaxdecsdo_newton .and. iter > newt_start(1070)do_newton and it > newt_start(torch 2751, MLX 2919, NumPy 2543)schedule.past_newton_startiter==rejstart .or. (mod(max(1,iter-rejstart),rejint)==0 .and. numrej<maxrej)(1136)it(torch 2560, MLX 2654, NumPy 2362)schedule.rejection_dueiter .le. restartiter(1022)iter <= restartiter(NumPy 2294)schedule.within_restart_windowiter .ge. share_start .and. mod(iter-share_start,share_iter)==0(1856)itf = it + 1(all three)schedule.periodic_due, unchangediter < share_start .or. mod(iter,share_iter) > 5(1803)(itf - share_start) % share_iter <= 5(all three)schedule.share_freeze, unchangedpdftype=1)do_choose_pdfsis dead code)itf >= kurt_startand(itf - kurt_start) % kurt_int == 0(torch, MLX)schedule.periodic_due, unchangedwritestep/histstep(NumPy)mod(iter, writestep)==0,mod(iter, histstep)==0(1124, 1130)itf % step == 0(issue #240)schedule.every, unchangedmin_dll/maxincs, decrease countingif (iter > 1)(1051-1098)len(ll_history) > 1/len(self.ll) < 2scalestep(doscalingcadence)iteration % scalestep == 0(torch 1824, MLX 1825, NumPy 2183)scalestep=1; differs forscalestep > 1schedule.everyandschedule.validate_iteration_settingmir_stepwaypointsit % mir_step == 0, recorded as 0-basedmir_history_lrate, ratchet ceilings)iterbeforeupdate_params(1056-1077, then 1122)_update_parametersleave(min_dll, grad norm, lrate floor)exitbeforeupdate_params(1111 vs 1122)breakafter_update_parametersfinal_ll_The anchored share A-freeze is already recorded in
docs/guides/amica-differences.md; every other gate now matches the reference.Row 15 is new (Phase 7's
scalesteprow took 14): the reference allowsmaxrestarts + 1restarts (numrestarts > maxrestartsends the run, amica15.f90:1023) and never clearsstartover(set at :1046), so after one restart it never callsupdate_paramsagain (:1115-1122); pamica's NumPy backend allowsmaxrestartsrestarts and resumes fitting after each. PyTorch and MLX have no restart-on-NaN path and stop withnan_ll.Native-binary numbers (pinned v0.3.3, seeded,
doscalingoff, single-threaded)First Newton iterations (
newt_start=3, 6 iterations, the gated test):Adeviation100 iterations:
newt_start=50(input.param)newt_start=50newt_start=3newt_start=3The ~1e-6 floor over 100 iterations is set by the recording before Newton starts: one mixture component's shape sits at
rho=1, where the reference's location update divides by|y|(amica15.f90:1527-1533), so round-off grows by orders of magnitude per iteration (natural gradient only,mudeviates 1.8e-9 after 4 iterations, 2.4e-6 after 5, 1.8e-2 after 49;A1.4e-4 after 49).The same amplification makes the 100-iteration endpoint
Aa poor parity metric: it deviates by 1e-3 to 1.6e-2 (Amari 2e-4 to 1.6e-3) before and after, in no consistent direction, while the LL trajectory tightens by more than two orders of magnitude.Found, not fixed (needs a lead decision)
The reference applies its response to a likelihood decrease (halve
lrate, and atmaxdecsratchetlrate0,rholrate0,newtrate) before that iteration'supdate_params; all three pamica backends apply it after, so it reaches the parameters one update late.This is on the default natural-gradient path whenever the likelihood decreases.
Seeded against the binary (
lrate=0.5,do_newton=0,doscalingoff, 30 iterations), the LL deviation jumps from 5.4e-6 to 3.6e-3 on the iteration after the first decrease; a prototype that applies the response before the update stays at 1.0e-5 throughout.A faithful fix also changes which parameters a convergence stop returns (the reference exits before the update, pamica after it), which is a public semantic, so it is left for a decision.
Changes to existing tests
Each encoded the old 0-based settings; none of their tolerances changed.
mlx_tests/test_mlx_keepbest.py:_FORCED_RESTORE_KWARGSand_FORCED_RESTORE_PDFTYPE1_KWARGSgo fromnewt_start=1to2, the exact trajectory the documented measurements came from (test_pdftype1_forced_restore_rolls_back_n_kurt_done_with_pdtypefailed otherwise); the module docstring says so.newt_start1 to 2:mlx_tests/test_mlx_llt_stash.py(_FORCED_RESTORE_KWARGS),mlx_tests/test_mlx_export.py::test_written_ll_ends_at_the_keep_best_restored_iterate,mlx_tests/test_mlx_mir.py::test_mir_history_survives_keep_best_restore,test_mlx_keepbest_cross_backend.py(_AGGRESSIVE_KWARGS),test_llt_stash.py::test_keep_best_restore_rolls_the_llt_stash_back,torch_tests/test_amica_ng_wrapper.py::test_write_amica_output_ll_matches_kept_iterate,torch_tests/test_ng_convergence.py::test_keep_best_restores_genuine_overshoot_under_min_dll_stopand::test_mir_history_survives_keep_best_restore.mlx_tests/test_mlx_reject.py::test_keep_best_restore_never_fires_under_do_reject:newt_start1 to 2 andrejstart5 to 6;::test_rejection_shrinks_good_sample_set_on_the_expected_schedule: docstring now counts from 1;::test_reject_param_validation: also checks the newrejstartvalidation.test_llt_stash.py:_reject_kwargsdocstring, andtest_llt_invariant_breaks_when_rejection_fires_on_the_last_iteration/test_llt_invariant_returns_one_iteration_after_a_rejectionmoverejstart5 to 6 (reject on iteration 6 of a 6-iteration fit).test_numpy_reject.py::test_rejection_does_not_spuriously_stop_fit: the rejection iteration isll[rejstart - 1].mlx_tests/test_mlx_newton.py:_ratchet_iterationsandtest_newtrate_ratchet_is_suppressed_before_newt_start,test_newtrate_ratchets_at_maxdecs_once_newton_runs,test_newtrate_never_ratchets_without_newtonreplay the reference's 1-based arithmetic;test_numdecs_resets_when_newton_switches_onis removed (it could not discriminate, see below) in favor of the cross-backend reset test.Review fix pass
newt_startper configuration from 60-iteration probes) found discriminating runs only atlrate=0.8,newt_start=3(21 hits, where the switch-on Hessian is not yet positive definite and the fallback step overshoots) and one two-model run atlrate=0.5,newt_start=11. The test uses 4096 frames,lrate=0.8,newt_ramp=1,maxdecs=3,newt_start=3, 4 iterations: the likelihood decreases on iterations 2, 3 and 4 (by 3.8e-3, 2.0e-2, 3.0e-2), the reference rule predicts no ratchet and the one-late rule one, and the test asserts that disagreement on the observed trajectory before checking the fittedlrateceiling. It holds on seeds 0-5 on all three backends, fails on all three with onlynewton_switches_onreverted, and fails on the pre-fix backends.lrate=0.5,maxdecs=2) completes a cycle on iteration 21 on all three backends, sotest_rho_rate_ratchet_gate_at_the_shipped_default_newt_startpins the gate atnewt_start=20(open) and21(closed); it fails on the pre-fix backends.=1(and0) rows for every helper; the first-Newton-step test runs atnewt_start1 and 5; a new real-fit test showsnewt_start=0and1give bit-identical fits on every backend on a run whose ratchets fire.Merge with Phase 7 (#340)
scalesteprow as 14 and renumbers the NumPy restart row to 15; the NumPy constructor docs keep both paragraphs; the four conflicting tests (mlx_tests/test_mlx_keepbest.py,mlx_tests/test_mlx_llt_stash.py,mlx_tests/test_mlx_reject.py,torch_tests/test_ng_convergence.py) take Phase 7's retuned recipes;paper.pdftakes the epic's build.nton+1so the documented trajectories reproduce bit for bit: the min_dll overshoot recipe (newt_start2,newtrate3.0) again peaks at 70 and stops at 71 on torch (1.9e-4 below the peak) and at 63/64 on MLX (4.2e-4), measured after the shift; itsdo_rejectvariants (test_ng_backend.py,test_mlx_reject.py) moverejstart5 to 6;test_doscaling_rows.py'sNEWTONstate usesnewt_start=2;test_min_dll_stop_reachable_at_shipped_default_thresholduses 6 and the slowtest_rholrate_ratchets_at_maxdecs_not_per_decrease51. Phase 7's_OPToracle config (newt_start=50, Newton off, passed to both sides) is unchanged.scalestep(c78f0f8): Phase 7's inline(iteration + 1) % scalestep == 0becomesschedule.everyin all three backends, and its check becomesschedule.validate_iteration_setting(identical semantics and message, only whendoscalingis on).newt_start=20gate test's precondition guard failed as intended (the second ratchet moved to index 19 on NumPy/MLX and past the budget on torch). Re-searched (seeds 0-5, lrate 0.5/0.6/0.8, maxdecs 2/3, newt_ramp 10/1, 4096/8192 frames on torch, then checked on NumPy and MLX): 4096 frames, seed 1, lrate 0.6, maxdecs 3, newt_ramp 1 decreases at ll indices 4, 5, 8 and 9, 19, 20 on all three backends (smallest decrease 4.7e-4), ratcheting at 8 and 20. The switch-on reset test's configuration still discriminates under the row rule (its guard asserts the decrease pattern and the (0, 1) replay split), and every other data-driven schedule test's guard holds.test_schedule_native_oracle.pyruns withdoscalingoff and is unchanged (3 passed). Withdoscalingon as well, the seeded 100-iteration Newton comparison (newt_start=50) stays within 3.9e-6 (torch) and 7.0e-6 (NumPy); ADR 0006 recorded 2.1e-4 with only the doscaling normalizes stored columns, not components (all backends) #333 fix.Test plan
uv run ruff check .,uv run ruff format --check .,uv run ty check,typoson the changed filespamica/tests/test_schedule_gates.py(always on; torch, NumPy, MLX): 55 passed, after the merge with Phase 7 too. Against the pre-change backends the Newton-switch, ratchet, reset, default-gate and rejection tests failpamica/tests/test_schedule_native_oracle.pywithAMICA_RUN_FORTRAN=1: 3 passed, before and after the merge; the torch and NumPy comparisons fail against the pre-change backendsAMICA_RUN_FORTRAN=1): torchtest_ng_convergence,test_ng_float32_stability,test_ng_restarts,test_ng_backend,test_ng_pdf_families,test_amica_ng_wrapper; MLXtest_mlx_keepbest,test_mlx_newton,test_mlx_restarts,test_mlx_reject,test_mlx_llt_stash,test_mlx_export,test_mlx_mir;test_mlx_reject_cross_backend,test_numpy_reject,test_mlx_convergence_stops,test_mlx_newton_cross_backend,test_mlx_keepbest_cross_backend,test_numpy_newton_multimodel,test_numpy_restarts,test_restart_policy,test_llt_stash,test_sample_data,test_doscaling_rows(its native oracle included) and the two new files: 506 passed, 1 skipped (a by-design NumPy skip intest_restart_policy), 3 xfaileduv run pytest pamica/tests -q --no-cov -n 4 -m "not slow": 1497 passed, 23 skipped (opt-in binary tests and that one by-design skip), 1 xfailed; no recipe-precondition skips