When unbiased is not enough

The estimates are unbiased for any settings and every initial distribution from which the chain converges (Theory), yet a run can miss the truth by many times its error bar, or cover it with an error bar too wide to use. This page runs such cases and shows what telescopic reports for each. A run’s warnings appear under its cell; Warnings and errors explains each one, and Initial distributions gives the advice on choosing one.

import warnings

import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize, special, stats

import telescopic
from telescopic.kernels import Independence, Mixture, MultivariateT, RandomWalk

np.set_printoptions(precision=3)

Two modes

A start that misses a mode

The target is the mixture \(\tfrac12\mathcal N(-4, 1) + \tfrac12\mathcal N(4, 1)\) of Jacob, O’Leary & Atchadé (2020, §5.1), with their random walk of proposal variance 1, \(k = 50\), \(m = 500\), lag 1 and 1,000 replicates. The test function is the indicator of \(x > 3\), whose expectation is \(\tfrac12\Phi(1) + \tfrac12\Phi(-7)\). From \(\mathcal N(10, 1)\), every chain starts above the mode at 4, far from the mode at \(-4\):

mixture = telescopic.examples.mixture()
truth = 0.5 * stats.norm.cdf(1) + 0.5 * stats.norm.cdf(-7)


def above_three(x):
    return (x[:, 0] > 3).astype(float)


def compare(result):
    estimate = result.estimate(above_three)
    low, high = estimate.interval
    error = (estimate.value - truth) / estimate.standard_error
    print(
        f"{estimate}; 95% interval [{low:.4g}, {high:.4g}]; "
        f"{error:+.1f} standard errors from the truth {truth:.4f}"
    )


def bimodal_run(initial):
    sampler = telescopic.CoupledSampler(
        mixture.log_prob,
        initial,
        vectorize=True,
        kernel=RandomWalk(np.eye(1), scale=1.0),
        rng=0,
    )
    return sampler.run(1000, k=50, m=500, lag=1)


narrow = bimodal_run(telescopic.initial.Normal([10.0], [[1.0]]))
compare(narrow)
Estimate(0.804645 ± 0.0047, R=1000); 95% interval [0.7955, 0.8138]; +82.5 standard errors from the truth 0.4207

The interval misses the truth by many standard errors, and the run emits no warning: telescopic.diagnostics.issues() finds none of the conditions that it checks.

telescopic.diagnostics.issues(narrow)
[]

This is the failure of an initial distribution that misses a mode (Initial distributions): every chain starts on the side of one mode, and the kernel rarely crosses to the other. Most seeds miss the truth in this setting without a warning (Measured rates).

A start that covers both modes

The same kernel and settings from \(\mathcal N(10, 10^2)\), the mixture’s default initial distribution (also theirs), which puts mass on both modes:

grid = np.linspace(-15, 35, 1001)
density = 0.5 * stats.norm.pdf(grid, -4, 1) + 0.5 * stats.norm.pdf(grid, 4, 1)
narrow_start = stats.norm.pdf(grid, 10, 1)
wide_start = stats.norm.pdf(grid, mixture.initial.mean[0], np.sqrt(mixture.initial.cov[0, 0]))
fig, ax = plt.subplots(figsize=(6, 2.8))
ax.fill_between(grid, density, color="0.85")
ax.plot(grid, density, color="0.45", linewidth=1.2)
ax.plot(grid, narrow_start, "--", color="C0")
ax.plot(grid, wide_start, "--", color="C1")
ax.fill_between(grid, wide_start, where=grid <= 0, color="C1", alpha=0.35)
ax.annotate("$N(10, 1)$", (11, 0.33), color="C0")
ax.annotate("$N(10, 10^2)$", (19, 0.05), color="C1")
below = stats.norm.cdf(-1)
ax.annotate(f"mass below 0: {below:.3f}", (-14.5, 0.27), color="C1")
ax.annotate(f"two starts on opposite sides: {2 * below * (1 - below):.3f}", (14, 0.2))
ax.set(xlabel="$x$", yticks=[], ylim=(0, 0.42));
The mixture's density, two gray humps at -4 and 4, with two dashed curves: the narrow initial distribution N(10, 1), a peak at 10 beyond the mode at 4, and the wide N(10, 10 squared), a low broad curve over both modes whose part below 0 is shaded, with its mass, 0.159; at the right, the probability 0.267 that two of its draws fall on opposite sides of 0.

