Skip to content

feat: af.NSS checkpoint/resume + on-the-fly visualization (Phases 2-3) - #1274

Merged
Jammy2211 merged 1 commit into
mainfrom
feature/nss-checkpointing-and-visualization
May 16, 2026
Merged

Jammy2211 merged 1 commit into
mainfrom
feature/nss-checkpointing-and-visualization

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Summary

Phases 2 and 3 of the nss_first_class_sampler roadmap ship together because they share the same architectural hook — the outer loop in NSS._fit. Closes #1273.

  • Phase 2 (checkpoint/resume): new checkpoint_interval: int = 100 kwarg; a nss_checkpoint.pkl is written atomically (tmp-and-rename) every N outer iterations to paths.search_internal_path. On _fit entry, an existing checkpoint is loaded and the run resumes from the saved (state, dead, run_key, iteration). Post-success cleanup deletes the checkpoint.
  • Phase 3 (on-the-fly viz): iterations_per_quick_update (accepted but no-op in Phase 1) now wires to a _fire_quick_update helper that picks the current best live particle and calls analysis.visualize(paths, instance, during_analysis=True). Wrapped in try/except so a viz failure logs a warning but does not kill a long fit.
search = af.NSS(
    name="my_fit",
    n_live=200,
    num_mcmc_steps=5,
    num_delete=50,
    termination=-3.0,
    checkpoint_interval=100,         # NEW
    iterations_per_quick_update=10,  # was no-op in Phase 1, now functional
)
# SLURM timeout mid-fit? Re-run with same paths — resumes from checkpoint automatically.
result = search.fit(model=model, analysis=analysis)

Key architectural finding

The roadmap claimed nss.ns.run_nested_sampling is a one-shot JIT'd jax.lax.while_loop requiring an upstream yallup/nss PR to add a checkpoint hook. Inspecting the upstream source revealed this is wrong — the JIT boundary is one_step (one outer iteration processing num_delete deaths in a JIT'd algo.step call); the outer while loop is plain Python. This means checkpointing and visualization can be implemented entirely inside NSS._fit by inlining the upstream loop pattern. No upstream PR needed.

The PR replaces the single run_nested_sampling call with a blackjax.nss(...) algo + JIT'd one_step closure + manual outer while loop, mirroring the upstream pattern verbatim. After the loop, nss.ns.finalise builds the final_state and nss.ns.log_weights produces the per-particle weights — same as the upstream Results packaging.

Test plan

  • pytest test_autofit — 1258 passed, 1 skipped (1252 baseline + 6 new checkpoint tests: _save_checkpoint / _load_checkpoint pytree round-trip, atomic-write semantics under simulated rename failure, _nss_checkpoint_path returns None for NullPaths, __init__ accepts checkpoint_interval, Phase 1 stub warning no longer fires, resume branch detection via mocked _load_checkpoint).
  • End-to-end resume smoke (autolens_workspace_developer/searches_minimal/nss_checkpoint_resume.py, ships in matching workspace_developer PR): two passes on a 2D Gaussian flat-likelihood problem. Capture pass snapshots the first checkpoint write before the post-success cleanup deletes it; resume pass restores the snapshot at the expected path and verifies the "Resuming NSS from checkpoint" log fires + identical final log_evidence (-0.0096) + post-success cleanup deletes the resumed-run checkpoint.
  • Phase 3 visualization: the resume smoke counts analysis.visualize invocations and asserts ≥ 1; the actual capture pass fired the hook 4 times.
  • Phase 1 regression (searches_minimal/nss_first_class_gaussian.py): still passes in 7 s wall, ESS 94/95, posterior recovers prior means under flat likelihood. Wrapper behaviour unchanged for users who don't set checkpoint_interval or iterations_per_quick_update.

API Changes

Pure additive at the kwarg level (checkpoint_interval=100); iterations_per_quick_update was already accepted in Phase 1 and is now functional. New module-level helpers _save_checkpoint / _load_checkpoint and a new _NSSInternal repackaging step. No existing API touched.
See full details below.

Full API Changes (for automation & release notes)

