Skip to content

Bayesian Inference and Samplers

Amadeus edited this page Dec 1, 2026 · 4 revisions

Bayesian Inference & Native Samplers (v1.0.0)

Back to Home · Previous: SBI & Batch Pipeline · Next: Multi-Probe, Fisher & Topology

21cmCU includes a zero-external-dependency compiled C99 inference engine (src/py21cmfast/src/inference_samplers.c) coupled directly to Likelihood21cm and multi-GPU warm worker pools (BatchPool), plus optional dispatchers for UltraNest, emcee, and 21CMMC.


1. Priors & Likelihood21cm

Defining Priors (ParameterPrior & PriorTransform)

import py21cmcu as p21

prior = p21.PriorTransform(
    [
        p21.ParameterPrior("F_STAR10_ACG", kind="uniform", low=-2.5, high=-0.5),
        p21.ParameterPrior("F_ESC10_ACG", kind="uniform", low=-2.0, high=-0.4),
        p21.ParameterPrior("KP_h_Mpc", kind="log_uniform", low=1.0, high=30.0),
    ]
)

# Or quickly from uniform bounds dict:
uniform_prior = p21.PriorTransform.from_bounds(
    {"F_STAR10_ACG": (-2.0, -0.6), "F_ESC10_ACG": (-2.0, -0.4)}
)

Supported prior shapes: "uniform", "log_uniform", and "normal" (mean, std).

Physical Likelihood (Likelihood21cm)

Likelihood21cm supports both coeval and lightcone forward models and accepts either scalar (ndim,) or vectorized batch (n_batch, ndim) parameter inputs:

import numpy as np
import py21cmcu as p21

base_inputs = p21.InputParameters.from_template(
    "simple", random_seed=42, DIM=128, HII_DIM=64, BOX_LEN=128.0
)

ll = p21.Likelihood21cm(
    base_inputs=base_inputs,
    param_names=("F_STAR10_ACG", "F_ESC10_ACG"),
    data_pk=data_pk,
    sigma_pk=sigma_pk,          # OR pass covariance=... OR cov_inv=...
    mode="coeval",              # or "lightcone"
    out_redshift=8.0,           # recommended explicit target when node_redshifts has >1 entry
    ps_n_bins=12,
    wedge_filter=True,          # supported in both coeval and lightcone modes
    wedge_buffer=0.05,
    model_error_frac=0.2,       # optional fractional modeling uncertainty in quadrature
    cuda_mode="fast",
    use_cuda=True,
    devices=(0,),
    workers_per_gpu=1,
)

Numerical Safeguards Built into Likelihood21cm

  1. Consistent coeval redshift resolution: simulate() and simulate_batch() share unified _resolve_coeval_redshift logic so single-point checks and batched sampler draws select identical redshift slices (always set explicit out_redshift=... when base_inputs.node_redshifts contains multiple redshifts).
  2. Lightcone wedge filtering: When mode="lightcone" and wedge_filter=True, Likelihood21cm applies apply_wedge_filter_3d prior to computing the 1D power spectrum.
  3. Fixed observation mask & strict NaN rejection: Observed bins are fixed at initialization (_obs_mask). If the physical model returns NaN/inf in any required observed bin, log_likelihood returns -inf rather than dropping the bin and inflating $\log \mathcal{L}$.
  4. Marginalized precision (cov_inv) with missing bins: When data_pk contains masked/NaN bins alongside a full precision matrix cov_inv, Likelihood21cm performs exact Schur-complement marginalization (P_oo - P_om P_mm^-1 P_mo) with scale-invariant block detection (scale * 1e-14), matching passing the sub-selected covariance matrix.
  5. Full Gaussian normalization with model_error_frac > 0: Because fractional modeling error $\sigma_{\mathrm{model}, i} = f \cdot |m_i(\theta)|$ depends on $\theta$, the likelihood includes $-\sum \log \sigma_{\mathrm{eff},i}$ (or $-\frac{1}{2}\log|\Sigma_{\mathrm{eff}}|$) so Bayesian model evidence and parameter comparison remain normalized.

2. Multi-Probe JointLikelihood & Planck $\tau_e$

Combine 21cm power-spectrum likelihoods with CMB Thomson optical depth $\tau_e$ (compute_tau_e) or external probes using JointLikelihood with optional weights and automatic -inf short-circuiting:

def tau_e_loglike(theta_batch: np.ndarray) -> np.ndarray:
    # Wrap reionization history (redshifts, xHI) -> compute_tau_e(...)
    tau_pred = compute_predicted_tau(theta_batch)
    return -0.5 * ((tau_pred - 0.0544) / 0.0073) ** 2

joint = p21.JointLikelihood(
    {"ps21": ll, "planck_tau_e": tau_e_loglike},
    weights={"ps21": 1.0, "planck_tau_e": 1.0},
    short_circuit=True,   # skips expensive downstream probes if ps21 returns -inf
)

