Skip to content

feat: af.NSS NonLinearSearch wrapper for Nested Slice Sampling (Phase 1 of nss_first_class_sampler) - #1272

Merged
Jammy2211 merged 1 commit into
mainfrom
feature/nss-search-wrapper
May 16, 2026
Merged

Jammy2211 merged 1 commit into
mainfrom
feature/nss-search-wrapper

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Summary

Adds af.NSS — a first-class NonLinearSearch wrapping nss.ns.run_nested_sampling (JAX-native, yallup/nss). Drop-in replacement for af.Nautilus(...) in any production autolens / autogalaxy / autofit script. Closes Phase 1 of the nss_first_class_sampler roadmap (#1271), unblocked by the Phase 0 JAX-native priors that landed in #1263 + the sign-convention fix in #1269.

import autofit as af

search = af.NSS(
    name="my_fit",
    n_live=200,
    num_mcmc_steps=5,
    num_delete=50,
    termination=-3.0,
)
result = search.fit(model=model, analysis=analysis)

The new module lives under autofit/non_linear/search/nest/nss/ and mirrors nautilus/'s structure. The _fit body builds JAX-traceable log_likelihood and prior_logprob closures threaded through Phase 0's xp=jnp plumbing (model.vector_from_unit_vector, model.log_prior_list_from_vector, model.instance_from_vector all with xp=jnp), draws n_live initial particles by mapping unit-cube samples through the prior transform, then calls nss.ns.run_nested_sampling. The returned final_state + results are repackaged into a NumPy-only _NSSInternal holder so the standard PyAutoFit pickled-search path keeps working — samples_via_internal_from then converts to NSSamples(SamplesNest) and AbstractNest.perform_update writes the standard output set (samples.csv, samples_summary.json, samples_info.json, etc.).

The numerical headline is the same nss_jit per-eval cost from the FINDINGS_v3 profiling project — 0.52 ms/eval on the HST MGE 15-dim likelihood vs 17.9 ms/eval for Nautilus on the same problem, ~30× faster per-eval. The new af.NSS wrapper makes that available to production users without leaving the standard Paths / Result / Aggregator plumbing.

What's stubbed (Phases 2/3/4)

  • Checkpointing / resumption (Phase 2): iterations_per_quick_update and iterations_per_full_update are accepted for API parity but log a warning when set. A state.json existence check under paths.search_internal_path warns that resume is not yet supported (the fit then proceeds from scratch).
  • On-the-fly visualization (Phase 3): same — iterations_per_quick_update is accepted but doesn't fire visualizations yet.
  • Install simplification (Phase 4): the nss import is guarded so import autofit works without the dep. af.NSS() raises a clear ImportError pointing at pip install git+https://github.com/yallup/nss.git. Phase 4 will ship a pip install autofit[nss] extra.

Design notes baked into this PR

  • Sampling space: physical, not unit-cube (status quo from nss_jit_one_config.py on the HPC). Slice walks have the natural metric of the problem and no per-step remapping cost. Documented in the af.NSS docstring.
  • log_evidence_error: exposed via NSSamples.log_evidence_error as logZs.std() — the stochastic batch error of the NS evidence estimator across the live ensemble.
  • number_of_cores: accepted for API parity only; ignored by NSS (JAX runs on whatever device it's configured for). Logs a warning if set > 1.
  • Fitness return: _fit returns a Fitness(model, analysis, paths, fom_is_log_likelihood=True, batch_size=1) instance even though af.NSS does not route through Fitness._call for sampling (it uses inline JAX closures). The Fitness object is required by AbstractNest.perform_update for post-fit work like latent-sample generation, which calls fitness.batch_size.
  • JIT persistent cache: left for a follow-up. Each cold fit currently pays a ~25-30s run_nested_sampling while_loop compile.

API Changes

Added af.NSS (Nested Slice Sampling) as a new public sampler at the top level, plus NSSamples as the corresponding posterior-samples class. Pure addition — no existing classes / signatures / behaviours change. The nss import is optional and guarded; import autofit continues to work without it.
See full details below.

Test Plan

  • pytest test_autofit — 1252 passed, 1 skipped (1242 baseline + 10 new NSS unit tests)
  • test_autofit/non_linear/search/nest/nss/test_search.py — 9 tests covering __init__ validation, identifier_fields, test-mode termination, ImportError when nss unavailable (monkeypatch _HAS_NSS=False), number_of_cores > 1 warning, samples_info_from with synthetic _NSSInternal, samples_via_internal_from returns NSSamples, weight normalisation (including the uniform-log-weight edge case), NSSamples.log_evidence_error property.
  • Fast Gaussian wiring smoke (autolens_workspace_developer/searches_minimal/nss_first_class_gaussian.py — ships in matching workspace PR) — runs af.NSS().fit(...) end-to-end in 10 sec wall on a 2D Gaussian flat-likelihood problem; recovers prior means via weighted posterior (x=2.4481 vs target 2.5, y=-0.9774 vs target -1.0), ESS 94/95, samples.csv written through the Paths pipeline, Result.max_log_likelihood_instance round-trips.
  • HST MGE numerical smoke (autolens_workspace_developer/searches_minimal/nss_first_class.py) — wiring confirmed via partial run (JIT compiled, nss accepted closures, 1000+ dead points accumulated with monotonic logZ progression). Full numerical-parity validation (einstein_radius=1.5996 ± 0.0002) on HPC GPU pending; the bare-script nss_jit.py already demonstrated the science result and this PR just wraps the bare call.
Full API Changes (for automation & release notes)

Added

  • autofit.NSS (autofit/non_linear/search/nest/nss/search.py) — new top-level NonLinearSearch for Nested Slice Sampling.
    Signature:
    NSS(
        name: Optional[str] = None,
        path_prefix: Optional[str] = None,
        unique_tag: Optional[str] = None,
        n_live: int = 200,
        num_mcmc_steps: int = 5,
        num_delete: int = 50,
        termination: float = -3.0,
        iterations_per_quick_update: Optional[int] = None,
        iterations_per_full_update: Optional[int] = None,
        number_of_cores: int = 1,
        seed: int = 42,
        silence: bool = False,
        session: Optional[sa.orm.Session] = None,
        **kwargs,
    )
    Identifier fields: n_live, num_mcmc_steps, num_delete, termination, seed. Raises ImportError from __init__ if the optional nss package is not installed.
  • autofit.non_linear.search.nest.nss.samples.NSSamples — SamplesNest subclass for NSS posteriors. Exposes log_evidence_error (the logZs.std() from the NS estimator's live ensemble).
  • autofit.non_linear.search.nest.nss package — internal module path; imports NSS for convenience.

Migration

None — pure addition. Existing users of af.Nautilus, af.DynestyStatic, af.Emcee, etc. are unaffected.

For users who want to adopt the new sampler:

# Before:
search = af.Nautilus(name="...", n_live=3000)

# After:
search = af.NSS(name="...", n_live=200, num_mcmc_steps=5, num_delete=50)

The optional nss dependency must be installed first (Phase 4 will ship a pip install autofit[nss] extra; for now: pip install git+https://github.com/yallup/nss.git).

🤖 Generated with Claude Code

Adds `af.NSS` — a first-class `NonLinearSearch` wrapping `nss.ns.run_nested_sampling`
(JAX-native, yallup/nss). Drop-in replacement for `af.Nautilus(...)` in any production
script. Phase 1 of the nss_first_class_sampler roadmap.

The new module `autofit/non_linear/search/nest/nss/` mirrors `nautilus/`'s structure:
search.py holds `NSS(AbstractNest)` + an `_NSSInternal` post-run state holder;
samples.py holds `NSSamples(SamplesNest)` (thin subclass for type identity, exposes
`log_evidence_error`). Optional-import guard for `nss.ns` keeps `import autofit`
working without the dep — `af.NSS()` raises a clear `ImportError` pointing at the
Phase 4 install simplification.

`_fit` builds JAX-traceable `log_likelihood` and `prior_logprob` closures through
Phase 0's xp=jnp plumbing (#1262 / #1266), draws n_live initial
samples by mapping unit-cube draws through `model.vector_from_unit_vector`, and
calls `run_nested_sampling`. The returned state is repackaged into a NumPy-only
`_NSSInternal` holder so the standard PyAutoFit pickled-search path works.

Phase 2 (checkpointing) and Phase 3 (on-the-fly visualization) are stubbed —
`iterations_per_quick_update` is accepted with a no-op log, and a state.json
existence check warns instead of resuming. JIT persistent cache is left for a
follow-up. Sampling space is physical (status quo from the validated bare
nss_jit.py reference).

Refs #1271

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 afc6f32 into main May 16, 2026
2 of 4 checks passed
@Jammy2211
Jammy2211 deleted the feature/nss-search-wrapper branch May 16, 2026 08:55
@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.

1 participant