Algorithm Search⌘K

Algorithmresearch

Simulation-based calibration

Also called SBC.

Checks a Bayesian sampler by drawing parameters from the prior, simulating data, and testing that the rank of the true parameter among posterior draws is uniform.

Time
Θ(N (S + C + L)) worst
Space
Θ(L) extra
Where
C = the cost of one run of the sampler under test; L = the number of posterior draws per replication; N = the number of replications; S = the cost of one simulation of data
Properties
randomizednot exactofflineiterative
Origin
Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari, Andrew Gelman, Samantha R. Cook, Donald B. Rubin, 2018

Simulation-based calibration (SBC) checks that a Bayesian computation is correct, using only the ability to sample from the prior and to simulate data. It repeats one experiment NN times: draw a parameter θ~\tilde\theta from the prior, simulate data y~\tilde y from it, run the method under test on y~\tilde y to get LL posterior draws, and record the rank of f(θ~)f(\tilde\theta) among the LL values f(θl)f(\theta_l) for a chosen function ff. Given y~\tilde y, the true parameter is itself a draw from the exact posterior, so if the method returns independent exact posterior draws, the rank is uniform on {0,1,…,L}\{0, 1, \ldots, L\}. A histogram of the NN ranks that is not flat shows an error, and its shape shows which kind: a U shape for posteriors that are too narrow, a hump for posteriors that are too wide, and a slope for a bias.

In plain words

You have a program that claims to compute the answer to a Bayesian question, and you want to know whether it is right without knowing the right answer. Make up a true value the way the model says values arise, make fake data from it, and ask the program for a sample of plausible values. If the program is right, the true value looks like just one more member of that sample. So it is equally likely to land at any position when you sort the sample: lowest, highest, or anywhere between. Repeat this many times and count the positions. A flat count is what a correct program gives. Too many lowest and highest positions mean the program is too sure of itself; too few mean it is not sure enough; a lean to one side means it is biased.

The problem

Input. A prior π(θ)\pi(\theta) to draw from; a simulator of data y∼p(y∣θ)y \sim p(y \mid \theta); the method under test, which given data yy returns LL draws meant to come from the posterior π(θ∣y)\pi(\theta \mid y); a real function ff of the parameter, such as one coordinate; the number of replications NN.

Output. The counts of the ranks 0,…,L0, \ldots, L over the NN replications, and a test of their uniformity.

What the test can show. Uniform ranks are necessary for a correct method, not sufficient. They test that the computed posterior is calibrated on average over the prior and the data, not that it is right for every data set.

The algorithm

  1. SBC(π, SIMULATE, SAMPLER, f, N, L)
  2. 1counts[0..L] ← 0
  3. 2for n ← 1 to N
  4. 3θ̃ ← a draw from the prior π
  5. 4ỹ ← SIMULATE(θ̃)
  6. 5θ₁..θ_L ← SAMPLER(ỹ, L) ▷ the method under test
  7. 6r ← #{l : f(θ_l) < f(θ̃)} + U{0..#{l : f(θ_l) = f(θ̃)}} ▷ ties broken at random
  8. 7counts[r] ← counts[r] + 1
  9. 8return counts ▷ uniform on 0..L if SAMPLER is correct

L3 and L4 draw (θ~,y~)(\tilde\theta, \tilde y) from the joint law of the model. The joint density π(θ)p(y∣θ)\pi(\theta)p(y \mid \theta) equals p(y)π(θ∣y)p(y)\pi(\theta \mid y), so y~\tilde y is a draw from the prior predictive law and, given y~\tilde y, θ~\tilde\theta is a draw from the exact posterior. L5 runs the method on y~\tilde y. L6 computes the rank. The term U{0..e}U\{0..e\}, a uniform integer up to the number ee of ties, matters only when f(θ)f(\theta) can take repeated values, for example with a discrete parameter. L8 returns the counts; the usual test is Pearson's chi-squared test against equal expected counts, often after merging the L+1L + 1 ranks into BB equal bins, together with a plot of the histogram.

Markov chain samplers. If L5 runs a Markov chain, its draws are correlated, and correlated draws give a U-shaped histogram even when the chain targets the right law. Talts and coauthors (2018) run a longer chain and keep every TT-th state, with TT the chain length divided by its effective sample size, so that about LL nearly independent draws remain.

Example

