Coming from emcee

emcee

telescopic

walkers, which move together as an ensemble

replicates: independent pairs of chains

burn-in steps, discarded

k, chosen from pilot meeting times; the bias left at k is corrected, not ignored

the autocorrelation time, which sets the error bars

meeting times, which set the cost; the error bars come from independent replicates

get_chain(flat=True)

result.measure: atoms whose weights can be negative; they are not samples, so plot them with their weights (Signed measures, Plot a result)

get_chain(), and arviz.from_emcee

result.chains(), and result.to_datatree(): one ordinary chain per kept replicate after k (What replaces a judgment of convergence)

log_prob_fn(theta, *args), vectorize=True, pool=

the same: log_prob(theta, *args), vectorize=True, pool=, except that log_prob returns the log-density alone, without blobs; derived quantities come from result.estimate after the run

run_mcmc(None, n_steps) continues the chains; an HDFBackend keeps them in a file to continue later

sampler.run(n) adds replicates to the same sampler; a new sampler continues a returned or saved result with sampler.resume(result) (Continuing a run); sample(..., checkpoint=directory) keeps the replicates in a directory as they finish, and the same call completes a killed run (Checkpoints)

telescopic does not make chains mix faster. Where one chain mixes slowly, as between distant modes, pairs meet late and replicates cost more. Its gain is error bars that do not depend on judging convergence, from replicates that run in parallel without communication.

The rest of this page runs telescopic and emcee on the line fit of the Quickstart, with the same number of log-density evaluations. The errors of the data are known, so the posterior is Gaussian and known exactly, and both samplers’ estimates can be checked against it.

The data and the exact posterior

A line fit like that of emcee’s tutorial, without its underestimated errors: 50 points x, y from the line \(y = -0.9x + 4.3\), with Gaussian errors whose standard deviations yerr, between 0.1 and 0.6, are known; the Quickstart draws them. The log-density is the log-likelihood, so the prior is flat. It takes one point of shape (2,), or a batch of shape (n, 2) as both samplers pass with vectorize=True. Counted wraps it to count the points at which a sampler evaluates it:

import emcee
import numpy as np
from scipy import optimize

import telescopic


def log_prob(theta, x, y, yerr):
    slope, intercept = theta[..., :1], theta[..., 1:]
    return -0.5 * np.sum(((y - slope * x - intercept) / yerr) ** 2, axis=-1)


class Counted:
    """log_prob, counting the points at which it is evaluated."""

    def __init__(self):
        self.points = 0

    def __call__(self, theta, *args):
        self.points += len(np.atleast_2d(theta))
        return log_prob(theta, *args)

The posterior’s mean is the weighted least-squares fit, and its covariance is \((A^\top C^{-1} A)^{-1}\), where \(A\) has the rows \((x_i, 1)\) and \(C\) is the diagonal matrix of the squared errors:

design = np.vander(x, 2)
precision = design.T @ (design / yerr[:, None] ** 2)
exact_mean = np.linalg.solve(precision, design.T @ (y / yerr**2))
exact_std = np.sqrt(np.diag(np.linalg.inv(precision)))

telescopic

We run the line fit from the Quickstart, starting from a Gaussian ten times wider than an optimizer’s error bars (Initial distributions), with the log-density evaluated in batches:

fit = optimize.minimize(lambda theta: -log_prob(theta, x, y, yerr), [0.0, 0.0])
init = telescopic.initial.Normal(mean=fit.x, cov=100 * fit.hess_inv)
for_telescopic = Counted()
result = telescopic.sample(
    for_telescopic,
    init,
    args=(x, y, yerr),
    vectorize=True,
    names=["slope", "intercept"],
    rng=42,
)
print(f"{for_telescopic.points:,} evaluations, {result.n_log_prob:,} of them in the run")
78,147 evaluations, 65,051 of them in the run

result.n_log_prob counts the evaluations of the run; the others are those of tuning and of the meeting-time pilot, which A slow log-density counts.

emcee

As in emcee’s tutorial, 32 walkers start within about \(10^{-4}\) of the optimizer’s fit. They take as many steps as telescopic’s evaluations allow. emcee copies NumPy’s global random state when it makes its sampler, so seeding that state fixes the run:

n_walkers = 32
n_steps = for_telescopic.points // n_walkers - 1  # emcee also evaluates the start
start = fit.x + 1e-4 * np.random.default_rng(1).normal(size=(n_walkers, 2))
for_emcee = Counted()
np.random.seed(42)
ensemble = emcee.EnsembleSampler(n_walkers, 2, for_emcee, args=(x, y, yerr), vectorize=True)
ensemble.run_mcmc(start, n_steps)
print(f"{n_steps:,} steps, {for_emcee.points:,} evaluations")
2,441 steps, 78,144 evaluations

The integrated autocorrelation time \(\tau_{\mathrm{int}}\) of each parameter sets the burn-in and the thinning. As in emcee’s documentation, the burn-in is twice the largest and the thinning half the smallest. The \(N\) steps of a walker after the burn-in are worth about \(N/\tau_{\mathrm{int}}\) independent draws, so the Monte Carlo error of a mean over the \(W = 32\) walkers is \(\hat\sigma\sqrt{\tau_{\mathrm{int}}/(WN)}\):

