Skip to content

Add best-of-N restarts to all backends - #299

Merged
neuromechanist merged 9 commits into
devfrom
feature/issue-198-restarts
Aug 24, 2026
Merged

neuromechanist merged 9 commits into
devfrom
feature/issue-198-restarts

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Adds best-of-N random restarts to all three array backends: run the fit from several seeds and keep the highest-likelihood one. Issue #145 showed the backend and the binary agree to 0.9974 mean correlation from an identical init, so the disagreement seen from random inits is basin choice on the weakest under-determined components, not a dynamics difference; picking the best of several seeds is the standard answer, and it extends #51's keep_best (best iterate within a run) across runs.

Decided policies

API. n_restarts: int = 1 and restart_seeds: Optional[list[int]] = None are constructor parameters on every backend, matching where seed already lives (AMICATorchNG(...), AMICAMLXNG(...), AMICA_NumPy(...) via its params dict), so the three surfaces are identical. The AMICA wrapper forwards both through fit(**kwargs) and mirrors the records.

Validation. n_restarts >= 1; restart_seeds must have exactly n_restarts entries; both are validated in the constructor, before any data is touched. When restart_seeds is omitted the seeds are seed, seed+1, ..., seed+n_restarts-1. n_restarts > 1 with no base seed and no explicit seeds is refused with a ValueError: best-of-N is only meaningful if the winner can be reproduced, and pamica will not seed itself from the clock or from OS entropy.