Model. θ∼N(0,1)\theta \sim N(0, 1) and y1,…,y5∼N(θ,1)y_1, \ldots, y_5 \sim N(\theta, 1), so the posterior is N(∑yi/6,1/6)N(\sum y_i/6, 1/6), with standard deviation 0.4080.408. The function is f(θ)=θf(\theta) = \theta.

Trace. Six replications with L=4L = 4 exact posterior draws, from random.Random(3):

nn θ~\tilde\theta posterior mean the 4 draws, sorted rank
1 0.095 0.211 0.193, 0.275, 0.508, 0.986 0
2 1.127 0.735 0.071, 0.120, 0.192, 0.638 4
3 −0.172-0.172 −0.382-0.382 −1.204-1.204, −0.727-0.727, −0.545-0.545, −0.075-0.075 3
4 −0.504-0.504 −1.073-1.073 −1.200-1.200, −0.939-0.939, −0.885-0.885, −0.857-0.857 4
5 1.045 0.461 −0.302-0.302, 0.015, 0.141, 0.898 4
6 −0.953-0.953 −1.362-1.362 −2.173-2.173, −1.661-1.661, −0.925-0.925, −0.686-0.686 2

Each rank is between 00 (the truth is below all draws) and 44 (above all). Six ranks say little; uniformity shows only over many replications.

Correct and wrong samplers. N=1000N = 1000 replications with L=20L = 20 draws, from random.Random(7). The 2121 ranks are merged into 77 bins of 33; a flat histogram has 142.9142.9 per bin. The pp-value is from the chi-squared test on all 2121 ranks (2020 degrees of freedom).

sampler counts in 7 bins pp-value shape
exact posterior 140, 147, 139, 160, 122, 150, 142 0.69 flat
standard deviation ×0.6\times 0.6 254, 111, 85, 100, 104, 99, 247 3×10−793 \times 10^{-79} U
standard deviation ×1.5\times 1.5 66, 134, 190, 228, 175, 148, 59 2×10−282 \times 10^{-28} hump
mean +0.5+ 0.5 standard deviations 277, 187, 175, 112, 101, 89, 59 4×10−464 \times 10^{-46} falling
the prior, ignoring the data 147, 142, 135, 155, 135, 141, 145 0.25 flat
exact Markov chain, ρ=0.9\rho = 0.9 292, 90, 119, 76, 82, 81, 260 3×10−1903 \times 10^{-190} U
the same chain, every 19th state 149, 128, 140, 154, 149, 127, 153 0.41 flat

When the draws are too narrow, the truth often falls outside them, so ranks 00 and 2020 are common. When they are too wide, the truth sits in their middle. When they are shifted up, the truth tends to be below them. The prior sampler passes, although it ignores the data: the truth and the draws are then independent draws from the prior, so the rank is uniform. The Markov chain has the exact posterior as its stationary law, and its first state is an exact draw, but with lag-one correlation 0.90.9 its 2020 consecutive states cluster, and the truth falls outside the cluster too often. The effective sample size of such a chain is n(1−ρ)/(1+ρ)=n/19n(1 - \rho)/(1 + \rho) = n/19, so keeping every 1919th state of a chain of length 380380 restores a flat histogram.

Correctness

The full proof is in proofs/correctness.md. It proves:

  1. The truth is a posterior draw. Given y~\tilde y, θ~\tilde\theta has the law π(θ∣y~)\pi(\theta \mid \tilde y), by Bayes' theorem.
  2. Uniform ranks. If the method returns LL independent draws from the exact posterior and f(θ)f(\theta) has no atoms, the rank is uniform on {0,…,L}\{0, \ldots, L\}. The L+1L + 1 values are exchangeable given y~\tilde y, so the truth is equally likely to hold each position.
  3. Ties. With random tie breaking, as in L6, the rank is uniform with no condition on atoms; the plain count of smaller values is not, since rank 00 is then too likely.
  4. What is tested. With a continuous computed posterior distribution function GyG_y, the rank is binomial(L,u)(L, u) given u=Gy~(f(θ~))u = G_{\tilde y}(f(\tilde\theta)), and the ranks are uniform for every LL exactly when uu is Uniform(0, 1). This explains the shapes and why the prior sampler passes.

What is proved and what is only measured: claims 1 to 4 are exact, and the tests check claim 3 and the prior sampler in exact rational arithmetic on discrete models. The chi-squared law of the test statistic is a large-sample approximation. With Markov chain draws none of the claims apply; the effect of thinning in the table is measured only.

