Choosing k, m and the lag

This page applies the automatic recipe of Atchadé & Jacob (2024) step by step on a correlated Gaussian, then measures the cost and the variance that other settings give. Settings describes k, m and the lag.

The pilot

The target is examples.gaussian(10): the Gaussian \(\mathcal N(0, \Sigma)\) in 10 dimensions with \(\Sigma_{ij} = 0.9^{|i-j|}\), started from \(\mathcal N(0, 4I)\). Its log-density takes a batch of points. tune() sets the proposal covariance of a random walk from adaptive Metropolis chains, and freezes the kernel:

import matplotlib.pyplot as plt
import numpy as np

import telescopic

example = telescopic.examples.gaussian(10)
sampler = telescopic.CoupledSampler(
    example.log_prob, example.initial, vectorize=True, rng=0
)
sampler.tune()
sampler.kernel
RandomWalk(cov=<10x10>, scale=None, coupling='reflection')

meeting_times() runs 100 new pairs with lag 1 until they meet, and telescopic.tuning.choose_k() takes the 99% quantile of \(\tau - 1\) as \(k\):

times = sampler.meeting_times()
k = telescopic.tuning.choose_k(times)
print(f"k = {k}; pairs with tau - 1 > k: {np.sum(times - 1 > k)} of {len(times)}")
k = 222; pairs with tau - 1 > k: 1 of 100

The recipe then sets the lag to \(k\) and \(m\) to \(10k\). The pilot’s meeting times, with \(k\) dashed and the level 0.01 dotted, and their survival function drawn by telescopic.plotting.survival() from the array and its lag:

from telescopic import plotting

fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.5))
left.hist(times - 1, bins=20)
left.set(xlabel=r"$\tau - 1$", ylabel="pilot pairs")
plotting.survival(times, 1, right)
right.axhline(0.01, color="gray", linestyle=":")
right.set(ylabel=r"$P(\tau - 1 > t)$")
for ax in (left, right):
    ax.axvline(k, color="gray", linestyle="--", label="$k$")
right.legend();
Left, a histogram of the pilot's meeting times less 1; right, their survival function on a logarithmic scale; both with a dashed vertical line at k, and the right with a dotted horizontal line at 0.01.

The meeting times of the pilot pairs, less the lag of 1: their histogram (left) and survival function on a log scale (right), with \(k\) dashed and the level 0.01 dotted.

The recipe

With k, m and lag left at "auto", the first run() applies the recipe to the pilot already run:

recipe = sampler.run(500)
recipe.summary()
meanstandard_errorstdq16q50q84
x00.006760280.005819790.998241-0.9873280.005994450.999189
x10.007430770.006069921.00053-0.9871780.005953791.00174
x20.01097020.005724320.99962-0.9860120.005500651.00892
x30.009282730.006165140.999762-0.9838960.009907791.00113
x40.01211660.006227860.999288-0.9835710.00934461.00894
x50.009129450.006284050.997688-0.9839520.005585281.00374
x60.008787780.006285931.00084-0.989540.006783791.01295
x70.008691410.006186441.00033-0.9846040.006016141.01073
x80.01020340.006282771.00107-0.9833050.01030231.00799
x90.009531560.006068111.00303-0.9887890.01114171.00714
  • R = 500, k = 222, m = 2220, lag = 222, thin = 1
  • kernel: RandomWalk(cov=<10x10>, scale=None, coupling='reflection')
  • meeting times: median 337, 90% 409, 99% 478, max 527; censored 0
  • tail index of the meeting times: 6.48
  • cost per replicate: 2342 kernel applications, 0.00308 s; relative cost 1.17
  • pairs meeting after k + lag: 3.8% (at most 5.5% at 95%)
  • largest share of one replicate in a variance: 4%, for the variance of x9

The footer gives the cost of a replicate, its relative cost, and the fraction of pairs that met after \(k + L\), the ones that carry a bias correction (The summary defines each entry). That fraction need not equal the pilot’s fraction after \(k + 1\): the lag changes the law of \(\tau - L\).

Other settings

Each setting below gets a sampler of its own, with its own seed, since a sampler keeps the settings of its first run. The samplers share the tuned kernel and so skip the tuning; with k given, they skip the pilot too. A run warns as it ends when a condition of Warnings and errors holds:

choices = {
    "lag_1": dict(k=k, m=10 * k, lag=1),
    "m_2k": dict(k=k, m=2 * k, lag=k),
    "k_50": dict(k=50, m=500, lag=1),
}
results = {"recipe": recipe}
for seed, (name, settings) in enumerate(choices.items(), start=1):
    other = telescopic.CoupledSampler(
        example.log_prob, example.initial, vectorize=True, kernel=sampler.kernel, rng=seed
    )
    results[name] = other.run(500, **settings)
ConvergenceWarning: replicate 194 holds 93% of the variance of the variance of x9: heavy tails or rare excursions make the error bars unreliable; check the initial distribution, and look for a mode that the other replicates missed
ConvergenceWarning: 95% 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

