Skip to content

Add restart-on-NaN mechanism to NumPy backend (#39) - #42

Merged
neuromechanist merged 3 commits into
mainfrom
39-amica_numpy-long-fit-hits-non-finite-likelihood-nan-iter-687-on-sample-data
Jul 5, 2026
Merged

neuromechanist merged 3 commits into
mainfrom
39-amica_numpy-long-fit-hits-non-finite-likelihood-nan-iter-687-on-sample-data

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Ports Fortran's NaN-recovery to the NumPy backend. The observed failure (CLI diverging to a non-finite likelihood ~iter 687) is a stochastic, init-dependent instability: with a fixed seed the fit is stable, and NG does the identical unfloored exact-EM mu/beta update, so it is a shared algorithm property, not a NumPy-specific bug. Fortran's only mitigation is a restart-on-NaN, which the NumPy backend lacked entirely.

Changes

  • Restart-on-NaN (Fortran amica17.f90:1027-1060): if the LL goes non-finite at iter <= restartiter (default 10), reinitialize from a fresh RNG draw and start over, up to maxrestarts (default 3); a later NaN stops the fit (Fortran exits too). New restartiter/maxrestarts/numrestarts params and a _reinitialize_for_restart helper.
  • Convergence-guard fix: _check_convergence guarded its ll[-2] comparison on self.iter, which keeps counting across restarts; guard on len(self.ll) instead so a post-restart first iteration doesn't IndexError.
  • Tests: fault-injection tests for the restart-recover and give-up-after-maxrestarts paths (real data; a subclass injects a non-finite LL to exercise the error path deterministically). Pinned --seed 0 in test_sample_data_cli so the integration test doesn't depend on a random draw.

Verification

  • Restart tests pass; non-slow suite 36 passed, 1 xfailed.
  • The full 2000-iter CLI run at seed=0 now completes without NaN (finite LL ~-3.41), where a random seed previously diverged.

Honest status on the CLI integration test

test_sample_data_cli stays xfail — this PR is progress, not a pass. The NaN is handled (seed pin + restart => all 2000 iters, no early stop), but a separate long-run drift remains: at ~150 iters seed=0 matches Fortran 32/32 (min corr 0.92), yet by 2000 iters the LL degrades (-3.404 -> -3.409) and some component correlations drop below the 0.8 gate. Fortran stays converged over the same run, so this is a convergence-schedule/stability parity gap, filed as #41. The xfail reason points at #41.

Related

Ports Fortran's NaN recovery (amica17.f90:1027-1060): if the log-likelihood
goes non-finite at iter <= restartiter (default 10), reinitialize from a
fresh RNG draw and start over, up to maxrestarts (default 3); a later NaN
stops the fit (Fortran exits too). The NumPy backend previously had no
restart, so an unlucky init that diverged just ran into a non-finite LL.

- New params restartiter/maxrestarts/numrestarts; _reinitialize_for_restart
  redraws A/mixture params and resets lrate + LL/nd history.
- Restart check in _optimize after the parameter update; restart window is
  restartiter iters after each restart.
- Fix _check_convergence to guard the ll[-2] comparison on len(self.ll), not
  self.iter (which keeps counting across restarts), so a post-restart first
  iteration no longer IndexErrors.
- test_sample_data_cli: pin --seed 0 (a known-stable basin) and un-xfail it;
  an integration test must not depend on a random init that can hit the
  shared stochastic late-NaN divergence. Add fault-injection tests for the
  restart-recover and give-up-after-maxrestarts paths.

Tested: non-slow suite 36 passed, 1 xfailed; restart tests green.
The #39 NaN is handled (pinned seed=0 + restart complete all 2000 iters,
finite LL, no early stop), but the full CLI-vs-Fortran match still fails on
a separate long-run drift: seed=0 matches Fortran 32/32 at ~150 iters but
degrades (LL -3.404 -> -3.409) by 2000 iters. Keep test_sample_data_cli
xfail with an accurate reason pointing at the new issue #41 (the seed pin
and restart stay, since the run now completes without NaN).
- _reinitialize_for_restart now redraws ONLY the mixing matrix A (matching
  Fortran amica17.f90:1032-1053, which keeps the last-successful mixture
  params); the previous cold-reset of mu/alpha/beta/rho/gm/c diverged from
  Fortran's restart trajectory.
- Surface terminal failure instead of a silent success: AMICA.fit sets
  self.converged / self.stop_reason; the CLI logs an error and exits non-zero
  (and no longer claims "Results saved") when the fit ends on a non-finite
  LL. Restart is logged at WARNING, terminal divergence at ERROR.
- Reset numrestarts per fit() (was only set in __init__, so a refit lost the
  restart budget).
- Use Fortran's absolute restartiter window (iter <= restartiter) and drop
  the more-lenient per-restart offset; comment no longer over-claims parity.
- Fix _check_convergence to guard the ll[-2] comparison on len(self.ll).
- Tests assert converged and that the restart is logged (not silent).

Tested: restart tests + non-slow suite green (36 passed, 1 xfailed).
@neuromechanist

Copy link
Copy Markdown
Member Author

Review (code-reviewer + silent-failure-hunter, Sonnet) + resolutions

Findings addressed in the latest commit:

Addressed

  • CRITICAL (parity): restart cold-reset too much. _reinitialize_for_restart was nulling mu/alpha/beta/rho/gm/c, but Fortran's restart (amica17.f90:1032-1053) redraws only A (recomputing comp_list/W) and keeps the last-successful mixture params, skipping the M-step that iteration. Now redraws only A.
  • CRITICAL/HIGH (silent failure): success reported on divergence. After maxrestarts exhaustion the fit ends on a NaN and writes nothing, yet the CLI logged "Results saved" and exited 0, and a library caller had no signal. AMICA.fit now sets self.converged/self.stop_reason; the CLI logs an ERROR and exits non-zero (no false "saved"); restart logs at WARNING, terminal divergence at ERROR.
  • numrestarts not reset on refit → reset at the start of each fit (per-fit budget).
  • Window/count fidelity → use Fortran's absolute iter <= restartiter window (dropped the more-lenient per-restart offset); comment no longer claims byte-for-byte parity on the restart count.
  • Tests now assert converged (True on recover, False on give-up) and that the restart is announced in the run log (guards against a silent-restart regression). The _check_convergence len(self.ll) guard fix is retained.

Verified / not changed

  • Restart loop is bounded (numrestarts cap), continue correctly skips convergence/reject/share/write, post-restart E-step uses the redrawn A, and the finite-guarded final write never persists NaNs (confirmed by test_restart_gives_up_after_maxrestarts).
  • Newton state and comp_list/W are rebuilt by _initialize_parameters; RNG is preserved so each restart is a genuinely new basin.

Non-slow suite: 36 passed, 1 xfailed. The full CLI integration test remains xfail on the separate #41 long-run drift (as documented).

@neuromechanist
neuromechanist merged commit 8328b79 into main Jul 5, 2026
@neuromechanist
neuromechanist deleted the 39-amica_numpy-long-fit-hits-non-finite-likelihood-nan-iter-687-on-sample-data branch July 5, 2026 03:29
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.

AMICA_NumPy long fit hits non-finite likelihood (NaN) ~iter 687 on sample data

1 participant