A correction. Theorem 1 of Talts and coauthors (2018) states uniformity of the plain rank for any one-dimensional function. It needs the condition of claim 2: a constant ff, or a discrete parameter, gives ties, and the plain rank is then not uniform. The randomized rank of L6 removes the condition.

Proof: Uniform ranks under a correct sampler, with ties, and what uniformity testsfull

Setting. A prior π(θ)\pi(\theta) and a model p(y∣θ)p(y \mid \theta) define the joint law π(θ)p(y∣θ)\pi(\theta)p(y \mid \theta) of (θ,y)(\theta, y), with marginal p(y)p(y) and posterior π(θ∣y)\pi(\theta \mid y). One replication of SBC draws θ~∼π\tilde\theta \sim \pi, then y~∼p(⋅∣θ~)\tilde y \sim p(\cdot \mid \tilde\theta), then θ1,…,θL\theta_1, \ldots, \theta_L from the sampler under test given y~\tilde y. A real function ff of the parameter is fixed. Write f~=f(θ~)\tilde f = f(\tilde\theta) and fl=f(θl)f_l = f(\theta_l). The plain rank is R0=#{l:fl<f~}R_0 = \#\{l : f_l < \tilde f\}; the randomized rank of L6 is

R=#{l:fl<f~}+U,U uniform on {0,1,…,#{l:fl=f~}},R = \#\{l : f_l < \tilde f\} + U, \qquad U \text{ uniform on } \{0, 1, \ldots, \#\{l : f_l = \tilde f\}\},

with UU drawn independently given the values.

Claim 1: the true parameter is a posterior draw given the data

Given y~=y\tilde y = y, θ~\tilde\theta has the law π(θ∣y)\pi(\theta \mid y).

Proof. The pair (θ~,y~)(\tilde\theta, \tilde y) has density π(θ)p(y∣θ)=p(y)π(θ∣y)\pi(\theta)p(y \mid \theta) = p(y)\pi(\theta \mid y) by Bayes' theorem, so the conditional density of θ~\tilde\theta given y~=y\tilde y = y is π(θ∣y)\pi(\theta \mid y). □\square

Claim 2: rank uniformity without ties

Suppose the sampler returns θ1,…,θL\theta_1, \ldots, \theta_L independent with law π(⋅∣y~)\pi(\cdot \mid \tilde y), independent of θ~\tilde\theta given y~\tilde y, and suppose that for almost every yy the law of f(θ)f(\theta) under π(⋅∣y)\pi(\cdot \mid y) has no atoms. Then P(R0=r)=1/(L+1)P(R_0 = r) = 1/(L+1) for r=0,…,Lr = 0, \ldots, L, and R=R0R = R_0 almost surely.

Proof. Fix y~=y\tilde y = y. By Claim 1 and the assumption, f~,f1,…,fL\tilde f, f_1, \ldots, f_L are L+1L + 1 independent values with the same atomless law, so they are distinct with probability one, and R=R0R = R_0. Write g0=f~g_0 = \tilde f and gl=flg_l = f_l, and let R(j)=#{l≠j:gl<gj}R^{(j)} = \#\{l \ne j : g_l < g_j\} be the rank of gjg_j among the others. The vector (g0,…,gL)(g_0, \ldots, g_L) is exchangeable, so swapping g0g_0 and gjg_j shows that R(j)R^{(j)} has the same law as R(0)=R0R^{(0)} = R_0. For distinct values, exactly one index has rank rr, so ∑j=0L1{R(j)=r}=1\sum_{j=0}^{L}\mathbf{1}\{R^{(j)} = r\} = 1. Taking expectations, (L+1)P(R0=r∣y~=y)=1(L + 1)P(R_0 = r \mid \tilde y = y) = 1. Averaging over yy gives the claim. □\square

Claim 3: randomized ranks are uniform even with ties

Under the sampler assumption of Claim 2, but with no condition on atoms, P(R=r)=1/(L+1)P(R = r) = 1/(L+1) for r=0,…,Lr = 0, \ldots, L. If ties have positive probability, the plain rank is not uniform: P(R0=0)>1/(L+1)P(R_0 = 0) > 1/(L+1) whenever P(f1=⋯=fL=f~)>0P(f_1 = \cdots = f_L = \tilde f) > 0.