For each run: the estimate of \(\mathbb E[x_0^2] = 1\), the mean cost of a replicate in kernel applications, the relative cost, the fraction of pairs that met after \(k + L\), the inefficiency (Theory), and the kinds of the warnings that apply, from telescopic.diagnostics.issues():

def second_moment(x):
    return x[:, 0] ** 2


print(
    f"{'':8}{'k':>5}{'lag':>5}{'m':>6}{'E[x0^2]':>16}{'cost':>7}"
    f"{'rel.':>6}{'late':>7}{'ineff.':>10}  issues"
)
rows = {}
for name, result in results.items():
    estimate = result.estimate(second_moment)
    row = result.diagnostics()
    row["inefficiency"] = np.var(estimate.replicates, ddof=1) * row["mean_cost"]
    row["issues"] = [issue.kind for issue in telescopic.diagnostics.issues(result)]
    row["estimate"] = estimate
    rows[name] = row
    print(
        f"{name:8}{result.k:5}{result.lag:5}{result.m:6}"
        f"{estimate.value:9.3f} ± {estimate.standard_error:<5.3f}{row['mean_cost']:7.0f}"
        f"{row['relative_cost']:6.2f}{row['late_fraction']:7.1%}"
        f"{row['inefficiency']:10.3g}  {row['issues']}"
    )
            k  lag     m         E[x0^2]   cost  rel.   late    ineff.  issues
recipe    222  222  2220    0.996 ± 0.006   2342  1.17   3.8%      43.8  []
lag_1     222    1  2220    1.005 ± 0.012   2339  1.17   2.4%       168  ['variance']
m_2k      222  222   444    1.013 ± 0.019    565  2.53   2.6%       101  []
k_50       50    1   500   -1.268 ± 1.364    619  1.37  95.4%  5.76e+05  ['late']

Every estimate lies within two standard errors of 1: the settings change the variance, not the bias (Settings). The inefficiency compares settings at equal compute, and the recipe’s is the lowest:

  • \(m = 2k\) costs less per replicate, but averages only \(k + 1\) states: its relative cost and its inefficiency are higher than the recipe’s.

  • Lag 1 has the recipe’s \(k\) and \(m\), and about its cost, but a higher inefficiency, and one replicate holds most of the variance of an estimate.

  • \(k = 50\) leaves most pairs to meet after \(k + L\), so that most replicates carry a bias correction: its inefficiency is orders of magnitude above the recipe’s, and the run warns that \(k\) may be too small.

Drawn, with the weight that each setting gives the differences of a late pair, as explained below, and with 95% intervals from 1,000 bootstrap resamples of each run’s replicates:

from telescopic.estimators import correction_coefficients

fig, (left, right) = plt.subplots(1, 2, figsize=(7.5, 3), width_ratios=(1.2, 1))
m = 10 * k
t = np.arange(0, m + 2 * k + 1)
for lag, color in ((1, "C0"), (k, "C1")):
    weight = correction_coefficients(t, k, m, lag, 1)
    left.step(t, weight, where="post", color=color, label=f"$L = {lag}$")
late = k + 1 + 100
left.axvline(late, color="gray", linestyle="--", linewidth=0.8)
left.annotate(r"$\tau = k + 101$", (late + 40, 0.01), color="gray")
left.set(yscale="log", xlabel="$t$", ylabel="weight of $\\Delta_t$")
left.legend(loc="center right")

bootstrap = np.random.default_rng(0)
labels = {"recipe": "recipe", "m_2k": "$m = 2k$", "lag_1": "lag 1", "k_50": "$k = 50$"}
for name, result in results.items():
    values = result.estimate(second_moment).replicates
    costs = result.costs[np.isfinite(result.meeting_times)]
    draws = bootstrap.integers(len(values), size=(1000, len(values)))
    resampled = np.var(values[draws], axis=1, ddof=1) * costs[draws].mean(axis=1)
    low, high = np.percentile(resampled, [2.5, 97.5])
    x, y = rows[name]["relative_cost"], rows[name]["inefficiency"]
    color = "C0" if result.lag == 1 else "C1"
    right.errorbar(x, y, yerr=[[y - low], [high - y]], fmt="o", color=color, capsize=3)
    right.annotate(
        labels[name], (x, y), xytext=(8, 0), textcoords="offset points", va="center",
        color=color,
    )
right.set(yscale="log", xlabel="relative cost", ylabel="inefficiency");
Left: the weight of a difference against t for lag 1, a ramp from k + 1 that reaches 1 at m + 1, and for lag k, a staircase that rises every k steps from 2k and is flat from m + k, on a log scale, with a late pair's meeting time marked. Right: the inefficiency on a log scale against the relative cost for four runs, the recipe lowest, then m = 2k and lag 1, and k = 50 far above the others.