The target \(\tfrac12\mathcal N(-4, 1) + \tfrac12\mathcal N(4, 1)\), in gray, and the two initial distributions, dashed: \(\mathcal N(10, 1)\) starts every chain beyond the mode at 4, and \(\mathcal N(10, 10^2)\) puts mass \(\Phi(-1)\), shaded, below 0, on the side of the mode at \(-4\). Two independent draws of \(\mathcal N(10, 10^2)\) fall on opposite sides of 0 with probability \(2\Phi(1)\Phi(-1)\), printed at the right.

wide = bimodal_run(mixture.initial)
ConvergenceWarning: replicate 30 has not met after 10000 iterations, and the run waits for it: a first Ctrl-C starts no new replicate but lets this one finish, and a second stops the run without a result; the meeting times may be heavy-tailed, so look at the kernel and the initial distribution
ConvergenceWarning: 41% of the pairs met after k + lag, so k may be too small: the bias correction is large and the variance high; run a new sampler with a larger k
ConvergenceWarning: the meeting times look heavy-tailed (tail index 1.77 < 2), so the variance of the estimates may be infinite; look at the survival function of plot_meeting_times, and at the kernel
compare(wide)
Estimate(-49.2237 ± 49, R=1000); 95% interval [-145.4, 46.91]; -1.0 standard errors from the truth 0.4207

The interval now covers the truth, but it is far wider than the range of a probability. The meeting times show why, in survival curves that telescopic.plotting.survival() overlays on one axis:

from telescopic import plotting

fig, ax = plt.subplots(figsize=(5, 3.5))
for label, result in (("$N(10, 1)$", narrow), ("$N(10, 10^2)$", wide)):
    plotting.survival(
        result.meeting_times, result.lag, ax, max_iter=result.max_iter, label=label
    )
ax.set(xscale="log", ylabel=r"$P(\tau - 1 > t)$")
ax.legend();
Two survival curves of the meeting times on logarithmic axes: the curve from N(10, 1) ends before 100 steps, and the curve from N(10, 10 squared) reaches beyond 10,000.

The survival functions of the meeting times from \(\mathcal N(10, 1)\) and from \(\mathcal N(10, 10^2)\), less the lag of 1, on log-log axes: from the wider start, the slowest pairs take more than \(10^4\) steps to meet.

measured = wide.diagnostics()
values = wide.estimate(above_three).replicates
print(f"slowest pair from N(10, 1): {narrow.meeting_times.max():.0f} steps")
print(f"pairs slower than 200 steps from N(10, 10^2): {np.mean(wide.meeting_times > 200):.3f}")
print(f"2 Phi(1) Phi(-1): {2 * stats.norm.cdf(1) * stats.norm.cdf(-1):.3f}")
print(f"pairs that met after k + lag: {measured['late_fraction']:.3f}")
print(f"tail index of the meeting times: {measured['tail_index']:.2f}")
print(f"the replicates' estimates: from {values.min():.0f} to {values.max():.0f}")
slowest pair from N(10, 1): 45 steps
pairs slower than 200 steps from N(10, 10^2): 0.274
2 Phi(1) Phi(-1): 0.267
pairs that met after k + lag: 0.411
tail index of the meeting times: 1.77
the replicates' estimates: from -13131 to 7246

Every pair from \(\mathcal N(10, 1)\) met within a few dozen steps. From \(\mathcal N(10, 10^2)\), the fraction of pairs slower than 200 steps is close to \(2\Phi(1)\Phi(-1)\), the probability that two draws fall on either side of 0: such a pair meets only after one of its chains crosses between the modes. The warnings report the consequences: more than a quarter of the pairs met after \(k + L\), a pair was still unmet after 10,000 iterations, and the tail index of the meeting times is below 2, so the variance of the estimates may be infinite. Until a pair meets, each difference \(\Delta_t\) enters its bias correction with a weight of up to 1 (Theory), so single replicates estimate this probability at values thousands apart: their mean is unbiased, and useless at these settings. The automatic recipe, applied to these meeting times, gives:

k_wide = telescopic.tuning.choose_k(wide.meeting_times)
print(f"k = {k_wide}, m = {10 * k_wide}; mean cost here: {measured['mean_cost']:.0f}")
k = 8389, m = 83890; mean cost here: 1869

Each replicate would then cost at least \(m\) kernel applications, many times the mean cost of this run.

A kernel that crosses

The automatic random walk, tuned on adaptive chains from the same wide start, learns a proposal covariance near the mixture’s variance of 17. With the default scale, 2.38 in one dimension, its proposals have a standard deviation near 10 and can cross between modes 8 apart in one step:

tuned = telescopic.CoupledSampler(
    mixture.log_prob, mixture.initial, vectorize=True, rng=0
).run(1000)
print("proposal covariance:", tuned.kernel.cov)
print(f"k = {tuned.k}, m = {tuned.m}, lag = {tuned.lag}")
compare(tuned)
proposal covariance: [[17.22]]
k = 23, m = 230, lag = 23
Estimate(0.415538 ± 0.0034, R=1000); 95% interval [0.4088, 0.4223]; -1.5 standard errors from the truth 0.4207

The interval covers the truth. The wide start made the failure visible, and the kernel that crosses removed it. A target with several modes needs both: an initial distribution that covers every mode (Initial distributions), and a kernel that crosses between them, such as this tuned random walk, or a Mixture with a component whose proposals reach the other modes (Kernels and couplings). With a kernel that cannot cross, the start decides which modes the pairs see.

A tuned proposal that covers one mode

A Mixture whose Independence component is left to tuning reaches only the modes that its tuned proposal covers. The target is \(0.7\,\mathcal N(-6e_1, I) + 0.3\,\mathcal N(6e_1, I)\) in 10 dimensions, two modes 12 apart, and the start \(\mathcal N(0, 100I)\) covers both. The test function is the indicator of \(x_0 < 0\), whose expectation is 0.7, the weight of the mode at \(-6e_1\):

dimension = 10
offset = np.zeros(dimension)
offset[0] = 6.0
log_weights = np.log([0.7, 0.3])


def two_modes(x):
    distances = np.array(
        [np.sum((x + offset) ** 2, axis=1), np.sum((x - offset) ** 2, axis=1)]
    )
    return special.logsumexp(log_weights[:, None] - 0.5 * distances, axis=0)


def left_mode(x):
    return (x[:, 0] < 0).astype(float)


cover = telescopic.initial.Normal(np.zeros(dimension), 100 * np.eye(dimension))


def mixture_run(seed, proposal=None):
    kernel = Mixture([RandomWalk(), Independence(proposal)], [0.8, 0.2])
    return telescopic.sample(two_modes, cover, 400, vectorize=True, kernel=kernel, rng=seed)


one_mode = mixture_run(3)
print(one_mode.estimate(left_mode))
print(f"largest R-hat of the tuning chains: {one_mode.tuning.rhat.max():.3f}")
print(f"location of the proposal along x_0: {one_mode.kernel.kernels[1].proposal.mean[0]:.2f}")
print(f"slowest pair: {one_mode.meeting_times.max():.0f} steps")
telescopic.diagnostics.issues(one_mode)
Estimate(0 ± 0, R=400)
largest R-hat of the tuning chains: 1.026
location of the proposal along x_0: 5.92
slowest pair: 103 steps
[]

The estimate is 0, with an error bar of 0, every pair met within about a hundred steps, and the run emits no warning. The tuning chains agree, and the Student-\(t\) proposal fitted to them sits in the mode at \(6e_1\). The four tuning chains settled in one mode (Tuning), so the proposal fitted to them covers that mode alone. Both chains of a pair receive the same proposal, accept it, and meet in that mode. As with a random walk whose steps are much shorter than the gap between modes (Theory), the replicates that would correct the estimate are too rare to occur in a run.

The next cell runs ten seeds and lists the kinds of warning that each run emits:

def compare_seeds(proposal=None):
    rows = []
    for seed in range(10):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", telescopic.ConvergenceWarning)
            result = mixture_run(seed, proposal)
        estimate = result.estimate(left_mode)
        wrong = abs(estimate.value - 0.7) > 5 * estimate.standard_error
        kinds = {issue.kind for issue in telescopic.diagnostics.issues(result)}
        rows.append((wrong, "tuning" in kinds, bool(kinds), kinds <= {"variance"}))
        print(
            f"seed {seed}: {estimate}, more than 5 standard errors from 0.7: {wrong}, "
            f"warnings: {sorted(kinds)}"
        )
    return np.array(rows)


tuned_rows = compare_seeds()
seed 0: Estimate(1.00022 ± 0.00027, R=400), more than 5 standard errors from 0.7: True, warnings: ['variance']
seed 1: Estimate(0.000232301 ± 0.00034, R=400), more than 5 standard errors from 0.7: True, warnings: ['variance']
seed 2: Estimate(0.00015625 ± 0.00016, R=400), more than 5 standard errors from 0.7: True, warnings: ['variance']
seed 3: Estimate(0 ± 0, R=400), more than 5 standard errors from 0.7: True, warnings: []
seed 4: Estimate(7.89474e-05 ± 0.00011, R=400), more than 5 standard errors from 0.7: True, warnings: ['variance']
seed 5: Estimate(1.00015 ± 0.00025, R=400), more than 5 standard errors from 0.7: True, warnings: ['variance']
seed 6: Estimate(0.697614 ± 0.0085, R=400), more than 5 standard errors from 0.7: False, warnings: ['tuning']
seed 7: Estimate(1 ± 5.6e-18, R=400), more than 5 standard errors from 0.7: True, warnings: []
seed 8: Estimate(0.999945 ± 5.1e-05, R=400), more than 5 standard errors from 0.7: True, warnings: []
seed 9: Estimate(3.76884e-05 ± 2.8e-05, R=400), more than 5 standard errors from 0.7: True, warnings: []