Proof. Let V0,…,VLV_0, \ldots, V_L be independent Uniform(0, 1) values, independent of everything else, and order the pairs (gj,Vj)(g_j, V_j) lexicographically. Given y~\tilde y the pairs are independent and identically distributed, and they are distinct with probability one because the VjV_j are. The argument of Claim 2 shows that the lexicographic rank R′R' of (g0,V0)(g_0, V_0) is uniform on {0,…,L}\{0, \ldots, L\}. Now fix the values g0,…,gLg_0, \ldots, g_L. Let e=#{l≥1:gl=g0}e = \#\{l \ge 1 : g_l = g_0\}. Then R′=#{l:gl<g0}+#{l:gl=g0,Vl<V0}R' = \#\{l : g_l < g_0\} + \#\{l : g_l = g_0, V_l < V_0\}, and the second term is the rank of V0V_0 among e+1e + 1 independent uniform values, which is uniform on {0,…,e}\{0, \ldots, e\}. So given the values, R′R' and RR have the same law, hence the same unconditional law, which is uniform.

For the second part, R0≤RR_0 \le R always, so P(R0=0)≥P(R=0)=1/(L+1)P(R_0 = 0) \ge P(R = 0) = 1/(L+1), and on the event that all L+1L + 1 values are equal, R0=0R_0 = 0 while R=UR = U is positive with probability L/(L+1)L/(L+1). That event has positive probability, which makes the inequality strict. □\square

A correction to the usual statement. Talts and coauthors (2018, Theorem 1) state uniformity of the plain rank for any one-dimensional function. That needs the atomless condition of Claim 2: for a constant ff, the plain rank is 00 in every replication. With discrete parameters, or with a function such as an indicator, use the randomized rank of Claim 3.

Claim 4: what uniform ranks test

Let the sampler return, given y~=y\tilde y = y, independent draws θl\theta_l from some law q(⋅∣y)q(\cdot \mid y) such that the distribution function Gy(t)=q(f(θ)≤t∣y)G_y(t) = q(f(\theta) \le t \mid y) is continuous, and let u=Gy~(f~)u = G_{\tilde y}(\tilde f). Then

P(R=r)=(Lr)E[ur(1−u)L−r],r=0,…,L,P(R = r) = \binom{L}{r}\mathbb{E}\big[u^r(1 - u)^{L - r}\big], \qquad r = 0, \ldots, L,

and the rank is uniform on {0,…,L}\{0, \ldots, L\} for every LL if and only if uu is Uniform(0, 1).

Proof. Given y~\tilde y and θ~\tilde\theta, each flf_l is below f~\tilde f with probability uu, independently, and ties have probability zero because GyG_y is continuous. So RR is binomial(L,u)(L, u) given uu, which gives the formula. If uu is uniform, (Lr)∫01ur(1−u)L−r du=(Lr)r! (L−r)!(L+1)!=1L+1\binom{L}{r}\int_0^1 u^r(1-u)^{L-r}\, du = \binom{L}{r}\frac{r!\,(L-r)!}{(L+1)!} = \frac{1}{L+1}. Conversely, if the rank is uniform for every LL, then r=Lr = L gives E[uL]=1/(L+1)\mathbb{E}[u^L] = 1/(L+1) for all L≥1L \ge 1, which are the moments of Uniform(0, 1). A law on [0,1][0, 1] is determined by its moments, so uu is uniform. □\square

So SBC tests whether the value of the computed posterior distribution function at the true parameter, uu, is uniform. A correct sampler passes by Claim 1, since then uu is the probability integral transform of a draw from its own continuous law. A sampler whose posteriors are too narrow puts uu near 00 and 11, which gives a U-shaped rank histogram; one that is too wide puts uu near 1/21/2, which gives a hump; one that is shifted up makes uu small. A sampler that returns the prior for every yy also passes: then θ~\tilde\theta and the draws are independent draws from π\pi, and uu is uniform. Uniform ranks are therefore necessary for a correct sampler but not sufficient.

What is proved and what is measured

Claims 1 to 4 are exact; the tests check Claim 3 and the prior-sampler remark in exact rational arithmetic on discrete models. Two parts of the method are not proved here. The chi-squared test of the rank counts uses Pearson's approximation of the statistic by the chi-squared law with B−1B - 1 degrees of freedom, which holds as the number of replications grows. When the draws come from a Markov chain, they are dependent, Claims 2 to 4 do not apply, and the fact that thinning to about LL effective draws restores near-uniform ranks (Talts and coauthors 2018, Algorithm 2) is measured on the page, not proved.