Left: the weight \(v_t/(m - k + 1)\) of the difference \(\Delta_t\) against \(t\) at the recipe’s \(k\) and \(m = 10k\), on a log scale, for \(L = 1\), a ramp, and for \(L = k\), a staircase; the dashed line marks a late pair that meets at \(\tau = k + L + 100\) with \(L = 1\), whose differences up to \(\tau - 1\) enter its estimate with these weights. Right: the inefficiency, on a log scale, against the relative cost, of the four runs above, with 95% bootstrap intervals, colored by lag as on the left. The recipe’s is the lowest.

The variance of lag 1 comes from its late pairs. A difference \(\Delta_t\) enters a replicate’s estimate with the weight \(v_t/(m - k + 1)\) of the theory, and \(v_t\) grows by one every \(L\) steps from \(t = k + L\) to \(t = m + L\). A pair that meets at \(\tau = k + L + 100\) carries weights up to \(100/(m - k + 1)\) with lag 1, and \(1/(m - k + 1)\) with lag \(k\):

spreads = {}
for name in ("recipe", "lag_1"):
    result = results[name]
    values = result.estimate(second_moment).replicates
    late = result.meeting_times - result.lag > result.k
    spreads[name] = np.var(values[late], ddof=1) / np.var(values[~late], ddof=1)
    print(f"{name}: {late.sum()} late pairs, with {spreads[name]:.3g} times the others' variance")
recipe: 19 late pairs, with 0.941 times the others' variance
lag_1: 12 late pairs, with 120 times the others' variance

With lag 1, the estimates of the late pairs vary far more than the others’; with lag \(k\), about as much.

Distance to stationarity

The lag does not change the law of \(X_t\), so the runs with lag 1 and lag \(k\) bound the same distance between it and the target (Theory), at about the same cost:

t = np.arange(2 * k)
fig, ax = plt.subplots(figsize=(5, 3.5))
bounds = {"lag 1": results["lag_1"].tv_bound(t), f"lag {k}": recipe.tv_bound(t)}
colors = {}
for label, (bound, error) in bounds.items():
    shown = bound > 0
    (line,) = ax.plot(t[shown], bound[shown], label=label)
    colors[label] = line.get_color()
ax.axvline(k, color="gray", linestyle="--", label="$k$")
ax.set(yscale="log", xlabel="$t$", ylabel=r"TV bound on $X_t$")
# Two standard errors where the bound is below its cap of 1, reaching the bottom of
# the axis where the lower edge is not positive.
bottom = ax.get_ylim()[0]
for label, (bound, error) in bounds.items():
    lower, upper = np.clip(bound - 2 * error, bottom, 1), np.minimum(bound + 2 * error, 1)
    below = (bound > 0) & (bound < 1)
    ax.fill_between(t, lower, upper, where=below, color=colors[label], alpha=0.3, linewidth=0)
ax.set_ylim(bottom=bottom)
ax.legend();
Two lines on a logarithmic scale, one for lag 1 and one for lag k, each falling from 1 as t grows inside a shaded band, with a dashed vertical line at k.

The estimated upper bound on the total variation distance between the law of \(X_t\) and the target, from the run with lag 1 and the run with lag \(k\), each with a band of two standard errors where it is below 1, with \(k\) dashed.

lag_one, lag_k = results["lag_1"].tv_bound([k])[0][0], recipe.tv_bound([k])[0][0]
print(f"at t = k: lag 1, {lag_one:.3f}; lag {k}, {lag_k:.3f}")
at t = k: lag 1, 0.716; lag 222, 0.038

At \(t = k\) the lag-1 bound is far larger than the lag-\(k\) bound: lag \(k\) gives the sharper bound, as in Biswas, Jacob & Vanetti (2019).

Partial “auto”

Any of k, m and lag can be given, with the others left at "auto", by the rule that Settings states. With k given:

given_k = telescopic.CoupledSampler(
    example.log_prob, example.initial, vectorize=True, kernel=sampler.kernel, rng=4
)
given_k.run(20, k=300)
print("pilot:", given_k.pilot)
given_k.settings
pilot: None
Settings(k=300, m=3000, lag=300, thin=1, max_iter=None, store=True, keep=None)

With m given:

given_m = telescopic.CoupledSampler(
    example.log_prob, example.initial, vectorize=True, kernel=sampler.kernel, rng=5
)
given_m.run(20, m=5000)
print(f"pilot pairs: {len(given_m.pilot)}; k = {given_m.settings.k}, against {k} above")
given_m.settings
pilot pairs: 100; k = 234, against 222 above
Settings(k=234, m=5000, lag=234, thin=1, max_iter=None, store=True, keep=None)

This sampler’s pilot and the first one chose different values of \(k\): \(k\) varies between pilots of 100 pairs. Another value on a later run of a sampler raises:

try:
    given_k.run(20, k=100)
except ValueError as error:
    print(error)
k was 300 in the earlier runs; a sampler keeps its settings, so start a new one for k=100