Neal’s funnel: a hard case¶
A target whose scale changes from one region to another is hard for every kernel with a fixed step, and coupled chains show it: their pairs meet slowly or not at all, and the run warns. This page runs the random walk and HMC on Neal’s funnel, reads what the meeting times and the warnings say, and then removes the difficulty by changing the coordinates of the target. Warnings and errors explains each warning, and Troubleshoot chains that do not meet is indexed by what a run shows.
The target¶
telescopic.examples.funnel() is the funnel of Neal (2003) in 10 dimensions: the
point is \((v, x_1, \dots, x_9)\), with \(v \sim \mathcal N(0, 9)\) and, given \(v\), each
\(x_i \sim \mathcal N(0, e^v)\). The standard deviation of the \(x_i\) is \(e^{v/2}\): about 20
at \(v = 6\), the mouth of the funnel, and 0.05 at \(v = -6\), its neck. A step that suits
one end is 400 times too large or too small at the other. The test functions are \(v\),
\(v^2\) and the indicator of the neck, \(v < -3\), whose exact expectations are 0, 9 and
\(\Phi(-1)\). The default initial distribution of the example is a Gaussian with the
target’s mean and covariance.
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
import telescopic
from telescopic import examples
funnel = examples.funnel()
truth = np.array([0.0, 9.0, stats.norm.cdf(-1)])
def moments_of_v(theta):
v = theta[:, 0]
return np.column_stack([v, v**2, v < -3])
print("exact E[v], E[v^2] and P(v < -3):", truth.round(4))
exact E[v], E[v^2] and P(v < -3): [0. 9. 0.1587]
Pilot pairs of the random walk and HMC¶
telescopic.CoupledSampler.meeting_times() tunes the kernel, then runs pairs with
lag 1 until they meet or reach a cap, as the meeting-time pilot of a run
does (The automatic pipeline), and returns
their meeting times, inf for a pair still unmet at the cap. The two samplers have the
same seed, so their tuning pilots and their pairs start from the
same points. An iteration of HMC evaluates the gradient n_steps times, so its pairs get
a smaller cap and fewer pairs, to keep this page within its time:
def pilot(log_prob, grad, initial, kernel, n, cap):
sampler = telescopic.CoupledSampler(
log_prob, initial, grad=grad, vectorize=True, kernel=kernel, rng=0
)
tau = sampler.meeting_times(n, max_iter=cap)
met = tau[np.isfinite(tau)]
print(f"{sampler.kernel}")
print(
f" {np.isinf(tau).sum()} of {n} pairs unmet at {cap}; median of the others "
f"{np.median(met):.0f}, largest {met.max():.0f}"
)
return tau
# The kernel, the number of pairs and the cap of each pilot.
funnel_pilots = {"random walk": ("rwmh", 200, 20_000), "HMC": ("hmc", 50, 2_000)}
funnel_tau = {
name: pilot(funnel.log_prob, funnel.grad, funnel.initial, *settings)
for name, settings in funnel_pilots.items()
}
RandomWalk(cov=<10x10>, scale=None, coupling='reflection')
0 of 200 pairs unmet at 20000; median of the others 150, largest 14212
HMC(step_size=0.25891029922451336, n_steps=4, cov=<10x10>, jitter=0.5, meeting_weight=0.05, meeting_scale=0.001)
36 of 50 pairs unmet at 2000; median of the others 476, largest 1605
ConvergenceWarning: pilot pair 146 has not met after 10000 iterations, and the run waits for it; the meeting times may be heavy-tailed, so look at the kernel and the initial distribution
Of the 200 pairs of the random walk, 0 were unmet at the cap; the others met after a median of 150 iterations, and the slowest after 14,212. A pair slow to meet emits the slow warning as it runs
(Slow pairs). HMC, with the step size that its
tuning chose, left 36 of 50 pairs unmet at the cap. Its step was
tuned toward an acceptance rate on chains in the bulk of the target, which is no
guarantee that coupled chains come together
(When the automatic step fails).
The automatic settings take the burn-in k from these meeting times
(telescopic.tuning.choose_k()), and a run raises the error below when too many
pilot pairs are unmet:
for name, tau in funnel_tau.items():
try:
k = telescopic.tuning.choose_k(tau)
print(f"{name}: k = {k}, so m = 10k = {10 * k}")
except ValueError as error:
print(f"{name}: ValueError: {error}")
random walk: k = 5759, so m = 10k = 57590
HMC: ValueError: quantile must be in (0, 1 - 1/R0] = (0, 0.98] for 50 pilot pairs, not 0.99; run more pilot pairs for a higher quantile
For the random walk, the recipe sets $k$ = 5,759 and $m$ = 57,590, so that each replicate would run at least 57,590 iterations. For HMC, k cannot be chosen, and telescopic.sample would raise this error after its pilot. A replicate runs at least \(m\) iterations, and
k cannot be chosen explains the error. A
step size checked on pilot pairs is the usual remedy
(Checking a step size), but on the funnel any
fixed step is too large in the neck or too small in the mouth.
A run within a budget¶
To see what a run reports, the random walk runs 500 replicates with settings given by hand, far shorter than the recipe’s: \(k = L = 200\) and \(m = 2000\), with a cap of 20,000 iterations on each pair. The warnings print below the cell:
walk = telescopic.CoupledSampler(funnel.log_prob, funnel.initial, vectorize=True, rng=0)
budget = walk.run(500, k=200, lag=200, m=2000, max_iter=20_000)
ConvergenceWarning: replicate 40 has not met after 20000 iterations; the meeting times may be heavy-tailed, so look at the kernel and the initial distribution
ConvergenceWarning: 1 of 500 pairs reached max_iter = 20000 without meeting and are excluded, which biases the estimates; run a new sampler with a larger max_iter, or none
ConvergenceWarning: 60% 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: replicate 234 holds 63% of the variance of the mean of x8: heavy tails or rare excursions make the error bars unreliable; check the initial distribution, and look for a mode that the other replicates missed
estimate = budget.estimate(moments_of_v)
print("E[v], E[v^2], P(v < -3):", estimate)
print("exact values:", truth.round(4))
print("warnings:", [issue.kind for issue in telescopic.diagnostics.issues(budget)])
E[v], E[v^2], P(v < -3): Estimate([2.96495 ± 0.89, 13.7553 ± 5.8, 0 ± 0], R=499)
exact values: [0. 9. 0.1587]
warnings: ['censored', 'late', 'variance', 'slow']
The estimate of $E[v]$ is 3.3 standard errors from 0, and no atom of any replicate lies below $v = -3$, so the probability of the neck is estimated as 0, with a standard error of 0. The run emits 4 warnings: censored, late, variance and slow. The largest share of one replicate in the variance of an estimate is 0.63, for the mean of x8, held by replicate 234, whose pair met at $\tau$ = 6,757, with 4 of the 500 pairs meeting later or not at all, after $k + L$ = 400, so its estimate carries a bias correction. Pairs that reached the cap, left out of the estimates: 1. Each warning’s entry in
Warnings and errors gives its meaning and remedy.
The warnings name symptoms; the cause here is a kernel whose single scale cannot serve
both ends of the funnel.
A change of coordinates¶
Write \(x_i = e^{v/2} z_i\). Under the target, \(z_i \sim \mathcal N(0, 1)\) independently of \(v\), so in the coordinates \((v, z_1, \dots, z_9)\) the target is the Gaussian \(\mathcal N(0, 9) \times \mathcal N(0, I)\), whose scale is the same everywhere. This is the non-centered parameterization of the funnel. The law of \(v\) does not change, and an expectation of a function \(h\) of the original point is that of \(h(v, e^{v/2} z)\) in the new coordinates. The log-density and its gradient, up to a constant, and an initial distribution twice as wide as the new target in each coordinate:
def log_prob(theta):
v, z = theta[:, 0], theta[:, 1:]
return -(v**2) / 18 - 0.5 * np.sum(z**2, axis=1)
def grad(theta):
gradient = -theta.copy()
gradient[:, 0] /= 9
return gradient
initial = telescopic.initial.Normal(np.zeros(10), 4 * np.diag([9.0] + [1.0] * 9))
noncentered_tau = {
"random walk, new coordinates": pilot(log_prob, grad, initial, "rwmh", 200, 20_000),
"HMC, new coordinates": pilot(log_prob, grad, initial, "hmc", 100, 5_000),
}
RandomWalk(cov=<10x10>, scale=None, coupling='reflection')
0 of 200 pairs unmet at 20000; median of the others 48, largest 172
HMC(step_size=0.8234897154796113, n_steps=2, cov=<10x10>, jitter=0.5, meeting_weight=0.05, meeting_scale=0.001)
0 of 100 pairs unmet at 5000; median of the others 25, largest 70
Every pair of both kernels met, the slowest after 172
iterations. The survival functions of \(\tau - 1\), the meeting time less the lag
(Meeting times and distance to stationarity), drawn by
telescopic.plotting.survival() from each pilot’s times, its lag of 1 and its cap,
put the four pilots side by side:
from telescopic import plotting
fig, ax = plt.subplots(figsize=(6, 3.8))
caps = {name: cap for name, (_, _, cap) in funnel_pilots.items()}
for label, tau in {**funnel_tau, **noncentered_tau}.items():
# Every pair in the new coordinates met, so only the funnel's pilots need their cap.
plotting.survival(tau, 1, ax, max_iter=caps.get(label), label=label)
ax.set(xscale="log", ylabel=r"$P(\tau - 1 > t)$")
ax.legend(fontsize=9);
The survival function \(P(\tau - 1 > t)\) of the pilots’ meeting times less the lag, against \(t\), for the random walk and HMC on the funnel and in the new coordinates. A curve that ends above 0 ends at the cap less 1, at the fraction of pairs unmet at the cap.¶
The run¶
The automatic settings, with the default random walk, in the new coordinates:
result = telescopic.sample(
log_prob,
initial,
1000,
vectorize=True,
names=["v"] + [f"z{i}" for i in range(1, 10)],
rng=0,
)
noncentered = result.estimate(moments_of_v)
print("E[v], E[v^2], P(v < -3):", noncentered)
errors = (noncentered.value - truth) / noncentered.standard_error
print("standard errors from the exact values:", errors.round(1))
result.summary()
E[v], E[v^2], P(v < -3): Estimate([0.00640164 ± 0.015, 8.96606 ± 0.048, 0.158033 ± 0.0015], R=1000)
standard errors from the exact values: [ 0.4 -0.7 -0.4]
| mean | standard_error | std | q16 | q50 | q84 | |
|---|---|---|---|---|---|---|
| v | 0.00640164 | 0.0150125 | 2.99437 | -2.97566 | 0.00621797 | 2.98232 |
| z1 | -0.00234301 | 0.00499613 | 0.998297 | -0.993043 | -0.00125247 | 0.991911 |
| z2 | 0.00339074 | 0.00552456 | 0.996736 | -0.990818 | 0.00356505 | 0.995779 |
| z3 | -0.00640226 | 0.00533112 | 0.998706 | -1.00247 | -0.00463168 | 0.986239 |
| z4 | 0.00392348 | 0.00560629 | 0.99541 | -0.985389 | -0.00114043 | 0.995432 |
| z5 | -0.00450175 | 0.00566096 | 1.0009 | -1.00257 | -0.00683415 | 0.988884 |
| z6 | 0.00239382 | 0.00596065 | 0.999166 | -0.996358 | 0.00602363 | 0.996324 |
| z7 | 0.000597921 | 0.00532363 | 1.0029 | -0.999276 | 0.00108219 | 0.996946 |
| z8 | 0.00902301 | 0.00598806 | 0.999113 | -0.981721 | 0.00693542 | 1.00901 |
| z9 | -0.00382124 | 0.00512468 | 0.999767 | -0.999419 | -0.00588011 | 0.994622 |
- R = 1000, k = 124, m = 1240, lag = 124, thin = 1
- kernel: RandomWalk(cov=<10x10>, scale=None, coupling='reflection')
- meeting times: median 176, 90% 226, 99% 284, max 360; censored 0
- tail index of the meeting times: 4.7
- cost per replicate: 1298 kernel applications, 0.00175 s; relative cost 1.16
- pairs meeting after k + lag: 4.4% (at most 5.6% at 95%)
- largest share of one replicate in a variance: 4%, for the variance of z5
All three estimates lie within three standard errors of the exact values.
The run emits no warning. The largest share of one replicate in the variance of an estimate is 0.04, for the variance of z5, held by replicate 950, whose pair met at $\tau$ = 144, with 910 of the 1000 pairs meeting later or not at all, by $k + L$ = 248, so its estimate carries no bias correction. plot_marginals() draws the marginal of \(v\) from
each run as a signed histogram with boxes of two standard errors
(Plot a result), here against its exact density:
grid = np.linspace(-10, 10, 400)
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), sharey=True)
for ax, (title, run) in zip(axes, (("funnel, budget run", budget), ("new coordinates", result))):
run.plot_marginals(0, bins=25, axes=[ax])
ax.plot(grid, stats.norm.pdf(grid, scale=3), color="0.45", label="exact $N(0, 9)$")
ax.set(title=title, xlim=(-10, 10))
axes[1].legend(fontsize=9);
The marginal of \(v\) estimated by the random walk on the funnel within a budget (left) and by the run in the new coordinates (right), as signed histograms with boxes of two standard errors, against the exact \(\mathcal N(0, 9)\).¶
No warning names the funnel’s changing scale as the cause: the warnings report symptoms, such as long meeting times, censored pairs or a dominant replicate, and here those of the budget run pointed to the kernel. An empty list of warnings means only that none of their conditions holds (Warnings and errors).