Complexity

Each replication makes one prior draw, one simulation of cost SS, one run of the method of cost CC, and LL comparisons, so the total time is Θ(N(S+C+L))\Theta(N(S + C + L)). The run of the method is usually the dominant cost, since it is a full posterior computation; SBC costs NN times one analysis. The replications are independent and run in parallel. With a Markov chain thinned by TT, CC includes TLTL chain steps. The memory is the LL draws of one replication and the L+1L + 1 counts, Θ(L)\Theta(L).

How many replications are needed: under uniformity each count is binomial(N,1/(L+1))(N, 1/(L+1)), with relative spread L/N\sqrt{L/N}. To see a 1010 percent excess in a bin of 1/B1/B of the ranks with a few standard errors, NN must be in the thousands, which is why moderate NN catches only clear errors.

Properties

  • Randomized. The counts and the pp-value vary with the seed; a correct method fails the test at level α\alpha in a fraction α\alpha of runs.
  • Needs no exact posterior. Only prior draws and data simulation are required, so it checks methods for models where no other reference exists.
  • Checks one function at a time. A separate histogram is needed for each coordinate or function ff, and errors that affect only the dependence between coordinates can pass all of them.
  • Necessary, not sufficient. It checks calibration averaged over the prior predictive law. The prior sampler passes, and a method that is wrong for some data sets and wrong in the other direction for others can pass.
  • Diagnostic shapes. The histogram shows the kind of error, not only its presence.

Variants and improvements

  • Posterior quantiles. Cook, Gelman and Rubin (2006) used the quantile of the truth among the draws, transformed to the normal scale, and combined the results across parameters. With finite LL the quantile is discrete, so its law is not exactly uniform; ranks remove that problem.
  • Bins. Merge the L+1L + 1 ranks into BB bins of equal size, with BB dividing L+1L + 1, to stabilize the counts.
  • Tests on the empirical distribution function. Compare the empirical distribution function of the normalized ranks r/(L+1)r/(L+1) with the uniform one, for example by a Kolmogorov-Smirnov test or simultaneous confidence bands; these are more powerful than the histogram for smooth departures.
  • Data-dependent test quantities. Taking ff to depend on the data as well, such as the log-likelihood of y~\tilde y at θ\theta, can reveal errors that every coordinate misses (Modrák and coauthors 2023).
  • Amortized methods. For neural posterior estimators and other likelihood-free methods, such as approximate Bayesian computation, each replication is cheap once the method is trained, so SBC with large NN is a standard check.

When to use it

Use SBC when you write a new sampler, a new model implementation, or an approximate method such as variational inference or ABC, and want evidence that it computes the posterior it should. It finds coding errors in the model, wrong priors in the sampler, and approximations that are systematically too narrow or too wide. For a single data set and an exact-in-principle sampler such as Hamiltonian Monte Carlo, convergence checks such as the Gelman-Rubin diagnostic are cheaper; SBC checks the method over the whole prior. To check the model against real data, use a posterior predictive check instead: SBC assumes the model is true.

Pitfalls

  • Autocorrelated draws. Taking LL consecutive states of a Markov chain in L5 gives a U-shaped histogram even for a correct chain; in the example, p=3×10−190p = 3 \times 10^{-190}. Thin the chain to about LL effective draws.
  • Plain ranks with ties. Counting only the smaller values in L6 when f(θ)f(\theta) has atoms makes rank 00 too likely, which looks like an error of the method. Break ties at random.
  • Drawing the truth from a different prior. If L3 draws from a prior other than the one the method uses, the truth is no longer a posterior draw, and correct methods fail. Use the same prior in both places, or use SBC exactly to detect such a mismatch.
  • Reading a flat histogram as proof. The prior sampler gives flat ranks in the example. A flat histogram from L8 says the method is calibrated on average, not that it uses the data correctly; compare also the posterior spread with the prior spread.
  • Too few replications. With NN of a few hundred, the histogram of L8 is noisy, and only large errors are visible. Choose NN in the thousands for subtle errors, and use the same seed scheme to reproduce failures.
  • Priors that are too wide. Very wide priors in L3 simulate extreme data sets on which the method fails for numerical reasons that never matter in practice. Use the prior of the actual analysis, and inspect failing replications.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