3. Native C99 Nested Sampling (run_nested_sampling)

NativeNestedSampler / run_nested_sampling implements multi-ellipsoid clustering (k-means + covariance bounding) and differential hit-and-run slice proposals in C99 (inference_samplers.c, compiled with -O3 -ffast-math -fno-finite-math-only to preserve ±inf/NaN semantics) with warm BatchPool GPU evaluation:

from pathlib import Path
import py21cmcu as p21

ns_res = p21.run_nested_sampling(
    log_likelihood=joint,
    prior=prior,
    n_live=200,
    batch_size=32,
    dlogz=0.1,
    max_clusters=4,
    slice_fraction=0.5,
    devices=(0,),
    workers_per_gpu=1,
    checkpoint_path=Path("native_ns_ckpt.h5"),
    checkpoint_every=50,
    resume=True,
    model_id="21cm_tau_v1",   # required when resuming non-Likelihood21cm custom callables
)
print(ns_res.summary())
ns_res.save_h5("posterior_ns.h5")   # or ns_res.save_npz("posterior_ns.npz")

Safety features in v1.0.0–v1.1.0:

  • Plateau bulk-eviction: Flat prior plateaus (such as wide -inf hard boundaries or tied likelihood values) are evicted and replenished consistently under variable $N_{\mathrm{live}}$ quadrature so evidence $\log Z$ does not overestimate invalid volume.
  • Provenance-verified HDF5 resume: Likelihood21cm (and all-Likelihood21cm JointLikelihood) automatically hashes full simulation + data/covariance configuration; custom Python callables (such as surrogate wrappers or custom JointLikelihood probes) must pass a matching explicit model_id="..." (or JointLikelihood(..., model_id="...")) when resuming with resume=True, or a ValueError is raised rather than reusing stale checkpoints. Matching runs additionally re-evaluate up to 32 stratified probe points before resuming.

4. Native C99 Ensemble MCMC (run_native_mcmc)

NativeEnsembleMCMC / run_native_mcmc runs independent walker ensembles alternating Goodman–Weare Stretch moves and Differential Evolution (DE-MC) updates in C99, returning a NestedSamplingResult with full convergence diagnostics:

mcmc_res = p21.run_native_mcmc(
    log_likelihood=joint,
    prior=prior,
    n_walkers=32,
    n_steps=400,
    burnin=100,
    thin=1,
    n_ensembles=2,      # >= 2 ensembles enables split-Rhat across ensembles & halves
    stretch_a=2.0,
    de_prob=0.5,
    checkpoint_path=Path("native_mcmc_ckpt.h5"),
    resume=True,
    model_id="21cm_tau_v1",   # required when resuming custom callables
)

print(mcmc_res.summary())
print(
    "diagnostics_ok:", mcmc_res.metadata["diagnostics_ok"],
    "| max_rhat:", mcmc_res.metadata["max_rhat"],
    "| min_N/IAT:", mcmc_res.metadata["min_n_over_iat"],
    "| ESS:", mcmc_res.ess,
)

Built-in diagnostics (inference_samplers.c):

  • Autocorrelation-adjusted ESS: Effective Sample Size accounts for Sokal Integrated Autocorrelation Time ($\mathrm{ESS} = N_{\mathrm{samples}} / \max \tau_{\mathrm{int}}$) rather than raw sample count.
  • Zero-variance stuck-chain detection: If acceptance collapses and chains sit motionless (v_max - v_min within 1-ULP tolerance), split-$\widehat{R}$ and IAT report NaN/inf, ess = 0.0, and metadata["diagnostics_ok"] = False instead of falsely claiming convergence.

5. Unified Dispatcher (run_21cmmc) & Terminal CLI (21cmcu infer)

Switch between backends (native_ns, native_mcmc, ultranest, emcee, 21cmmc) with one API:

res = p21.run_21cmmc(
    base_inputs=base_inputs,
    param_names=("F_STAR10_ACG", "F_ESC10_ACG"),
    prior={"F_STAR10_ACG": (-2.0, -0.6), "F_ESC10_ACG": (-2.0, -0.4)},
    data_pk=data_pk,
    sigma_pk=sigma_pk,
    backend="native_ns",     # or "native_mcmc", "ultranest", "emcee", "21cmmc"
    mode="coeval",
    out_redshift=8.0,
    ps_n_bins=12,
    devices=(0,),
    batch_size=16,
    min_num_live_points=200,
    dlogz=0.2,
    use_cuda=True,
)

Or run directly from the shell via 21cmcu infer (input .npz containing data_pk and optional sigma_pk or cov_inv):