Added

  • autofit.NSS.__init__(checkpoint_interval: int = 100, ...) — new kwarg controlling outer iterations between checkpoint writes. Identifier fields unchanged.
  • autofit.NSS.checkpoint_file — public property exposing the resolved checkpoint path (paths.search_internal_path / "nss_checkpoint.pkl"). Returns None for NullPaths. Mirrors the existing Nautilus.checkpoint_file convention.
  • autofit.non_linear.search.nest.nss.search._save_checkpoint(path, state, dead, run_key, iteration) — module-level helper. Atomic pickle write via tmp-and-rename. Round-trips JAX pytrees through NumPy.
  • autofit.non_linear.search.nest.nss.search._load_checkpoint(path) — inverse helper. Returns (state, dead, run_key, iteration) with JAX arrays restored.

Changed Behaviour

  • autofit.NSS.iterations_per_quick_update — was accepted-but-no-op in Phase 1 with a log warning. Now functional: every N outer iterations the current best live particle is fed to analysis.visualize(paths, instance, during_analysis=True). The Phase 1 "not yet wired" log is gone.
  • autofit.NSS._fit — replaces the single nss.ns.run_nested_sampling(...) call with an inlined blackjax.nss + manual outer while loop. Behaviour is mathematically equivalent for a single-shot run; the new code path also writes/reads checkpoints between iterations.
  • autofit.NSS.checkpoint_file — previously pointed at the unused state.json Phase 1 sentinel. Now points at nss_checkpoint.pkl.

Migration

None — pure addition + behaviour upgrade. Existing af.NSS(...) callers that didn't set checkpoint_interval or iterations_per_quick_update see no change. Existing callers that set iterations_per_quick_update no longer trip the Phase 1 stub warning and now get real on-the-fly visualization (intended behaviour from day 1).

🤖 Generated with Claude Code

Phases 2-3 of nss_first_class_sampler land together — they share the
same architectural hook (the outer loop in NSS._fit) so the PR couples
them naturally.

Phase 2 — checkpointing/resume:
- New checkpoint_interval kwarg (default 100 outer iterations).
- Module-level _save_checkpoint / _load_checkpoint helpers serialise
  the (state, dead, run_key, iteration) tuple via pickle, round-tripping
  through NumPy with jax.tree_util.tree_map so the on-disk format is
  independent of the JAX install. Atomic via tmp-and-rename — a SLURM
  timeout halfway through a write leaves the previous good checkpoint
  intact.
- _fit detects an existing nss_checkpoint.pkl at paths.search_internal_path
  on entry and resumes; otherwise initialises fresh. Post-success
  cleanup deletes the checkpoint to mirror Nautilus's
  output_search_internal pattern.

Phase 3 — on-the-fly visualization:
- iterations_per_quick_update (already accepted but no-op in Phase 1)
  now wires to a _fire_quick_update helper that picks the current best
  live particle from state.particles and calls
  analysis.visualize(paths, instance, during_analysis=True). Wrapped
  in try/except so a viz failure logs a warning but does not kill a
  long fit.

Implementation: the upstream nss.ns.run_nested_sampling outer loop is
plain Python (not jax.lax.while_loop — the JIT boundary is one_step,
processing num_delete deaths per outer iteration). Inlining the loop
in NSS._fit lets us hook checkpoint writes + viz calls between
iterations without any upstream yallup/nss PR. Replaces the single
run_nested_sampling call with a blackjax.nss algo + manual outer
while-loop + finalise + log_weights — mirroring the upstream pattern.

Phase 1's stub log warnings (resume-not-supported, iterations_per_quick_update-no-op)
removed. checkpoint_file property now points at nss_checkpoint.pkl
(was the unused state.json sentinel).

Closes #1273

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@Jammy2211 Jammy2211 added the pending-release PR queued for the next release build label May 16, 2026
@Jammy2211
Jammy2211 merged commit c163c8a into main May 16, 2026
2 of 4 checks passed
@Jammy2211
Jammy2211 deleted the feature/nss-checkpointing-and-visualization branch May 16, 2026 09:28
@Jammy2211 Jammy2211 removed the pending-release PR queued for the next release build label Sep 4, 2026
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.

feat: af.NSS checkpointing + on-the-fly visualization (Phases 2-3)

1 participant