simulation_based_calibration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simulation-based-calibration/. The authors are listed in prov/GB2WNE.jsonl.
"""Simulation-based calibration (Talts, Betancourt, Simpson, Vehtari and Gelman 2018).

Draw a parameter from the prior, simulate data from it, ask the sampler under test for L
posterior draws given those data, and record the rank of the true parameter among the
draws. If the sampler returns independent draws from the true posterior, the ranks are
uniform on {0, ..., L}. Ties are broken at random, which keeps the ranks uniform when the
quantity has atoms.
"""

import math
import random
from typing import Callable, Sequence


def rank_with_ties(f_true: float, f_draws: Sequence[float], rng: random.Random) -> int:
    """Number of draws below f_true, plus a uniform share of the draws equal to it."""
    below = sum(1 for v in f_draws if v < f_true)
    ties = sum(1 for v in f_draws if v == f_true)
    return below + (rng.randint(0, ties) if ties else 0)


def sbc(
    prior_draw: Callable,
    simulate: Callable,
    posterior_draws: Callable,
    f: Callable,
    n_reps: int,
    n_draws: int,
    rng: random.Random,
) -> list[int]:
    """Return the counts of the ranks 0..n_draws over n_reps replications.

    posterior_draws(y, n_draws, rng) is the sampler under test.
    """
    counts = [0] * (n_draws + 1)  # @line L1
    for _ in range(n_reps):  # @line L2
        theta = prior_draw(rng)  # @line L3
        y = simulate(theta, rng)  # @line L4
        draws = posterior_draws(y, n_draws, rng)  # @line L5
        r = rank_with_ties(f(theta), [f(t) for t in draws], rng)  # @line L6
        counts[r] += 1  # @line L7
    return counts  # @line L8


def bin_counts(counts: Sequence[int], n_bins: int) -> list[int]:
    """Merge the L + 1 rank counts into n_bins equal bins; n_bins must divide L + 1."""
    width, rem = divmod(len(counts), n_bins)
    if rem:
        raise ValueError("the number of bins must divide L + 1")
    return [sum(counts[b * width:(b + 1) * width]) for b in range(n_bins)]


