Repository navigation
Add best-of-N restarts to all backends - #299
Merged
Merged
Conversation
This was referenced Aug 25, 2026
Merged
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.
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.
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 = 1andrestart_seeds: Optional[list[int]] = Noneare constructor parameters on every backend, matching whereseedalready lives (AMICATorchNG(...),AMICAMLXNG(...),AMICA_NumPy(...)via its params dict), so the three surfaces are identical. TheAMICAwrapper forwards both throughfit(**kwargs)and mirrors the records.Validation.
n_restarts >= 1;restart_seedsmust have exactlyn_restartsentries; both are validated in the constructor, before any data is touched. Whenrestart_seedsis omitted the seeds areseed, seed+1, ..., seed+n_restarts-1.n_restarts > 1with 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 thekeep_bestiterate where that fired) andll[-1]on NumPy. Ties keep the earlier restart, so the choice is deterministic. Degenerate restarts (nan_ll/singular_ll/nan_params, or NumPy'sconverged=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, aRuntimeError;numpy.linalg.LinAlgError, aValueError; the MLX backend's issue #274 condition-number guard, aRuntimeError) 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 asstop_reason="restart_error"(a shared constant, in every backend's_DEGENERATE_STOP_REASONS, andconverged=Falseon 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 aValueErrorfrom the argument checks still propagates as the caller mistake it is.restart_erroris kept distinct fromsingular_llbecause "the fit could not run" and "the fit ran and reported -inf" are different facts, andrestart_stop_reasons_should say which happened. Only the multi-restart path catches:n_restarts=1still raises exactly as it did before this feature existed, because bit-identity includes error behavior — asserted per backend.Records.
restart_seeds_,restart_lls_andrestart_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, andstate_dict/from_state_dictround-trips them (additively, so pre-#198 payloads still load).Execution. Restarts run serially, so a fit costs
n_restartstimes as long. Parallel restarts are a possible follow-up, not this PR.Extension, not parity. Fortran has no search over seeds; its
maxrestarts/restartiteris a recovery path that redraws A after an early non-finite likelihood and never compares two completed fits. Recorded as row 10 ofdocs/guides/amica-differences.mdwithn_restarts=1stated 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.
fitcalls_fit_oncedirectly 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_ATTRSplusll_history/final_ll_(torch additionally over the LLt arrays, NumPy additionally overndand 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 onen_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'sA,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.pyparses each backend module withast, collects everyself.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 handedself, a mixin in another file, or asetattr(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 ofcore.pymust 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_arrand its schedule counters; NumPy copies the parameters pluscomp_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_parametersonly draws a parameter that is stillNone, and_check_convergenceratchetslrate0/newtratein place with nothing restoring them, so_reset_for_restartnulls 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/fitand 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_blockx 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 NumPywritestepinterleaving case (writestep=1makes every iteration of every restart write, and the on-diskA/W/muafterfitmust 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/saveall 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 pyteston the four new files plustorch_tests/andmlx_tests/: 421 passed, 6 skipped, 4 deselected. Full suite-m "not slow" -n auto: 764 passed, 18 skipped, 1 xfailed.ruff check,ruff format --checkandty check: all clean, zero diagnostics.Closes #198