Check a native Bayesian sampler
The current example uses Rust’s bayesian_metropolis_chains operation through
execute. It replaces the earlier
NumpyroFitter tutorial. Its purpose is to check a sampler against a known
answer before considering a less tractable scientific model.
Learning outcomes
Section titled “Learning outcomes”You will derive the target mean and variance for one bounded parameter, run four chains from dispersed starts, and distinguish stored draws from effective sample size. You will explain why good diagnostic values and agreement in one fixture do not prove convergence or validate an empirical likelihood.
Prerequisites
Section titled “Prerequisites”Use the native development installation. The example needs the installed package and Python’s standard library, with no external dataset or network access. Basic familiarity with a Normal likelihood, a Normal prior and variance is helpful.
Only the Logistic asymptote L is unknown. The slope k = 0.5 and midpoint
x0 = 2 are fixed. The single synthetic observation is y = 50 at t = 2,
where the model gives y = L / 2. The observation noise standard deviation is
one and the prior for L has mean 96 and standard deviation two. Support is
restricted to [80, 120].
Run the checked file from the repository root:
.venv-native/bin/python -I examples/native_bayesian.py"""Check a bounded four-chain sampler against an independent Gaussian posterior."""
import jsonfrom math import isfinitefrom statistics import mean, variance
from innovate import execute
def main() -> None: """Check support, draws, diagnostics and a predeclared Monte Carlo tolerance.""" result = execute( "bayesian_metropolis_chains", forecast_model="logistic", parameter="L", bounds=[80, 120], proposal_step=4, gaussian_priors={"L": {"mean": 96, "sd": 2}}, noise_sd=1, observed=[50], prediction={"inputs": {"time": [2]}, "parameters": {"k": 0.5, "x0": 2}}, draws=4000, warmup=1000, chains=[ {"seed": 41, "initial": {"L": 83}}, {"seed": 42, "initial": {"L": 94}}, {"seed": 43, "initial": {"L": 106}}, {"seed": 44, "initial": {"L": 118}}, ], )["result"] chains = result["chains"] assert len(chains) == 4 assert [chain["seed"] for chain in chains] == [41, 42, 43, 44] for chain in chains: assert chain["draws"] == 4000 and chain["warmup"] == 1000 assert len(chain["samples"]) == 4000 assert 0 < chain["acceptance_rate"] < 1 samples = [sample for chain in chains for sample in chain["samples"]] assert all(isfinite(sample) and 80 <= sample <= 120 for sample in samples)
# At the midpoint, y=L/2. Combining N(96, 4) with y=50, noise variance 1, # gives N(98, 2), truncated to [80, 120]. Both bounds exceed 12 SD from 98; # truncation is negligible at the declared tolerances, not mathematically absent. # These fixed tolerances check a seeded fixture; they are not interval coverage. assert abs(mean(samples) - 98.0) < 0.2 assert abs(variance(samples) - 2.0) < 0.3 assert len(result["diagnostics"]) == 1 diagnostic = result["diagnostics"][0] assert diagnostic["parameter"] == "L" assert diagnostic["effective_sample_size"]["draws_used"] == 16000 rhat = diagnostic["split_rhat"]["rhat"] assert isfinite(rhat) and 0 < rhat < 1.05 for name in ("bulk_ess", "tail_ess"): effective_samples = diagnostic["effective_sample_size"][name] assert isfinite(effective_samples) and effective_samples > 1000 # Diagnostic thresholds are warning criteria, not proof of convergence. print(json.dumps({"chains": len(chains), "draws": len(samples), "posterior_oracle_passed": True}, sort_keys=True))
if __name__ == "__main__": main()Four chains start at 83, 94, 106 and 118 using distinct explicit seeds. Each uses 1000 warmup iterations and retains 4000 draws. The script checks every sample against the support, checks the declared posterior-moment tolerances, and requires finite diagnostic values within the fixture’s bounds.
Expected results
Section titled “Expected results”The successful run prints this exact contract output:
{"chains": 4, "draws": 16000, "posterior_oracle_passed": true}The 16,000 stored draws are the combined retained samples from four chains. They are not 16,000 independent observations. A failed assertion should trigger investigation of the sampled target, initialization, implementation and Monte Carlo behavior; changing the expected value to match a run would remove the independent check.
Interpretation
Section titled “Interpretation”At the midpoint, observing 50 with noise variance one supplies a likelihood
for L centered at 100 with variance four. The prior also has variance four,
centered at 96. Adding their precisions gives posterior variance
1 / (1/4 + 1/4) = 2; the precision-weighted posterior mean is 98. The finite
support truncates this Normal distribution. Both boundaries are more than
12 posterior standard deviations from the mean, so truncation is negligible at
the declared tolerances, though it is not mathematically absent.
The script allows absolute deviations below 0.2 for the sample mean and 0.3 for
the sample variance. It also checks rank-normalized split R-hat below 1.05 and
bulk and tail effective sample sizes above 1000. These are fixture regression
bounds, not an empirical analysis acceptance policy. The diagnostic framework
and its limits are discussed by
Vehtari and colleagues, with
the authors’ code and supplementary examples.
For a new analysis,
Section 2 of the author manuscript
recommends at least four chains and R-hat < 1.01 as a first-level check.
Assess Monte Carlo error for the particular quantities and precision you need.
Reader task: why is the posterior mean 98 rather than the likelihood’s 100? The prior and likelihood have equal precision in this case, so the mean is their average. If the prior standard deviation were changed, the independent target calculation and tolerances would need deliberate review before changing the checked fixture.
Limitations
Section titled “Limitations”One observation cannot identify L, k and x0 jointly in this example; the
last two are deliberately fixed. The case does not test a hierarchical model,
multimodal posterior, empirical prior, calibrated credible-interval coverage or
an appropriate observation model for real adoption counts.
A favorable R-hat or effective sample size is a diagnostic observation, not proof that all posterior regions were explored. The posterior oracle strengthens this specific test but does not establish general sampler adequacy. Use the native capability guide for supported Bayesian operations and the scientific qualification work that remains open.