tau_int = ensemble.get_autocorr_time()
burn, thin = int(2 * tau_int.max()), int(tau_int.min() / 2)
samples = ensemble.get_chain(discard=burn, thin=thin, flat=True)
emcee_mean, emcee_std = samples.mean(axis=0), samples.std(axis=0)
emcee_error = emcee_std * np.sqrt(tau_int / (n_walkers * (n_steps - burn)))
print(f"tau_int = {tau_int.round(1)}; burn-in {burn} steps, thinning {thin}")
tau_int = [28.7 30.3]; burn-in 60 steps, thinning 14

Side by side

The means with their error bars, and the standard deviations, of slope and intercept:

mean = result.mean()
with np.printoptions(precision=5):
    print("means:      exact", exact_mean)
    print("            emcee", emcee_mean, "±", emcee_error)
    print("       telescopic", mean.value, "±", mean.standard_error)
    print("stds:       exact", exact_std)
    print("            emcee", emcee_std)
    print("       telescopic", result.std())
means:      exact [-0.88907  4.26331]
            emcee [-0.88888  4.26213] ± [0.00023 0.00132]
       telescopic [-0.88906  4.26328] ± [0.00013 0.00071]
stds:       exact [0.01206 0.06581]
            emcee [0.01201 0.06596]
       telescopic [0.01191 0.06497]

The means differ from the exact ones by at most 0.89 error bars, and the standard deviations by at most 1.3%. With the same number of log-density evaluations, telescopic’s error bars are 0.57 and 0.54 times emcee’s, for the slope and the intercept. This is one run of each, on one target.

Drawn against the exact posterior, the two samplers’ means with two error bars, in units of the posterior’s standard deviation, and the joint posterior:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

fig, (left, right) = plt.subplots(1, 2, figsize=(7, 3), width_ratios=(1, 1.2))
for row, name in enumerate(["slope", "intercept"]):
    for shift, (label, value, error, color) in enumerate(
        (
            ("emcee", emcee_mean, emcee_error, "C2"),
            ("telescopic", mean.value, mean.standard_error, "C0"),
        )
    ):
        z_value = (value[row] - exact_mean[row]) / exact_std[row]
        z_error = 2 * error[row] / exact_std[row]
        left.errorbar(
            z_value, row + 0.15 * (2 * shift - 1), xerr=z_error, fmt="o", color=color,
            capsize=3, label=label if row == 0 else None,
        )
left.axvline(0, color="gray", linewidth=0.8)
left.set_yticks([0, 1], ["slope", "intercept"])
left.set_ylim(1.5, -1.0)
left.set(xlabel="(mean $-$ exact) / posterior std")
left.legend(loc="upper center", ncols=2)

span = np.column_stack([exact_mean - 3.5 * exact_std, exact_mean + 3.5 * exact_std])
masses, _, (slope_edges, intercept_edges) = result.histogram([0, 1], bins=24, range=span)
shade = LinearSegmentedColormap.from_list("shade", [fig.get_facecolor(), "C0"])
right.pcolormesh(slope_edges, intercept_edges, masses.T, cmap=shade, vmin=0)
cov = np.linalg.inv(precision)
values, vectors = np.linalg.eigh(cov)
angle = np.linspace(0, 2 * np.pi, 200)
circle = np.stack([np.cos(angle), np.sin(angle)])
for radius in (1, 2):
    ellipse = exact_mean[:, None] + radius * vectors @ (np.sqrt(values)[:, None] * circle)
    right.plot(*ellipse, color="0.25", linewidth=1.2)
shown = samples[np.random.default_rng(0).choice(len(samples), 1000, replace=False)]
right.plot(*shown.T, ".", color="C2", markersize=1.5, alpha=0.6)
right.set(xlim=span[0], ylim=span[1], xlabel="slope", ylabel="intercept");
Left: for the slope and the intercept, a vertical line at the exact mean and two dots with horizontal error bars, emcee's and telescopic's, both within a tenth of a posterior standard deviation of the line. Right: the exact 1- and 2-sigma ellipses of slope and intercept, a tilted ellipse, over telescopic's two-dimensional histogram, shaded blue by each bin's mass, which fills the ellipses, and emcee's samples as small dots that fill them too.

Left: emcee’s and telescopic’s means of the slope and the intercept with two error bars, at equal numbers of log-density evaluations, as distances from the exact mean in units of the exact posterior standard deviation. Right: the exact 1- and 2-sigma ellipses of the posterior, telescopic’s histogram of slope and intercept from result.histogram, darker where a bin’s mass is larger, and a thousand of emcee’s samples.

What the error bars mean

Both error bars estimate the Monte Carlo error of a mean, under different assumptions.

emcee’s, \(\hat\sigma\sqrt{\tau_{\mathrm{int}}/(WN)}\), treats the walkers as independent chains that were stationary after the burn-in, and it inherits the error of \(\tau_{\mathrm{int}}\), estimated from the same run. A burn-in that is too short biases the means by an amount that the error bar does not include.

telescopic’s is the standard error of a mean of independent replicates, whose estimates are unbiased for any burn-in k (Theory). It is valid as the number of replicates grows, provided their variance is finite, and it needs no judgment of convergence: the meeting times bound the distance from stationarity instead (Quickstart, Error bars from replicates).