Skip to content

feat: af.SMC — blackjax adaptive tempered SMC search - #1546

Merged
Jammy2211 merged 1 commit into
mainfrom
feature/blackjax-smc-search
Aug 29, 2026
Merged

Jammy2211 merged 1 commit into
mainfrom
feature/blackjax-smc-search

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Closes #1544. Rung 2 of the overflow-flood fix wave — the af.SMC library half, which the autolens_profiling SMC cell and the A100 probe (Wave B) depend on.

Ports the validated gradient-SMC prototype (autolens_workspace_developer branch feature/blackjax-smc-gradient-kernel, searches_minimal/blackjax_smc_grad.py + smc_gradient_findings.md) into the library, templated on the sibling blackjax/nuts/search.py and reusing blackjax/chains.py.

What this adds

af.SMC wraps blackjax.adaptive_tempered_smc with a gradient inner kernel — MALA by default, HMC optionally — sampling in a whitened space and recovering log Z for free from the tempering increments. It is the first PyAutoFit search that is both gradient-based and evidence-producing.

The three measured fixes that made the prototype sample are carried over verbatim, each documented at the site it applies:

  • Full-covariance Cholesky whitening from a warm start. Prior-whitening does not whiten the posterior (269x anisotropy measured on a 15-parameter lens model), and diagonal whitening leaves a tilted ridge (condition number 568, |r| = 0.95). inverse_mass_matrix accepts a Result/Samples/array and is resolved through the existing chains.resolve_inverse_mass_matrix.
  • The step targets the posterior width, not the reference width. The warm reference is inflated by whiten_inflate so it covers the posterior, so scaling to the reference's own width overshoots by whiten_inflate^2 (measured: eps=1.148 -> acc 0.00, eps=0.1 -> acc 0.94).
  • MALA's step_size is a squared length. The auto-scaling applies ell = 2.38 * d^(-1/6) * sigma, eps = ell^2 / 2, and sigma * d^(-1/4) for HMC.

