Repository navigation
feat: af.SMC — blackjax adaptive tempered SMC search - #1546
Merged
Merged
Conversation
…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
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.
Closes #1544. Rung 2 of the overflow-flood fix wave — the
af.SMClibrary half, which theautolens_profilingSMC cell and the A100 probe (Wave B) depend on.Ports the validated gradient-SMC prototype (
autolens_workspace_developerbranchfeature/blackjax-smc-gradient-kernel,searches_minimal/blackjax_smc_grad.py+smc_gradient_findings.md) into the library, templated on the siblingblackjax/nuts/search.pyand reusingblackjax/chains.py.What this adds
af.SMCwrapsblackjax.adaptive_tempered_smcwith a gradient inner kernel — MALA by default, HMC optionally — sampling in a whitened space and recoveringlog Zfor 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:
inverse_mass_matrixaccepts aResult/Samples/array and is resolved through the existingchains.resolve_inverse_mass_matrix.whiten_inflateso it covers the posterior, so scaling to the reference's own width overshoots bywhiten_inflate^2(measured:eps=1.148 -> acc 0.00,eps=0.1 -> acc 0.94).step_sizeis a squared length. The auto-scaling appliesell = 2.38 * d^(-1/6) * sigma,eps = ell^2 / 2, andsigma * d^(-1/4)for HMC.There is deliberately no per-temperature kernel adaptation:
blackjax.smc.inner_kernel_tuningwas 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 shortcutlambda: it still starts at 0, but from a normalised Gaussian referencegcentred on the warm-start point, bridged aslogprior_fn := log g,loglikelihood_fn := log prior + log L - log g, withlog|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 garbagelog Z, so the lambda schedule, per-step acceptance and realised ESS are persisted tosearch_internaland surfaced onSamplesSMCaslambda_list/acceptance_rate_list/ess_list.API Changes
New public class:
af.SMC(lazily exported via_LAZY_ATTRS, likeaf.NSS; nothing at import time pulls jax or blackjax).__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:InitializerPrior, notInitializerBall. Cold SMC'slog_evidenceis only valid when the initial particles are drawn from the prior; theAbstractMCMCball 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)."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 subclassesSamplesPDF(weight-driven PDF/medians/errors) rather thanSamplesMCMC(unweighted chain draws, auto-correlation diagnostics). Addslog_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_ATTRSentry and the docs autosummary.af.SMCrequires anAnalysisbuilt withuse_jax=True(its kernel is gradient-based) and raises a clear error otherwise, exactly asaf.BlackJAXNUTSdoes.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—SMCandBlackJAXNUTSadded to the MCMC autosummary (BlackJAXNUTSwas 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 samerequires_blackjaxskipiftest_blackjax_nuts.pyuses, 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 haslog 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):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.yamldefaults file plus asearch.yamlentry. That layout no longer exists: PyAutoFit #1202 ("replace YAML config with explicit Python defaults in search classes") removed it, andBlackJAXNUTScarries no YAML either. Defaults are explicit Python arguments, mirroring the sibling search.Release-notes content for this feature is the
## API Changessection 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_profilingSMC cell / A100 probe (Wave B, gated on this merging).🤖 Generated with Claude Code
https://claude.ai/code/session_01LoFQxXV9W59icpEyiGL4eG