21cmcu infer obs_pk.npz \
  --bounds '{"F_STAR10_ACG": [-2.0, -0.6], "F_ESC10_ACG": [-2.0, -0.4]}' \
  --backend native_ns \
  --mode coeval \
  --dim 128 --hii-dim 64 --box-len 128.0 --out-redshift 8.0 \
  --devices 0 --workers-per-gpu 1 --batch-size 16 \
  --n-live 200 --dlogz 0.2 --model-error-frac 0.2 \
  --checkpoint infer_ckpt.h5 --resume \
  --out posterior_ns.h5

For MCMC from CLI, pass --backend native_mcmc --n-walkers 32 --n-steps 400 --burnin 100.


6. Posterior Surrogate Audits & Blind PCA Foreground Removal

Auditing Emulator Posteriors Against Native GPU Physics (audit_posterior_native)

Verify posterior samples generated by a fast surrogate or neural emulator by evaluating an equal-weight posterior subsample through Likelihood21cm.simulate_batch:

audit = p21.audit_posterior_native(
    ns_res,
    likelihood=ll,
    surrogate_predict=my_emulator_predict,   # (n_draws, ndim) -> (n_draws, n_k)
    n_draws=16,
)
print(
    f"valid_rms_z={audit.valid_rms_zscore:.3f}, "
    f"p90_L2={audit.l2_p90:.3f}, "
    f"failure_rate={audit.failure_rate:.1%} ({audit.n_failed_draws}/{audit.n_draws})"
)

The default selection="posterior" draws from ns_res.samples, the equal-weight posterior sample. Use selection="likelihood_range" with a nested result to recover the previous spread over log-likelihood ranks. In that mode, the RMS, percentiles, and failure rate summarize coverage draws, not posterior probability. The result records its selection.

audit_posterior_native evaluates over the fixed observation mask (required_mask) and reports n_failed_draws, failure_rate, and bin_failure_rate separately whenever native draws return NaN/inf, rather than treating failed predictions as zero error.

Blind PCA Foreground Removal (remove_foreground_pca_3d)

Project out the top spectrally smooth eigenmodes along the line-of-sight axis before computing power spectra or feeding SBI networks:

diag = p21.remove_foreground_pca_3d(
    tb_cube, n_modes=3, los_axis=2, return_diagnostics=True
)
cleaned_cube = diag["cleaned"]
explained = diag["explained_variance_ratio"]

See the complete runnable example in examples/10_ultranest_and_21cmmc_inference.py.


7. Multi-Redshift UV Luminosity Function Likelihood (UVLFLikelihood)

Jointly constrain galaxy star-formation efficiency alongside 21cm power spectra by evaluating 21cmFAST's native ComputeLF UV luminosity function across redshifts inside UVLFLikelihood:

ll_uv = p21.UVLFLikelihood(
    base_inputs=base_inputs,
    param_names=["F_STAR10_ACG", "F_ESC10_ACG"],
    redshifts=[6.0, 8.0, 10.0],
    m_uv_obs=muv_grid,             # shape (n_z, n_mag)
    log10_phi_obs=log10_phi_grid,  # shape (n_z, n_mag)
    sigma_log10_phi=0.15,
    component="both",              # "both", "acg", or "mcg"
    model_error_frac=0.05,         # includes -sum log(sigma_eff) normalization
)

joint = p21.JointLikelihood(
    components={"21cm": ll_21cm, "uvlf": ll_uv},
    weights={"21cm": 1.0, "uvlf": 1.0},
)

UVLFLikelihood shares Likelihood21cm's deterministic SHA-256 checkpoint provenance: modifying observed magnitudes, errors, redshifts, or component causes resume=True to reject stale checkpoints.


8. Closed-Loop Active SBI (select_active_sbi_points & ActiveSBILoop)

Pair SBISimulator with sequential posterior-density, ensemble epistemic uncertainty, max-entropy, or hybrid acquisition functions while reducing cosmic variance via fixed_paired_initial_conditions:

# Generate variance-reduced Fixed-and-Paired initial conditions (Angulo & Pontzen 2016)
ic_plus, ic_minus = p21.fixed_paired_initial_conditions(
    dim=128, hii_dim=64, box_len=200.0, seed=42, fix_amplitude=True, paired=True
)

# Run active simulation rounds with diverse candidate acquisition
loop = p21.ActiveSBILoop(
    sbi_sim,
    param_bounds={"F_STAR10_ACG": (-2.0, -0.5), "F_ESC10_ACG": (-2.0, -0.3)},
    acquisition="hybrid",          # "posterior_density", "ensemble_std", "max_entropy", "hybrid"
    n_init=64,
    n_per_round=32,
    n_candidates=1024,
    diversity_weight=0.25,
)
steps = loop.run(n_rounds=3, train_fn=train_posterior_or_ensemble, x_obs=obs_summary)
print(steps[-1].n_total, steps[-1].wall_s)

Each round returns an ActiveSBIStepResult containing selected_theta, selected_x, scores, total_theta, and total_x.

Clone this wiki locally