Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions searches/nss/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# NSS — Nested Slice Sampling (parked implementation)

This directory preserves the **`af.NSS`** nested slice sampler that was
previously bundled with PyAutoFit at
`autofit/non_linear/search/nest/nss/`. It was removed from the library on
2026-07-11 (PyAutoFit#1356) because the bespoke install / CI / build machinery
it required was not justified by its measured performance — but the sampler
works, and this is the full, working implementation kept here so it can be
re-mainlined cheaply once `nss` ships as a genuine PyPI package.

Like `../ultranest/` and `../pyswarms/`, `search.py` imports only from
`autofit`'s base classes, so it is a drop-in `af.NonLinearSearch`. The
intra-package imports were converted to **relative** imports (`from .samples
import NSSamples`, …), so the module works both from here (`from searches.nss
import NSS`) and verbatim if the folder is dropped back into the library.

## What NSS is

A JAX-native nested sampler whose inner sampling loop runs end-to-end inside
`jax.jit`. When the log-likelihood is itself JAX-traceable it avoids the
Python ↔ JAX boundary that Nautilus and Dynesty cross on every call. On the
production lensing likelihoods that motivated it the per-evaluation cost was
roughly **30× lower than Nautilus** (MGE). The catch — and the reason it was
parked rather than kept — is that it is **OOM-prone on pixelization / Delaunay
inversions** via the vmap fan-out, so it was never a clear across-the-board
win.

## Why it couldn't be a normal `pip install autofit[nss]`

Its real dependencies are two **pinned git forks**, and PyPI/TestPyPI reject
direct `git+https://` URLs inside an uploaded wheel
(`400 Can't have direct dependency: blackjax @ git+...`). So the `[nss]` extra
could only carry `fastprogress<1.1`, and the two forks had to be installed
manually afterwards.

### The exact install recipe (needed to run this again)

```bash
pip install "fastprogress<1.1" # keeps fastprogress from pulling python-fasthtml (1.1.5+)
pip install \
"blackjax @ git+https://github.com/handley-lab/blackjax.git@ef45acd2f2fa0cca15adbdcd3ff7cb3a98987cb5" \
"nss @ git+https://github.com/yallup/nss.git@69159b0f4a3a53123b9eec7df91e4ed3885e4dc4"
```

- The **`handley-lab/blackjax`** fork carries the `blackjax.ns.adaptive.init`
entrypoint that mainline blackjax lacks. SHA `ef45acd2` is the May 2026
"Merge PR #60 — double_compile" revision, locally validated against the
Phase 1–3 work.
- **`yallup/nss`** (the sampler itself) sits on top of that fork.
- This fork **conflicts with the mainline `blackjax`** pinned in autofit's
`[optional]` extra — install NSS in its own environment, do not naively
combine or bump the two.

## Requirement: a JAX-traceable analysis

NSS runs the likelihood inside `jax.jit`, so the analysis must be built with
`use_jax=True` (its arithmetic then dispatches through `jax.numpy`). Handing it
a plain NumPy analysis raises `TracerArrayConversionError`. See `example.py`.

## Key kwargs

| kwarg | production default | meaning |
|-------|--------------------|---------|
| `n_live` | 200 | live particles maintained throughout the run |
| `num_mcmc_steps` | 5 | slice-MCMC inner steps per dead-point batch |
| `num_delete` | 50 | particles removed per outer iteration (larger ⇒ less JIT overhead, coarser coverage) |
| `termination` | -3.0 | stop on `logZ_live - logZ` (≈ remaining evidence < 1e-3) |
| `checkpoint_interval` | — | outer iterations between resumable disk checkpoints (SLURM-friendly) |
| `iterations_per_quick_update` | None | if set, calls `analysis.visualize(...)` every N outer iterations |

## Re-mainlining checklist (when `nss` becomes a real pip package)

1. Move this folder back to `PyAutoFit/autofit/non_linear/search/nest/nss/`
(relative imports mean the module files need no edits).
2. Restore `tests/` to `PyAutoFit/test_autofit/non_linear/search/nest/nss/`
— the tests were kept **verbatim** against the library import paths
(`autofit.non_linear.search.nest.nss.*`, including the `mock.patch` target
strings), so they run unchanged from that location.
3. Re-add to `autofit/__init__.py`:
`from .non_linear.search.nest.nss.search import NSS`.
4. Add the dependency to `pyproject.toml`. If `nss` is a real PyPI package by
then, this is finally a plain `nss = ["nss>=X"]` extra — the whole reason
this was removed. Otherwise restore the git+ recipe above.
5. Restore the `Search: NSS` tutorial section in
`autofit_workspace/scripts/searches/nest.py` (see PyAutoFit#1356 diff).

Provenance: removed in PyAutoFit#1356 (2026-07-11); the removal diff is the
authoritative record of every touch-point across the six repos.
1 change: 1 addition & 0 deletions searches/nss/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .search import NSS
115 changes: 115 additions & 0 deletions searches/nss/_chunked_nss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Local replica of ``blackjax.ns.nss.as_top_level_api`` with chunked init.

PyAutoFit#1303 added ``make_chunked_update_strategy`` for the per-iteration
MCMC step path inside ``blackjax.ns.from_mcmc.update_with_mcmc_take_last``.
That covers the inner vmap over ``num_delete`` particles, but **not** the
separate hardcoded ``jax.vmap(init_state_fn)`` inside
``blackjax.ns.nss.as_top_level_api``'s ``init_fn``
(``blackjax/ns/nss.py:223-230`` in the handley-lab fork) — and that's where
inversion-heavy lensing cells (PyAutoLens pixelization / Delaunay at HST
scale) OOM on A100 80 GB before the sampling loop even starts.

This module replaces ``_blackjax.nss(...)`` with a local builder so we
control both seams:

- The chunked update_strategy goes through ``make_chunked_update_strategy``
(PyAutoFit#1303). Behaviour unchanged from that PR.
- The chunked init swaps ``jax.vmap(init_state_fn)`` for
``jax.lax.map(init_state_fn, positions, batch_size=chunk_size)`` so peak
GPU memory during ``algo.init`` becomes ``chunk_size × per_particle_state``
instead of ``n_live × per_particle_state``.

When ``chunk_size`` is None the builder still uses ``jax.vmap`` and is
bit-identical to upstream. The builder otherwise produces a
``blackjax.SamplingAlgorithm`` with the same shape ``_blackjax.nss(...)``
returns, so ``af.NSS._fit`` is a one-line switch.

See PyAutoFit#1304 for the diagnosis and A100 evidence (jobs 322605 /
322606 OOM at the same byte counts as before #1303 landed, because the
crash is in ``algo.init`` not ``algo.step``).
"""

from __future__ import annotations

from functools import partial
from typing import Callable, Optional


def build_chunked_nss_algorithm(
*,
logprior_fn: Callable,
loglikelihood_fn: Callable,
num_inner_steps: int,
num_delete: int,
chunk_size: Optional[int],
):
"""Return a ``blackjax.SamplingAlgorithm`` with chunked init + step paths.

Replicates the body of ``blackjax.ns.nss.as_top_level_api`` (the
handley-lab fork) so we can plug in chunked variants of the two
vmap sites — the inner MCMC step (via the existing
``make_chunked_update_strategy``) and the n_live-wide init.

Parameters
----------
logprior_fn
Log-prior callable, ``positions -> scalar log-prior``.
loglikelihood_fn
Log-likelihood callable, ``positions -> scalar log-L``.
num_inner_steps
Number of HRSS steps per particle replacement (matches
``af.NSS.num_mcmc_steps``).
num_delete
Number of particles replaced per outer iteration (matches
``af.NSS.num_delete``).
chunk_size
Optional GPU-memory knob. When None, both vmap sites use plain
``jax.vmap`` and the result is bit-identical to upstream
``blackjax.nss(...)``. When set, peak memory in each site becomes
``chunk_size × per_particle_state``.
"""
# Local imports keep this module cheap to import when ``af.NSS`` is
# never used (blackjax + jax are optional deps gated by the
# ``[nss]`` extra; see PyAutoFit pyproject.toml).
import jax
from blackjax import SamplingAlgorithm
from blackjax.ns.adaptive import init as ns_init
from blackjax.ns.base import init_state_strategy
from blackjax.ns.nss import build_kernel, update_inner_kernel_params

from ._chunked_update import (
make_chunked_update_strategy,
)

init_state_fn = partial(
init_state_strategy,
logprior_fn=logprior_fn,
loglikelihood_fn=loglikelihood_fn,
)

kernel = build_kernel(
init_state_fn,
num_inner_steps,
num_delete,
update_strategy=make_chunked_update_strategy(chunk_size),
)

def init_fn(position, rng_key=None):
# Mirror the upstream signature (rng_key is unused but accepted for
# API parity with ``blackjax.ns.nss.as_top_level_api``).
if chunk_size is None:
init_batcher = jax.vmap(init_state_fn)
else:
init_batcher = lambda p: jax.lax.map(
init_state_fn, p, batch_size=chunk_size
)
return ns_init(
position,
init_state_fn=init_batcher,
update_inner_kernel_params_fn=update_inner_kernel_params,
)

def step_fn(rng_key, state):
return kernel(rng_key, state)

return SamplingAlgorithm(init_fn, step_fn)
119 changes: 119 additions & 0 deletions searches/nss/_chunked_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Chunked replacement for ``blackjax.ns.from_mcmc.update_with_mcmc_take_last``.

Upstream blackjax fans out ``num_delete`` particles through ``jax.vmap``
with no chunking:

sample_keys = jax.random.split(sample_key, num_delete)
return jax.vmap(mcmc_kernel)(sample_keys, start_state)

On inversion-heavy likelihoods (e.g. PyAutoLens pixelization / Delaunay
source models) the per-particle MCMC state plus scatter temp buffers
exceeds A100 80 GB even at ``num_delete=16``. See PyAutoFit#1301 for the
full diagnosis and per-cell evidence from ``autolens_profiling``.

``chunked_update_with_mcmc_take_last`` accepts a ``chunk_size`` kwarg and
swaps the vmap for ``jax.lax.map(..., batch_size=chunk_size)`` when
``chunk_size < num_delete`` — same vmap parallelism within a chunk, sequential
chunks across. Peak memory becomes ``chunk_size × per_particle_state``
instead of ``num_delete × per_particle_state``.

When ``chunk_size`` is None or ``>= num_delete`` the function is
bit-identical to upstream.

``blackjax.nss(...)`` already exposes ``update_strategy`` as a kwarg
(see ``blackjax/ns/nss.py:157``), so ``af.NSS._fit`` only needs to pass
this builder to opt in:

algo = _blackjax.nss(
...,
update_strategy=make_chunked_update_strategy(chunk_size),
)
"""

from __future__ import annotations

from functools import partial
from typing import Callable, Optional


def make_chunked_update_strategy(chunk_size: Optional[int]) -> Callable:
"""Return an ``update_strategy`` callable for ``blackjax.nss(...)``.

Signature matches ``blackjax.ns.from_mcmc.update_with_mcmc_take_last``
so it can be passed through the ``update_strategy=`` kwarg unmodified.

Parameters
----------
chunk_size
Number of particles to vmap-batch per chunk. When None or
``>= num_delete`` the chunked path is skipped and the function
falls through to a plain ``jax.vmap`` (matching upstream
behaviour bit-for-bit).
"""

def chunked_update_with_mcmc_take_last(
constrained_mcmc_step_fn,
num_mcmc_steps,
num_delete,
):
"""Drop-in for ``blackjax.ns.from_mcmc.update_with_mcmc_take_last``.

Identical to upstream except the inner
``jax.vmap(mcmc_kernel)(sample_keys, start_state)`` is replaced
with ``jax.lax.map(..., batch_size=chunk_size)`` when
``chunk_size`` is set and smaller than ``num_delete``.
"""
import jax
import jax.numpy as jnp

def update_function(rng_key, state, loglikelihood_0, **step_parameters):
choice_key, sample_key = jax.random.split(rng_key)
particles = state.particles

# Select start particles from survivors (verbatim from upstream).
weights = (particles.loglikelihood > loglikelihood_0).astype(jnp.float32)
weights = jnp.where(weights.sum() > 0.0, weights, jnp.ones_like(weights))
start_idx = jax.random.choice(
choice_key,
len(weights),
shape=(num_delete,),
p=weights / weights.sum(),
replace=True,
)
start_state = jax.tree.map(lambda x: x[start_idx], particles)

shared_mcmc_step_fn = partial(
constrained_mcmc_step_fn,
loglikelihood_0=loglikelihood_0,
**step_parameters,
)

def mcmc_kernel(rng_key, state):
keys = jax.random.split(rng_key, num_mcmc_steps)

def body_fn(state, rng_key):
new_state, info = shared_mcmc_step_fn(rng_key, state)
return new_state, info

final_state, infos = jax.lax.scan(body_fn, state, keys)
return final_state, infos

sample_keys = jax.random.split(sample_key, num_delete)

# Fall through to bit-identical upstream behaviour when the
# user hasn't asked for chunking, or when the requested chunk
# already covers every particle.
if chunk_size is None or chunk_size >= num_delete:
return jax.vmap(mcmc_kernel)(sample_keys, start_state)

# Chunked path: jax.lax.map(batch_size=k) vmaps within each
# chunk-of-k particles and loops across chunks.
return jax.lax.map(
lambda xs: mcmc_kernel(xs[0], xs[1]),
(sample_keys, start_state),
batch_size=chunk_size,
)

return update_function

return chunked_update_with_mcmc_take_last
Loading