Selection. Highest returned-iterate log-likelihood wins, i.e. exactly final_ll_ on the torch and MLX backends (already the keep_best iterate where that fired) and ll[-1] on NumPy. Ties keep the earlier restart, so the choice is deterministic. Degenerate restarts (nan_ll/singular_ll/nan_params, or NumPy's converged=False) are excluded from selection but recorded with a NaN likelihood; if every restart is degenerate the model is left holding the last one, so #50's degenerate-fit contract applies exactly as it does to a single degenerate fit.

Failure isolation. A restart that raises is isolated exactly like one that ends degenerate. A truly singular mixing matrix makes the unmixing inversion raise (torch.linalg.LinAlgError, a RuntimeError; numpy.linalg.LinAlgError, a ValueError; the MLX backend's issue #274 condition-number guard, a RuntimeError) rather than produce the non-finite likelihood the in-loop guards catch — and inside a best-of-N search, letting that propagate would discard the restarts that already succeeded, which is the exact opposite of the feature's purpose. Each per-restart fit is therefore wrapped: the failure is recorded as stop_reason="restart_error" (a shared constant, in every backend's _DEGENERATE_STOP_REASONS, and converged=False on NumPy), logged at WARNING with the exception type and message, and the search continues with the next seed. The catch is deliberately narrow — only the numerical-failure types, so a ValueError from the argument checks still propagates as the caller mistake it is. restart_error is kept distinct from singular_ll because "the fit could not run" and "the fit ran and reported -inf" are different facts, and restart_stop_reasons_ should say which happened. Only the multi-restart path catches: n_restarts=1 still raises exactly as it did before this feature existed, because bit-identity includes error behavior — asserted per backend.

Records. restart_seeds_, restart_lls_ and restart_stop_reasons_ are index-aligned lists on the fitted model, populated even for the default single-restart fit, plus one INFO line naming the winner. The wrapper mirrors all three, and state_dict/from_state_dict round-trips them (additively, so pre-#198 payloads still load).

Execution. Restarts run serially, so a fit costs n_restarts times as long. Parallel restarts are a possible follow-up, not this PR.

Extension, not parity. Fortran has no search over seeds; its maxrestarts/restartiter is a recovery path that redraws A after an early non-finite likelihood and never compares two completed fits. Recorded as row 10 of docs/guides/amica-differences.md with n_restarts=1 stated as the parity-preserving default.

Bit-identity at n_restarts=1

The single-restart path bypasses the restart machinery entirely: no snapshot, no reseeding, no reset, no extra RNG draw. fit calls _fit_once directly and only writes the record lists afterwards. This is asserted per backend by comparing against a model constructed without any restart argument, over every attribute in that backend's _RESTART_STATE_ATTRS plus ll_history/final_ll_ (torch additionally over the LLt arrays, NumPy additionally over nd and the RNG state): exact equality, no tolerance.

Acceptance evidence

The acceptance test on each backend runs three independent fits on the real sample EEG at seeds [54, 50, 42], then one n_restarts=3, restart_seeds=[54, 50, 42] fit, and asserts the latter equals the argmax of the former state for state - every attribute the fit path writes, not just the likelihood. The seeds are ordered best-to-worst so the winner is the FIRST restart (asserted), since a winner that happened to be last would leave the snapshot/restore path untested. Measured on the bundled 32-channel sample at 5 iterations: per-restart LLs -3.264177210 / -3.264757966 / -3.264984217 (torch and NumPy, float64; MLX float32 agrees to 6e-7), winner restart 1 (seed 54), and the winning model's A, W, mu, alpha, beta, rho, gm, c, comp_list, pdtype, ll_history, final_ll_, LLt arrays, counters and tuned block size all compare bit-equal to the standalone seed-54 fit. The NumPy backend additionally reproduces that fit's full RNG state (generator, key, position, and the cached-Gaussian fields).

The seed choice is a flake-margin decision, not a convenience. The winner leads the runner-up by 5.8e-4 and the last restart by 8.1e-4, against float64 BLAS summation noise of ~1e-12 relative (~3e-12 absolute on an LL of ~3.26) - about eight orders of magnitude of headroom, so an OpenBLAS/Accelerate swap or a thread-count change cannot reorder the winners (the issue #241 flake class). On MLX the same margin sits ~1500x above float32 noise (~4e-7). For contrast, the obvious alternative of "more iterations" is worse: at 10 iterations the top two seeds converge to within 2.9e-7 of each other, which is exactly the configuration that would flake. The winner-is-first precondition also carries an assert message saying that a failure there is a platform-BLAS ordering finding to report, not a correctness bug in the restart loop.

State-copy completeness

Each backend declares _RESTART_STATE_ATTRS (copied per restart) and _RESTART_INVARIANT_ATTRS (written by the fit path but a function of the data alone, so constant across the restarts of one call). pamica/tests/test_restart_policy.py parses each backend module with ast, collects every self.x = ... target in every method except __init__/_setup_logging/_load_params, and asserts exact set equality against those two lists plus the shared record names. Adding a field to a fit-path method - or leaving a stale name behind - fails the suite until it is classified, which is what stops a future field from being silently dropped from a winning restart's state.

The guard has one documented blind spot, now written into the test: it only sees self.<attr> = ... inside the backend class in its own module, so a module-level helper handed self, a mixin in another file, or a setattr (which the restore itself uses - counting it would make the guard circular) is invisible. No such fit-path mutator exists today; a refactor that moves fit-path logic out of core.py must extend the scan.

Per-backend copied sets: torch copies A, W, c, mu, alpha, beta, rho, gm, comp_list, pdtype, iteration, ll_history, final_ll_, stop_reason, mir_history_, n_newton_fallbacks, n_kurt_done, numrej, good_idx, _ndtmpsum, lrate, lrate_cap, newtrate, rholrate, _llt_logv, _llt_ll, _llt_lht, _llt_lt, block_size, seed; MLX copies the same parameter set plus _comp_used_arr, _lgamma_table, _logdet_W, _nd_arr and its schedule counters; NumPy copies the parameters plus comp_used, sigma2, lambda_, kappa, iter, ll, nd, converged, stop_reason, numrej, numrestarts, good_idx, num_good_samples, _last_ll_samples, _llt_logv, _llt_ll, lrate, lrate0, newtrate, rholrate, block_size, seed, rng.

The NumPy backend needed one extra piece: its _initialize_parameters only draws a parameter that is still None, and _check_convergence ratchets lrate0/newtrate in place with nothing restoring them, so _reset_for_restart nulls the parameters and restores the pristine rates. Without it restart k+1 would continue from restart k's solution and annealed schedule; a dedicated test pins the rates against an independent fit. The torch and MLX backends already reset everything in _initialize_parameters/fit and needed no such method.

Tests

pamica/tests/test_restart_policy.py (shared seed derivation, selection, copy semantics, cross-backend surface and the structural guard), pamica/tests/torch_tests/test_ng_restarts.py, pamica/tests/test_numpy_restarts.py, pamica/tests/mlx_tests/test_mlx_restarts.py. Real sample EEG only, exact-equality assertions, no timing or trajectory-dependent guards, so they are machine-robust; the MLX file self-skips off Apple Silicon and runs in macOS CI.

The mixed degenerate/healthy case uses the error-path injection pattern already established by test_sample_data.py::test_restart_gives_up_after_maxrestarts: a subclass corrupts the likelihood for one named seed while every other seed runs the untouched algorithm on the real recording. It is the only way to get a mixed set of restarts - NaN in the data degenerates every seed alike (and raises in NumPy preprocessing before any fit), and divergence from a plain hyperparameter is a machine-dependent outcome no CI can rely on. Crash isolation is tested the same way, injected at the hook the real failure comes from (_update_unmixing_matrices -> the inversion) with the exception type each library actually raises: the best seed crashes, so the winner must come from the survivors; a single-restart fit with the same injection must still raise; and an all-crashed search must keep the degenerate contract.

Added in review, beyond the original suite: do_opt_block x restarts on all three backends (the block-size search's return value is stubbed deterministically - which size wins a real sweep is documented as machine-dependent - so two restarts tune to different sizes and the winner's must survive the restore); the NumPy writestep interleaving case (writestep=1 makes every iteration of every restart write, and the on-disk A/W/mu after fit must equal the winner's in-memory state and an independent fit from the winning seed, turning the documented caveat into a tested claim); the wrapper x restarts x all-degenerate integration case (is_fitted_/converged_ false, transform/get_mixing_matrix/save all refusing, records still readable); and the MLX explicit-single-seed override case that was missing next to its torch and NumPy siblings.

Gates

uv run pytest on the four new files plus torch_tests/ and mlx_tests/: 421 passed, 6 skipped, 4 deselected. Full suite -m "not slow" -n auto: 764 passed, 18 skipped, 1 xfailed. ruff check, ruff format --check and ty check: all clean, zero diagnostics.

Closes #198

@neuromechanist
neuromechanist merged commit d392ba0 into dev Aug 24, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-198-restarts branch August 24, 2026 04:16
This was referenced Aug 25, 2026
neuromechanist added a commit that referenced this pull request Aug 25, 2026
* Complete 0.3.3 changelog for release

Rename Unreleased to 0.3.3 with a release summary and add the missing
user-facing entries: best-of-N restarts (#198/#299), MNE bad_* annotation
rejection (#251/#252), the numpy comp_used staleness fix (#240/#243), and
the nd pre-update gm weighting (#219/#241). Docs only, not tested beyond
proofread.

* Correct stale counts and citations in changelog

The 0.3.3 param-reader entry still said 36 unsupported keywords and
listed the do_opt_block search among them; #232 moved those four keys
to identity mappings, leaving 32 (fortran_params.py's own arithmetic:
57 + 32 = 89). Also aligned two Fortran citations with the literal
source: the loglik/modloglik allocation spans 2617-2620 and the
reject_data zeroing block 2231-2234, matching the ranges now used
across the codebase. Docs only.
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.

Improve NG init-robustness on under-determined components (best-of-N restarts)

1 participant