Repository navigation
Add Fortran convergence criteria to AMICATorchNG - #213
Merged
Merged
Conversation
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
Three tests in test_ng_convergence.py used only bundled EEG and pure PyTorch (no Fortran binary) and ran in seconds, but were marked @pytest.mark.slow. CI runs pytest -m "not slow", documented as excluding tests that invoke the macOS-only Fortran reference binary, so these three never ran in CI. One of them, test_a_frozen_window_still_computes_fresh_grad_norm, is the only test of the dAk/A-freeze decoupling (issue #207), so that change had zero CI coverage. PR #213 review finding 1.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
None of the three fit()-loop stop blocks (decrease branch; min_dll; grad_norm) short-circuits on an earlier one having already fired the same iteration, matching Fortran's independent leave=.true. structure (not a fidelity bug). But the standalone grad_norm check runs unconditionally after the decrease branch, so under the shipped use_grad_norm=True default it always wins: "grad_norm_floor" is unreachable as a final stop_reason, and the use_grad_norm docstring wrongly implied it was the fix for the reported CUDA case. Corrected the docstring/comments in torch_impl/core.py and amica.py, and added a test proving the shadowing under shipped True/True defaults. PR #213 review finding 2.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
test_do_reject_interaction_min_dll_stop_leaves_good_idx_usable set use_min_dll=False, so it actually exercised grad_norm_floor, not min_dll; renamed to match. Added the two genuinely missing do_reject combinations: the standalone min_dll and grad_norm stops. PR #213 review finding 3.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
The old test's trajectory was monotonically increasing, so final_ll_ == max(ll_history) == ll_history[-1] held whether the restore logic worked or was a no-op. Reworked it around the known non-monotone recipe from test_write_amica_output_ll_matches_kept_iterate (#92), combined with a loosened min_dll so the run stops a few iterations past its peak via the new min_dll stop_reason, and assert final_ll_ != ll_history[-1] to prove the restore branch actually ran. PR #213 review finding 4.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
The wrapper usability test's own docstring claimed "transform()/ save() usable" but never called AMICA.save() anywhere in the file. Added a real save()/load() round trip and confirmed the reloaded model reports the same stop_reason_ and reproduces transform() exactly. PR #213 review finding 5.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
Added tests that the five new config keys (use_min_dll/min_dll/ maxincs/use_grad_norm/min_nd) round-trip through state_dict()/ from_state_dict(), and that a simulated pre-#207 payload (format_ version 3, missing those keys) still loads and falls back to the Fortran defaults. Also documented, at the format_version check itself, why it deliberately was not bumped for this change (prior precedent #52/#53 bumped it; the additive-only new keys don't need to). PR #213 review finding 6.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
Every prior min_dll/grad_norm test loosens the threshold by 5-6 orders of magnitude to force a fast stop, which would not catch a scale bug in the comparison itself (issue #212 found exactly that in the numpy_impl backend). Added a fast (a few seconds), non-slow test at the literal shipped defaults (min_dll=1e-9, maxincs=5, use_grad_norm=True, min_nd=1e-7, none overridden) that reaches min_dll via an early Newton start on a small real-data subset. PR #213 review finding 7.
neuromechanist
added a commit
that referenced
this pull request
Aug 10, 2026
Issue #161 flagged two documented-but-untested mir_history_ claims: that a keep_best restore (#51) does not rewrite it (so its last entry can be from discarded, pre-restore parameters, distinct from model.mir(X) on the returned ones), and that it comes back empty after a save/load round trip (not persisted in state_dict()). Both verified true on real data; also updated the module docstring to summarize the full set of PR #213 review additions in this file. Folds in issue #161.
neuromechanist
force-pushed
the
207-ng-convergence-criteria
branch
from
August 10, 2026 01:11
07e23e4 to
ef6d9c4
Compare
AMICATorchNG was missing three Fortran convergence criteria (amica15.f90): use_min_dll/maxincs (consecutive small-gain stop), use_grad_norm/min_nd (weight-gradient-norm stop), and the decrease-branch's ".or. ndtmpsum <= min_nd" half -- the last is why lrate could sit at newtrate and oscillate under do_newton=True without ever stopping. All three are Fortran-faithful defaults (True/1e-9/5/True/1e-7, matching amica15_header.f90). ndtmpsum is now computed every iteration (Fortran-faithful, including the comp_used mask): the direction/dAk computation in _update_parameters was decoupled from the share_comps A-freeze gate, since Fortran computes dAk/ndtmpsum unconditionally in accum_updates_and_likelihood, strictly before the separately-gated update_A step. Default (non-sharing) path is unaffected. New stop_reason values (min_dll, grad_norm, grad_norm_floor) are converged, not degenerate; plumbed through AMICA (**kwargs) and state_dict()/from_state_dict(). Corrected a misleading comment claiming only amica17 normalizes LL before the min_dll comparison -- amica15 (the actual reference binary's source) normalizes identically; the real divergence is numpy_impl's un-normalized raw-sum LL comparison, a separate pre-existing gap this does not touch. Tested: full torch suite green (188 passed, 5 pre-existing skips); validate_implementations.py unchanged at max-iter 100 and 2000 (matches sample_params.json's budget) -- PyTorch LL/iteration count identical before/after, neither stop fires on the bundled 32-channel sample within that budget.
Real bundled sample EEG only. Covers: each stop firing with the right stop_reason (min_dll, grad_norm, grad_norm_floor, and the pre-existing lrate_floor unshadowed by the new check); the maxincs consecutive-count rule including reset-on-larger-gain, verified against an independent reimplementation applied to a stops-disabled reference trajectory rather than hardcoded iteration numbers; the have_prev guard (never fires before two LL values exist); the share_comps freeze window still computing a fresh (non-stale) ndtmpsum every iteration; a converged stop leaving transform/ state_dict/AMICA.save usable; keep_best and do_reject interactions; and that both stops disabled reproduces pre-#207 behavior (never emits the three new stop_reason values). 14/14 pass; ruff and ty clean.
Three tests in test_ng_convergence.py used only bundled EEG and pure PyTorch (no Fortran binary) and ran in seconds, but were marked @pytest.mark.slow. CI runs pytest -m "not slow", documented as excluding tests that invoke the macOS-only Fortran reference binary, so these three never ran in CI. One of them, test_a_frozen_window_still_computes_fresh_grad_norm, is the only test of the dAk/A-freeze decoupling (issue #207), so that change had zero CI coverage. PR #213 review finding 1.
None of the three fit()-loop stop blocks (decrease branch; min_dll; grad_norm) short-circuits on an earlier one having already fired the same iteration, matching Fortran's independent leave=.true. structure (not a fidelity bug). But the standalone grad_norm check runs unconditionally after the decrease branch, so under the shipped use_grad_norm=True default it always wins: "grad_norm_floor" is unreachable as a final stop_reason, and the use_grad_norm docstring wrongly implied it was the fix for the reported CUDA case. Corrected the docstring/comments in torch_impl/core.py and amica.py, and added a test proving the shadowing under shipped True/True defaults. PR #213 review finding 2.
test_do_reject_interaction_min_dll_stop_leaves_good_idx_usable set use_min_dll=False, so it actually exercised grad_norm_floor, not min_dll; renamed to match. Added the two genuinely missing do_reject combinations: the standalone min_dll and grad_norm stops. PR #213 review finding 3.
The old test's trajectory was monotonically increasing, so final_ll_ == max(ll_history) == ll_history[-1] held whether the restore logic worked or was a no-op. Reworked it around the known non-monotone recipe from test_write_amica_output_ll_matches_kept_iterate (#92), combined with a loosened min_dll so the run stops a few iterations past its peak via the new min_dll stop_reason, and assert final_ll_ != ll_history[-1] to prove the restore branch actually ran. PR #213 review finding 4.
The wrapper usability test's own docstring claimed "transform()/ save() usable" but never called AMICA.save() anywhere in the file. Added a real save()/load() round trip and confirmed the reloaded model reports the same stop_reason_ and reproduces transform() exactly. PR #213 review finding 5.
Added tests that the five new config keys (use_min_dll/min_dll/ maxincs/use_grad_norm/min_nd) round-trip through state_dict()/ from_state_dict(), and that a simulated pre-#207 payload (format_ version 3, missing those keys) still loads and falls back to the Fortran defaults. Also documented, at the format_version check itself, why it deliberately was not bumped for this change (prior precedent #52/#53 bumped it; the additive-only new keys don't need to). PR #213 review finding 6.
Every prior min_dll/grad_norm test loosens the threshold by 5-6 orders of magnitude to force a fast stop, which would not catch a scale bug in the comparison itself (issue #212 found exactly that in the numpy_impl backend). Added a fast (a few seconds), non-slow test at the literal shipped defaults (min_dll=1e-9, maxincs=5, use_grad_norm=True, min_nd=1e-7, none overridden) that reaches min_dll via an early Newton start on a small real-data subset. PR #213 review finding 7.
Issue #161 flagged two documented-but-untested mir_history_ claims: that a keep_best restore (#51) does not rewrite it (so its last entry can be from discarded, pre-restore parameters, distinct from model.mir(X) on the returned ones), and that it comes back empty after a save/load round trip (not persisted in state_dict()). Both verified true on real data; also updated the module docstring to summarize the full set of PR #213 review additions in this file. Folds in issue #161.
The test is actually the slowest in the file (~8s from the 326-iteration fit itself), not "well under 3s" as originally written; corrected to state the real number and why it's still not a slow-marker candidate.
The iteration at which min_dll fires is BLAS-dependent: 326 on macOS-arm64, 412 on Linux-x86_64 with a CUDA torch build, and past 500 on the GitHub Linux runner, where CI failed with stop_reason=max_iter. At max_iter=500 the test consumed 82 percent of its budget on the fastest platform, so any numerical variation tipped it over. The claim under test is that the default threshold is reachable at all, not that it is reached by a given iteration, so raise the budget well above the observed spread and record the spread in the docstring. Refs #207
CI failed twice on iteration-count assumptions. First the stop reason, because max_iter=500 left no headroom; then a leftover len(ll_history) < 500 bound after the budget was raised. The stop fires at 326 on macOS-arm64, 412 on Linux-x86_64 with a CUDA torch build, and 1076 on the GitHub runner, so any constant fitted to one machine is a trap. Both bounds now track the budget. The unrelated len(ll_history) == 23 golden value in the lrate_floor test is loosened for the same reason, before it fails the same way. Refs #207
neuromechanist
force-pushed
the
207-ng-convergence-criteria
branch
from
August 10, 2026 01:18
ef6d9c4 to
ec56c33
Compare
3 tasks
This was referenced Aug 15, 2026
3 tasks done
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 #207.
Reported by @SvennoNito from a 236-channel, 8.3M-sample float64 run where the log-likelihood flattened by ~iteration 300 but the fit continued to 1000. The diagnosis in the issue was right: with
do_newton=Truethe learning rate settles atnewtrateand oscillates rather than annealing, solrate_floornever fires andmax_iteris the only working stop.Three gaps, not one
Investigating the report turned up two more beyond the reported
min_dll:use_min_dll/min_dll/maxincs- absent.use_grad_norm/min_nd- absent, and the underlying gradient norm was never computed anywhere intorch_impl/core.py.amica15.f90:1040readsif ((lrate .le. minlrate) .or. (ndtmpsum .le. min_nd)); the port only had the first condition.What changed
AMICATorchNGgainsuse_min_dll=True,min_dll=1e-9,maxincs=5,use_grad_norm=True,min_nd=1e-7, matchingamica15_header.f90:24,74,109._update_parametersnow computesndtmpsumevery iteration as thecomp_used-masked RMS ofdAk. This required decoupling the direction computation from theshare_compsA-freeze: Fortran computesdAk/ndtmpsumunconditionally inaccum_updates_and_likelihood(amica15.f90:1730-1743), strictly before the separately gatedupdate_A(:1785). Only the step itself stays gated. The non-sharing path is bit-for-byte unchanged.fit()gains the two stops plus the missing decrease-branch condition, all gated on having two log-likelihood values (mirroring Fortran'siter > 1), reportingstop_reasonofmin_dll,grad_norm, orgrad_norm_floor. These are converged stops, not degenerate ones, so they are deliberately not in_DEGENERATE_STOP_REASONSand the model stays usable afterwards. Config persists throughstate_dict(); older saved files still load, falling back to constructor defaults.Parity
validate_implementations.py, before and after:do_newton=1)Byte-identical on the PyTorch side at both budgets. The Fortran side wobbles ~1e-5 in LL between runs, which is the binary's own non-determinism, not this change: the PyTorch side ran the same seed and did not move at all.
Do the stops fire?
Not on the bundled 32-channel sample, within any budget this repo uses. At 2000 iterations
ndtmpsumis ~0.0014, roughly 14000x abovemin_nd. The reference Fortran binary was run directly to ~iteration 5073 with matching settings and did not stop either; its ownndplateaus around 1.0-1.65e-5 from ~iteration 2700. So on this dataset both implementations sit on a noise floor well short of the default thresholds. That is worth knowing before anyone expects these criteria to help on small data.The reporter's actual regime (236 channels, CUDA) could not be reproduced here: no CUDA on this machine and no fetch path for data at that scale. The mechanism was confirmed on the bundled sample instead, where
lrate == newtrate == 0.0625and settled at 2000 iterations with Newton on, exactly as reported.Corrections found along the way
The comment at
torch_impl/core.py:94claimed amica17 uniquely normalizes the log-likelihood before themin_dllcomparison. Both amica15 (:1752) and amica17 (:1866) normalize identically. Comment corrected.Separately,
numpy_implis not a faithful reference here: itsself.llis a raw un-normalized sum, so its ownmin_dllcan never fire. Filed as #212, out of scope for this PR.Tests
pamica/tests/torch_tests/test_ng_convergence.py, 14 tests on the real bundled sample, no synthetic data: each stop firing with the rightstop_reason; themaxincsconsecutive-count including reset-on-larger-gain, checked against an independent reimplementation of the Fortran rule rather than hardcoded numbers; neither stop firing before two LL values exist; a fresh (non-stale)ndtmpsumduring ashare_compsfreeze window; usability oftransform/state_dict/AMICA.saveafter each stop;keep_bestanddo_rejectinteractions; and both-disabled reproducing pre-#207 behaviour exactly.Whole suite: 332 passed, 14 skipped, 3 xfailed, 0 failed. The skips are pre-existing opt-in
AMICA_RUN_FORTRAN=1and MLX-gated tests; the three xfails are pre-existingxfail(strict=True)markers intest_sample_data.py, unrelated to this change.ruff check,ruff format, andty checkclean.