There is deliberately no per-temperature kernel adaptation: blackjax.smc.inner_kernel_tuning was measured to collapse acceptance (0.04–0.12, worse than a fixed step's 0.84 → 0.15 decay).

Warm starting keeps the evidence. Dropping the particles at a previous best fit would destroy log Z, which is only valid when tempering starts from a normalised distribution. So the warm path does not shortcut lambda: it still starts at 0, but from a normalised Gaussian reference g centred on the warm-start point, bridged as logprior_fn := log g, loglikelihood_fn := log prior + log L - log g, with log|det L| added back. The cold path needs neither correction — the SMC estimator is a ratio in which both cancel — and that asymmetry is pinned by a test.

A run is judged by its acceptance trace, not by converged. "Tempering reached lambda = 1" is a criterion an acceptance-collapsed run satisfies while reporting garbage log Z, so the lambda schedule, per-step acceptance and realised ESS are persisted to search_internal and surfaced on SamplesSMC as lambda_list / acceptance_rate_list / ess_list.

API Changes

New public class: af.SMC (lazily exported via _LAZY_ATTRS, like af.NSS; nothing at import time pulls jax or blackjax).

af.SMC(
    name=None, path_prefix=None, unique_tag=None,
    num_particles=256,            # particles, and the number of posterior samples returned
    kernel="mala",                # "mala" (default) or "hmc"
    num_mcmc_steps=5,             # inner-kernel updates per particle per temperature
    num_integration_steps=8,      # HMC leapfrog steps; ignored for MALA
    target_ess=0.5,               # ESS fraction adaptive tempering targets per lambda increment
    step_size=None,               # None = auto-scale from the target width (see above)
    whiten_inflate=2.0,           # warm reference widening; also sets the auto step's target width
    max_smc_steps=200,            # hard cap on temperatures; a run that hits it is not converged
    batch_size=0,                 # >0 = blackjax lax.map batching, for peak GPU memory
    seed=42,
    initializer=None,             # defaults to InitializerPrior (see below)
    inverse_mass_matrix=None,     # the whitening covariance: None | array | Result | Samples
    auto_correlation_settings=AutoCorrelationsSettings(check_for_convergence=False),
    iterations_per_quick_update=None, iterations_per_full_update=None,
    number_of_cores=1, silence=False, session=None,
)

__identifier_fields__ = ("num_particles", "kernel", "num_mcmc_steps", "num_integration_steps", "target_ess", "inverse_mass_matrix").

Two deliberate departures from af.BlackJAXNUTS, both because they would otherwise fail silently:

  • The default initializer is InitializerPrior, not InitializerBall. Cold SMC's log_evidence is only valid when the initial particles are drawn from the prior; the AbstractMCMC ball default would invalidate it without any visible symptom. A warning fires if a cold run is given a non-prior initializer (and if a warm run is left on the prior default, which would centre the reference on a random prior draw).
  • The "diagonal" / "dense" strings are rejected. They name an adaptation strategy; SMC does not adapt its metric, so accepting them would silently give a cold, prior-whitened run.

New samples class: SamplesSMC(SamplesPDF) — SMC particles are weighted, so this subclasses SamplesPDF (weight-driven PDF/medians/errors) rather than SamplesMCMC (unweighted chain draws, auto-correlation diagnostics). Adds log_evidence, lambda_list, acceptance_rate_list, ess_list, converged.

Nothing existing changes. No signature, default or behaviour of any current class is touched; the only edits outside the new package are one _LAZY_ATTRS entry and the docs autosummary.

af.SMC requires an Analysis built with use_jax=True (its kernel is gradient-based) and raises a clear error otherwise, exactly as af.BlackJAXNUTS does.

Files

  • autofit/non_linear/search/mcmc/blackjax/smc/{__init__.py,search.py,samples.py} — new.
  • autofit/__init__.py — "SMC" added to _LAZY_ATTRS.
  • docs/api/searches.rst — SMC and BlackJAXNUTS added to the MCMC autosummary (BlackJAXNUTS was missing).
  • test_autofit/non_linear/search/mcmc/test_blackjax_smc.py — new, 31 tests.

Testing

test_autofit/non_linear/search/mcmc/test_blackjax_smc.py — 31 tests, ~20 s. Construction, identifier, test-mode and whitening/step/evidence-bookkeeping tests are pure numpy; the end-to-end tests are gated by the same requires_blackjax skipif test_blackjax_nuts.py uses, so the no-extras Python-version matrix leg stays green.

The evidence tests assert against a closed form: a zero-centred isotropic Gaussian likelihood under Uniform(-5, 5) priors has log Z = 0.5·d·log(2π) + d·log σ − d·log(2L) = −2.7673 for d=2, σ=1, L=5. Measured (1000 particles, num_mcmc_steps=10, target_ess=0.8, seed 1):

arm recovered log Z Δ from analytic acceptance trace
cold (prior-whitened) −2.8493 −0.082 0.88 → 0.96
warm (bridge + Jacobian) −2.7869 −0.020 0.80 → 0.24
HMC warm −2.7532 +0.014 0.96 → 0.96

All three inside the 0.1-nat bar, and the HMC arm reproduces the phase-0 finding that HMC holds acceptance where MALA's decays.

Full suite: 2336 passed, 3 skipped (python -m pytest test_autofit/).

Deviation from the wave plan

The plan listed a config/non_linear/mcmc/SMC.yaml defaults file plus a search.yaml entry. That layout no longer exists: PyAutoFit #1202 ("replace YAML config with explicit Python defaults in search classes") removed it, and BlackJAXNUTS carries no YAML either. Defaults are explicit Python arguments, mirroring the sibling search.

Release-notes content for this feature is the ## API Changes section above (PyAutoFit has no in-repo notes file).

Not in scope

Per-temperature step adaptation (measured to collapse acceptance — fix-or-drop is its own task), a pixelized-likelihood arm (gradient-uncertified), and the autolens_profiling SMC cell / A100 probe (Wave B, gated on this merging).

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoFQxXV9W59icpEyiGL4eG

…inner kernel

Ports the validated gradient-SMC prototype (autolens_workspace_developer branch
feature/blackjax-smc-gradient-kernel) into PyAutoFit as a first-class search,
templated on the sibling blackjax/nuts/search.py and reusing blackjax/chains.py.

af.SMC wraps blackjax.adaptive_tempered_smc with a MALA (default) or HMC inner
kernel, sampling in a whitened space and recovering the log evidence for free
from the tempering increments. The three measured fixes that made the prototype
sample are carried over: full-covariance Cholesky whitening from a warm start
(prior-whitening does not whiten the posterior — 269x anisotropy), a step scaled
to the posterior width rather than the inflated reference width, and MALA's
squared-length step_size units. There is deliberately no per-temperature kernel
adaptation — blackjax's inner_kernel_tuning was measured to collapse acceptance.

Warm starting keeps log Z valid by tempering from a normalised Gaussian
reference rather than dropping particles at the previous best fit: lambda still
starts at 0, and the bridge (logprior_fn := log g, loglikelihood_fn := log prior
+ log L - log g) plus the whitening Jacobian returns the true evidence.

The lambda schedule, per-step acceptance and ESS are persisted to
search_internal and surfaced on SamplesSMC, because "tempering reached lambda=1"
is a weak criterion an acceptance-collapsed run can satisfy with garbage log Z.

Closes #1544.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoFQxXV9W59icpEyiGL4eG
@Jammy2211 Jammy2211 added the pending-release PR queued for the next release build label Aug 29, 2026
@Jammy2211
Jammy2211 merged commit b70cf7f into main Aug 29, 2026
4 checks passed
@Jammy2211
Jammy2211 deleted the feature/blackjax-smc-search branch August 29, 2026 20:33
@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.

af.SMC: blackjax adaptive tempered SMC search

1 participant