def chi2_sf(x: float, k: int) -> float:
    """P(X >= x) for X chi-squared with k degrees of freedom, in closed form.

    Even k: exp(-x/2) sum_{j < k/2} (x/2)^j / j!.
    Odd k: erfc(sqrt(x/2)) + exp(-x/2) sum_{j < (k-1)/2} (x/2)^(j+1/2) / Gamma(j + 3/2).
    """
    if x <= 0:
        return 1.0
    h = x / 2
    if k % 2 == 0:
        term, total = 1.0, 1.0
        for j in range(1, k // 2):
            term *= h / j
            total += term
        return math.exp(-h) * total
    total = math.erfc(math.sqrt(h))
    term = math.sqrt(h) / math.gamma(1.5)
    for j in range((k - 1) // 2):
        total += math.exp(-h) * term
        term *= h / (j + 1.5)
    return total


def chi2_uniformity(counts: Sequence[int]) -> tuple[float, float]:
    """Pearson's chi-squared statistic against equal expected counts, and its p-value."""
    n, b = sum(counts), len(counts)
    e = n / b
    stat = math.fsum((c - e) ** 2 / e for c in counts)
    return stat, chi2_sf(stat, b - 1)


def thin(chain: Sequence, step: int, n: int) -> list:
    """Every step-th state of the chain, n of them (Talts et al., Algorithm 2)."""
    out = list(chain[step - 1::step])[:n]
    if len(out) < n:
        raise ValueError("chain too short for this thinning")
    return out


# A conjugate test model: theta ~ N(0, 1), y_1..y_m ~ N(theta, 1);
# the posterior is N(sum(y) / (m + 1), 1 / (m + 1)).

def normal_model(m: int):
    def prior_draw(rng):
        return rng.gauss(0.0, 1.0)

    def simulate(theta, rng):
        return [rng.gauss(theta, 1.0) for _ in range(m)]

    def posterior(y):
        return sum(y) / (m + 1), 1.0 / (m + 1)

    return prior_draw, simulate, posterior


def gaussian_sampler(posterior: Callable, scale: float = 1.0, shift: float = 0.0) -> Callable:
    """Independent draws from N(mean + shift * sd, (scale * sd)^2); scale 1 and shift 0 is correct."""
    def draws(y, n, rng):
        mu, v = posterior(y)
        sd = math.sqrt(v)
        return [rng.gauss(mu + shift * sd, scale * sd) for _ in range(n)]
    return draws


def ar1_sampler(posterior: Callable, rho: float, step: int = 1) -> Callable:
    """A Markov chain with the exact posterior as its stationary law, started at a
    posterior draw: x' = mu + rho (x - mu) + sqrt(1 - rho^2) sd e. Keeps every step-th state."""
    def draws(y, n, rng):
        mu, v = posterior(y)
        sd = math.sqrt(v)
        x = rng.gauss(mu, sd)
        c = math.sqrt(1 - rho * rho) * sd
        chain = []
        for _ in range(n * step):
            x = mu + rho * (x - mu) + c * rng.gauss(0.0, 1.0)
            chain.append(x)
        return thin(chain, step, n)
    return draws
test_simulation_based_calibration.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simulation-based-calibration/. The authors are listed in prov/GB2WNE.jsonl.
"""Tests for simulation-based calibration: the exact law of the rank in a discrete model
(uniform with random tie breaking, not uniform without it), uniform ranks for a correct
sampler, the characteristic shapes for wrong ones, and thinning of a Markov chain."""

import itertools
import math
import random
import unittest
from fractions import Fraction as F

from simulation_based_calibration import (
    ar1_sampler,
    bin_counts,
    chi2_sf,
    chi2_uniformity,
    gaussian_sampler,
    normal_model,
    sbc,
)


def exact_rank_law(prior, like, post_of, n_draws, randomize=True):
    """The exact law of the rank of theta~ among n_draws draws from post_of(y), for a model
    with finitely many parameter values and data values. prior[t] and like[t][y] are Fractions."""
    k = len(prior)
    ys = range(len(like[0]))
    law = [F(0)] * (n_draws + 1)
    for y in ys:
        q = post_of(y)
        for t in range(k):
            joint = prior[t] * like[t][y]
            if joint == 0:
                continue
            for draws in itertools.product(range(k), repeat=n_draws):
                pd = math.prod((q[d] for d in draws), start=F(1))
                below = sum(1 for d in draws if d < t)
                ties = sum(1 for d in draws if d == t)
                if randomize:
                    for r in range(below, below + ties + 1):
                        law[r] += joint * pd / (ties + 1)
                else:
                    law[below] += joint * pd
    return law


class TestExactRankLaw(unittest.TestCase):
    def test_uniform_with_random_ties_and_also_for_the_prior(self):
        rng = random.Random(1)
        for _ in range(500):
            k = rng.randint(2, 4)
            m = rng.randint(1, 3)
            raw = [rng.randint(1, 9) for _ in range(k)]
            prior = [F(v, sum(raw)) for v in raw]
            ps = sorted(rng.sample([F(1, 5), F(2, 5), F(3, 5), F(4, 5), F(1, 2)], k))
            like = [[math.comb(m, y) * p**y * (1 - p) ** (m - y) for y in range(m + 1)] for p in ps]

            def post_of(y):
                joint = [prior[t] * like[t][y] for t in range(k)]
                s = sum(joint)
                return [j / s for j in joint]

            n_draws = rng.randint(1, 3)
            law = exact_rank_law(prior, like, post_of, n_draws)
            self.assertEqual(law, [F(1, n_draws + 1)] * (n_draws + 1))
            # without random tie breaking, rank 0 is too likely
            plain = exact_rank_law(prior, like, post_of, n_draws, randomize=False)
            self.assertEqual(sum(plain), 1)
            self.assertGreater(plain[0], F(1, n_draws + 1))
            # a sampler that ignores the data and returns the prior also passes
            law_prior = exact_rank_law(prior, like, lambda y: prior, n_draws)
            self.assertEqual(law_prior, [F(1, n_draws + 1)] * (n_draws + 1))


class TestNormalModel(unittest.TestCase):
    L = 20

    def run_sbc(self, sampler):
        prior_draw, simulate, _ = normal_model(5)
        return sbc(prior_draw, simulate, sampler, lambda t: t, 1000, self.L, random.Random(7))

    def test_correct_sampler_gives_uniform_ranks(self):
        _, _, post = normal_model(5)
        c = self.run_sbc(gaussian_sampler(post))
        self.assertEqual(sum(c), 1000)
        self.assertGreater(chi2_uniformity(c)[1], 0.01)
        self.assertGreater(chi2_uniformity(bin_counts(c, 7))[1], 0.01)

    def test_wrong_samplers_give_their_shapes(self):
        _, _, post = normal_model(5)
        expected_ends = 2 * 1000 / (self.L + 1)
        narrow = self.run_sbc(gaussian_sampler(post, scale=0.6))
        self.assertLess(chi2_uniformity(narrow)[1], 1e-10)
        self.assertGreater(narrow[0] + narrow[-1], 2 * expected_ends)  # U shape
        wide = self.run_sbc(gaussian_sampler(post, scale=1.5))
        self.assertLess(chi2_uniformity(wide)[1], 1e-10)
        self.assertLess(wide[0] + wide[-1], expected_ends / 2)  # hump
        shifted = self.run_sbc(gaussian_sampler(post, shift=0.5))
        self.assertLess(chi2_uniformity(shifted)[1], 1e-10)
        mean_rank = sum(r * c for r, c in enumerate(shifted)) / 1000
        self.assertLess(mean_rank, self.L / 2 - 2)  # draws too high, so the truth ranks low

    def test_prior_sampler_is_not_detected(self):
        c = self.run_sbc(lambda y, n, rng: [rng.gauss(0.0, 1.0) for _ in range(n)])
        self.assertGreater(chi2_uniformity(c)[1], 0.01)

    def test_autocorrelated_chain_fails_and_thinning_fixes_it(self):
        _, _, post = normal_model(5)
        raw = self.run_sbc(ar1_sampler(post, 0.9))
        self.assertLess(chi2_uniformity(raw)[1], 1e-10)
        self.assertGreater(raw[0] + raw[-1], 3 * 2 * 1000 / (self.L + 1))
        # effective sample size of an AR(1) chain: n (1 - rho) / (1 + rho), so thin by 19
        thinned = self.run_sbc(ar1_sampler(post, 0.9, 19))
        self.assertGreater(chi2_uniformity(thinned)[1], 0.01)


class TestChiSquared(unittest.TestCase):
    def test_closed_forms(self):
        # upper 5 percent points from standard tables
        for x, k in ((3.841, 1), (5.991, 2), (7.815, 3), (30.144, 19), (31.410, 20)):
            self.assertAlmostEqual(chi2_sf(x, k), 0.05, places=3)
        for x in (0.1, 1.0, 4.0, 20.0):
            self.assertAlmostEqual(chi2_sf(x, 1), math.erfc(math.sqrt(x / 2)), places=12)
            self.assertAlmostEqual(chi2_sf(x, 2), math.exp(-x / 2), places=12)
            # P(chi2_{k+2} >= x) = P(chi2_k >= x) + (x/2)^(k/2) e^(-x/2) / Gamma(k/2 + 1)
            for k in range(1, 12):
                h = x / 2
                self.assertAlmostEqual(chi2_sf(x, k + 2), chi2_sf(x, k) + h ** (k / 2) * math.exp(-h) / math.gamma(k / 2 + 1), places=12)


if __name__ == "__main__":
    unittest.main()

History

Geweke (2004) tested posterior simulators by comparing two ways of drawing from the joint law of parameters and data. Cook, Gelman and Rubin (2006) proposed to validate Bayesian software by simulating parameters from the prior and data from the model, and checking that the posterior quantiles of the true parameters are uniform. Gelman (2017) published a correction noting that dependence between draws changes the law of their test statistics. Talts, Betancourt, Simpson, Vehtari and Gelman (2018) replaced the quantiles by rank statistics, whose law is exactly uniform for independent draws, interpreted the shapes of the rank histogram, and gave a thinning rule for Markov chains. SBC is now a standard check in probabilistic programming and in simulation-based inference.

References

  1. Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari and Andrew Gelman, Validating Bayesian inference algorithms with simulation-based calibration, 2018, Section 4.1 and Algorithm 1 (rank statistics and the SBC histogram), Section 4.2 (U shape for posteriors that are too narrow, hump for too wide, skew for bias), Section 5.1 and Algorithm 2 (thinning a Markov chain by its effective sample size), Appendix B (proof of Theorem 1)
  2. Samantha R. Cook, Andrew Gelman and Donald B. Rubin, Validation of software for Bayesian models using posterior quantiles, Journal of Computational and Graphical Statistics 15(3), 2006, pages 675 to 692: posterior quantiles of the true parameter are uniform for correct software (general locator)
  3. Andrew Gelman, Correction to Cook, Gelman and Rubin (2006), Journal of Computational and Graphical Statistics, 2017, the dependence created by autocorrelated draws changes the law of the test statistics of the 2006 paper (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example