Most runs estimate the weight 0.7 as 0 or 1, depending on the mode that the tuning chains found, each with a small error bar. The warning that the tuning chains disagree (tuning) fires only in a run whose estimate is right: there they split between the modes, and the proposal fitted to them spans both. Agreeing tuning chains do not show that the run found every mode. Some of the wrong runs emit no warning at all, and the others only the warning that one replicate holds most of the variance (variance), which does not name the cause (Measured rates).

Two things help. Runs with different seeds disagree by far more than their error bars, so running more than one seed shows the failure whenever their tuning chains settle in different modes. They need not: on the same target with a second mode of standard deviation 0.3, the tuning chains of all 20 seeds tried settled in the wider mode, and every run estimated the weight 0.7 as 1 (runs of the same experiment, with the same setup, as the measured rates of the tuning warning), so agreement between seeds does not show that every mode was found. And when the modes are known, from optimizations started at several points or from the model, an Independence proposal given explicitly can cover them all. It needs only where the modes are, not their weights. A Student-\(t\) located at the midpoint of the two modes, the origin, whose scale matrix is the identity widened along \(x_0\) by the square of half the distance between the modes, reaches both:

scale = np.eye(dimension)
scale[0, 0] += offset[0] ** 2  # half the distance between the modes, squared
covering_rows = compare_seeds(MultivariateT(np.zeros(dimension), scale))
seed 0: Estimate(0.674764 ± 0.015, R=400), more than 5 standard errors from 0.7: False, warnings: ['late']
seed 1: Estimate(0.712805 ± 0.0095, R=400), more than 5 standard errors from 0.7: False, warnings: []
seed 2: Estimate(0.70444 ± 0.0087, R=400), more than 5 standard errors from 0.7: False, warnings: []
seed 3: Estimate(0.696559 ± 0.0069, R=400), more than 5 standard errors from 0.7: False, warnings: []
seed 4: Estimate(0.706211 ± 0.017, R=400), more than 5 standard errors from 0.7: False, warnings: ['late', 'variance']
seed 5: Estimate(0.695133 ± 0.014, R=400), more than 5 standard errors from 0.7: False, warnings: ['late', 'variance']
seed 6: Estimate(0.70915 ± 0.015, R=400), more than 5 standard errors from 0.7: False, warnings: ['late', 'tuning']
seed 7: Estimate(0.690884 ± 0.0091, R=400), more than 5 standard errors from 0.7: False, warnings: []
seed 8: Estimate(0.699639 ± 0.0074, R=400), more than 5 standard errors from 0.7: False, warnings: []
seed 9: Estimate(0.703285 ± 0.011, R=400), more than 5 standard errors from 0.7: False, warnings: ['late']

Every estimate now lies within 5 standard errors of 0.7. Such a proposal covers only the modes it is given: a mode that no optimization found stays as invisible as before.

A start far wider than the target

The line fit of the Quickstart, on its data x, y and yerr, with the log-density of Coming from emcee, which takes one point or a batch, and its exact Gaussian posterior, computed as there:

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)


design = np.vander(x, 2)
precision = design.T @ (design / yerr[:, None] ** 2)
exact_mean = np.linalg.solve(precision, design.T @ (y / yerr**2))
exact_var = np.diag(np.linalg.inv(precision))
exact_std = np.sqrt(exact_var)
print("exact mean", exact_mean, "and standard deviations", exact_std)
print("N(0, 10 I): standard deviations", np.sqrt(10) / exact_std, "times the exact ones")
exact mean [-0.889  4.263] and standard deviations [0.012 0.066]
N(0, 10 I): standard deviations [262.244  48.054] times the exact ones

From \(\mathcal N(0, 10I)\), whose standard deviations are hundreds and tens of times the posterior’s:

far = telescopic.sample(
    log_prob,
    telescopic.initial.Normal(np.zeros(2), 10 * np.eye(2)),
    args=(x, y, yerr),
    vectorize=True,
    names=["slope", "intercept"],
    rng=42,
)
far.summary()
ConvergenceWarning: the initial distribution is about 111 times wider than the target, by the standard deviations of its draws against those of the tuning chains: k from the 99% quantile of the pilot meeting times can leave a few replicates on their way to the target, which can dominate the variance; use a narrower initial distribution, or else give a larger k by hand; a confirmation round of pilot pairs at lag k is an option (A start far wider than the target, in the guide 'Set k, m, the lag, thin and max_iter')
ConvergenceWarning: replicate 30 holds 99% of the variance of the variance of slope: heavy tails or rare excursions make the error bars unreliable; check the initial distribution, and look for a mode that the other replicates missed
meanstandard_errorstdq16q50q84
slope-0.88890.0001606970.0176269-0.901033-0.889055-0.877079
intercept4.263230.0001467440.06612344.197734.263274.32855
  • R = 100, k = 1682, m = 16820, lag = 1682, thin = 1
  • kernel: RandomWalk(cov=<2x2>, scale=None, coupling='reflection')
  • meeting times: median 2136, 90% 2710, 99% 3323, max 3324; censored 0
  • cost per replicate: 1.738e+04 kernel applications, 0.0385 s; relative cost 1.15
  • pairs meeting after k + lag: 0.0% (at most 3.0% at 95%)
  • largest share of one replicate in a variance: 99%, for the variance of slope
  • warning: replicate 30 holds 99% of the variance of the variance of slope: heavy tails or rare excursions make the error bars unreliable; check the initial distribution, and look for a mode that the other replicates missed
  • warning: the initial distribution is about 111 times wider than the target, by the standard deviations of its draws against those of the tuning chains: k from the 99% quantile of the pilot meeting times can leave a few replicates on their way to the target, which can dominate the variance; use a narrower initial distribution, or else give a larger k by hand; a confirmation round of pilot pairs at lag k is an option (A start far wider than the target, in the guide 'Set k, m, the lag, thin and max_iter')

Tuning warned first, before any pair ran, that the start is far wider than the target. One replicate then holds most of the variance of an estimate, and the run warns again. Against the exact posterior, with the variances estimated as the expectations of \((\theta - \mu)^2\) for the exact mean \(\mu\):

def compare_line(result):
    spread = result.estimate(lambda theta: (theta - exact_mean) ** 2)
    print("standard deviations over the exact ones:", result.std() / exact_std)
    print("variances over the exact ones:", spread.value / exact_var)
    print("their standard errors over the exact ones:", spread.standard_error / exact_var)
    return spread


spread = compare_line(far)
standard deviations over the exact ones: [1.462 1.005]
variances over the exact ones: [2.137 1.01 ]
their standard errors over the exact ones: [1.138 0.009]

The slope’s standard deviation is too large, and the standard error of its variance exceeds the variance itself. The replicates’ estimates of the slope’s variance, over the exact one:

ratios = np.sort(spread.replicates[:, 0] / exact_var[0])
print(f"smallest {ratios[0]:.3f}, second largest {ratios[-2]:.3f}, largest {ratios[-1]:.1f}")
smallest 0.949, second largest 1.061, largest 114.8

One replicate causes it, as Initial distributions explains for starts this far. A Gaussian centered on an optimizer’s fit, with its inverse Hessian scaled by 100, is ten times wider than the posterior:

fit = optimize.minimize(lambda theta: -log_prob(theta, x, y, yerr), [0.0, 0.0])
widened = telescopic.sample(
    log_prob,
    telescopic.initial.Normal(fit.x, 100 * fit.hess_inv),
    args=(x, y, yerr),
    vectorize=True,
    names=["slope", "intercept"],
    rng=42,
)
compare_line(widened)
widened.summary()
standard deviations over the exact ones: [0.988 0.987]
variances over the exact ones: [0.976 0.975]
their standard errors over the exact ones: [0.018 0.015]
meanstandard_errorstdq16q50q84
slope-0.8890560.0001317920.0119146-0.901088-0.889112-0.877118
intercept4.263280.0007050460.06496734.198084.264454.32796
  • R = 100, k = 63, m = 630, lag = 63, thin = 1
  • kernel: RandomWalk(cov=<2x2>, scale=None, coupling='reflection')
  • meeting times: median 82, 90% 103, 99% 128, max 138; censored 0
  • cost per replicate: 651.9 kernel applications, 0.00157 s; relative cost 1.15
  • pairs meeting after k + lag: 2.0% (at most 6.2% at 95%)
  • largest share of one replicate in a variance: 31%, for the variance of slope

The run emits no warning, no replicate dominates, and the standard deviations and variances agree with the exact ones, with small error bars.

Each run above printed its warnings as it ended, or, for a slow pair, as it happened, except the runs of compare_seeds, which listed them. Warnings and errors shows how to read them from a result and how to turn them into errors.