Choose a kernel¶
A kernel moves one chain and leaves the target invariant. Its coupling moves a pair of
chains so that each chain, on its own, moves by the kernel, and so that the two can
become equal (Theory). Each kernel of
telescopic.kernels comes with its coupling. The argument kernel of
telescopic.sample() and telescopic.CoupledSampler takes a kernel, or the
string that names it. In the coupling column, a maximal coupling makes two draws
equal with the largest probability that their two distributions allow. A
reflection-maximal coupling does so for two Gaussians with one covariance, and when
the draws differ, the offset of the second from its mean mirrors that of the first. A
common uniform, momentum or random number is one draw that both chains use:
Kernel |
String |
Needs |
Coupling |
|
|---|---|---|---|---|
|
|
log-density |
reflection-maximal proposals, common uniform |
|
|
|
log-density, gradient |
reflection-maximal proposals, common uniform |
|
|
|
log-density, gradient |
common step, momentum and uniform; reflection-maximal meeting step |
|
|
|
log-density |
common proposal and uniform |
|
|
none |
full conditionals |
per block: maximal, common random numbers, or both |
nothing |
|
none |
what its components need |
common component |
its components’ parameters |
"auto", the default, is the random walk even when a gradient is given, as grad or
log_prob_and_grad.
Choosing a kernel¶
The random walk, the default, needs only the log-density and has no step size to tune.
MALA and HMC need the gradient, as
gradorlog_prob_and_grad. A step evaluates the log-density and the gradient once (MALA) orn_stepstimes (HMC). Their automatic step sizes can fail to couple (When the automatic step fails). A wrong gradient leaves them exact but slow, so a sampler built with one compares the gradient with differences of the log-density first (Checking the gradient).The independence kernel suits a target that a Student-\(t\) approximates well, such as a posterior close to Gaussian.
Gibbs suits models whose full conditionals are known, such as conjugate hierarchical models.
Coupling does not make a kernel mix faster (Theory): a kernel that mixes slowly meets slowly. To compare kernels on a target, compare their inefficiency, the variance of a replicate’s estimate times the cost of a replicate (Settings). Gradients compares the random walk, MALA and HMC on a Gaussian.
Tuning¶
Parameters left as None are tuned from four adaptive Metropolis chains, the
tuning pilot (Settings); parameters given are kept.
telescopic.kernels.Kernel.tune() returns a tuned copy and the pilot’s report. The
sampler calls it once, before anything else runs, and keeps the tuned kernel:
import numpy as np
from scipy import stats
import telescopic
from telescopic import examples, kernels
gaussian = examples.gaussian(10) # N(0, S), S_ij = 0.9^|i - j|, from N(0, 4I)
target = telescopic.Target(gaussian.log_prob, grad=gaussian.grad, vectorize=True)
tuned, report = kernels.HMC().tune(target, gaussian.initial, rng=0)
tuned
HMC(step_size=0.8240974702326241, n_steps=2, cov=<10x10>, jitter=0.5, meeting_weight=0.05, meeting_scale=0.001)
The four chains share one proposal covariance, and on a target with well-separated modes they can all settle in one mode during their descent, before they reach it: on the two-mode target of A tuned proposal that covers one mode, started from \(\mathcal N(0, 100I)\), in 15 of 20 runs in 10 dimensions and 18 of 20 in 32. The tuned parameters then describe that mode alone, and the chains’ \(\hat R\) stays near 1, so the warning about disagreeing tuning chains (Disagreeing tuning chains) is silent.
Setup of these runs: telescopic at commit d014ac1, Python 3.13.18, NumPy 2.5.4 and SciPy
1.18.1, OMP_NUM_THREADS=1, on an Intel Xeon processor at 2.10 GHz with 4 logical cores.
Random walk¶
telescopic.kernels.RandomWalk proposes \(x' = x + \lambda Cz\), with \(CC^\top\) =
cov, \(\lambda\) = scale and \(z \sim \mathcal N(0, I)\), and accepts when
\(\log u < \log\pi(x') - \log\pi(x)\).
coupling="reflection", the default, draws the two proposals from the reflection-maximal coupling of their Gaussians and decides both acceptances with one uniform, as in Jacob, O’Leary & Atchadé (2020) and O’Leary (2021). A coupled step evaluates the log-density at most twice per pair, once when the proposals coincide.coupling="maximal"uses the rejection maximal coupling with independent residuals, whose meeting times grow exponentially with the dimension (Jacob, O’Leary & Atchadé 2020, §4.2); it is there for comparison.couplingalso takes the coupling objectstelescopic.couplings.Reflection()andtelescopic.couplings.Maximal(), which give the same numbers as their names. The attributecouplingreturns what was given and cannot be reassigned.tunesetscovto the covariance of the pilot chains.scaledefaults to \(2.38/\sqrt d\), the optimal scale of Roberts, Gelman & Gilks (1997) for a Gaussian target of covariancecov, and is not tuned.
MALA¶
telescopic.kernels.MALA needs the gradient, as grad or log_prob_and_grad.
It proposes
\(x' = x + \tfrac{\epsilon^2}{2}\Sigma\nabla\log\pi(x) + \epsilon Cz\), with
\(\Sigma = CC^\top\) = cov and \(\epsilon\) = step_size, and accepts by the
Metropolis-Hastings ratio, which includes the proposal densities.
The coupled step draws the two proposals from the reflection-maximal coupling of their distributions, which share the covariance \(\epsilon^2\Sigma\), and shares the uniform, as in Jacob, O’Leary & Atchadé (2020, §4.4). It is MALA’s only coupling,
telescopic.couplings.Reflection.tunesetscovto the covariance of the pilot chains, thenstep_sizeby dual averaging toward the acceptance rate of 0.574 that Roberts & Rosenthal (1998) found optimal, on four chains started from the pilot’s last states.
HMC¶
telescopic.kernels.HMC needs the gradient, as grad or log_prob_and_grad.
Each step applies one of two components,
chosen by a uniform:
with probability \(1 - \gamma\), \(\gamma\) =
meeting_weight, a leapfrog trajectory ofn_stepssteps, withcovas the inverse mass matrix. The size of its steps is drawn for each trajectory, uniformly between \((1 - j)\epsilon\) and \((1 + j)\epsilon\), with \(\epsilon\) =step_sizeand \(j\) =jitter, 0.5 by default;jitter=0gives the fixed step \(\epsilon\);with probability \(\gamma\), the meeting step: a random-walk step with proposal covariance \(\sigma^2\Sigma\), \(\sigma\) =
meeting_scale.
Coupled chains take the same component. Their trajectories share the step, the
momentum and the uniform, which can bring the chains together but never makes them
equal. The jitter keeps a step from staying on a resonance of the leapfrog, where
trajectories with a fixed step do not bring the chains closer
(When the automatic step fails).
Each trajectory leaves the target invariant, and the step does not depend on the
state, so the jittered kernel does too. The meeting
step couples them by the reflection-maximal coupling, which can make them equal once
they are within about meeting_scale of each other in the coordinates that cov
whitens. This is the construction of Heng & Jacob (2019), whose meeting step is not
whitened and uses the rejection maximal coupling.
Two chains of telescopic.kernels.HMC on a standard normal target in two
dimensions, with cov the identity, jitter=0, 5 leapfrog steps of 0.2 and
meeting_scale=0.5, where the default is 0.001, so that the meeting step can be
seen. \(X\), in magenta, and \(Y\), in teal, take three trajectories with the same
momentum, each drawn with its leapfrog points: the chains come closer at each one but do
not become equal. Then a meeting step, a random-walk step of scale \(\sigma\) =
meeting_scale around each chain, drawn as dashed circles and coupled by the
reflection-maximal coupling, moves both chains to one point, in the ink of met chains.
The end of each trajectory and the point of the meeting are those of the package’s
coupled step.¶
tune sets cov to the covariance of the pilot chains, then step_size by dual
averaging of the jittered trajectories alone toward an acceptance rate of 0.8. n_steps
defaults to \(\lceil 1/\epsilon\rceil\), a trajectory of length about 1 in whitened
coordinates at the step \(\epsilon\), and at most 1,000; the jitter leaves it fixed, so
the length of a trajectory varies between \(1 - j\) and \(1 + j\) times that.
Independence¶
telescopic.kernels.Independence proposes \(x' \sim q\) whatever the current
state, and accepts when
\(\log u < [\log\pi(x') - \log q(x')] - [\log\pi(x) - \log q(x)]\). The weight \(\pi/q\)
is 0 wherever \(\pi\) is 0, even where \(q\) is 0 too, so a chain at zero density accepts
any proposal of finite density, as the random walk does. A proposal where \(q\) is 0 is
rejected, even where \(\pi\) is not: sample drew a point that log_density gives no
mass, such as a draw clipped onto the edge of an open support.
The coupled step gives both chains the same proposal and the same uniform, so a pair meets when both accept. It is a maximal coupling of the kernel (O’Leary, Wang & Jacob 2021),
telescopic.couplings.Shared.The chains’ states keep \(\log q\) at their positions with the point at which it was computed, and use it only where that point is the position bit for bit, so that a chain moved by another kernel of a mixture gets a fresh value. A step and a coupled step evaluate
log_densityonce, at the proposals and at the states without a valid value: usually \(n\) rows, where without the cache they were \(2n\) and \(3n\). Wherelog_densitygives a point the same value in any batch, asMultivariateTdoes, no number changes.The attribute
proposalreturns the distribution given and cannot be reassigned; tuning builds a new kernel.proposalis atelescopic.kernels.MultivariateT, a Student-\(t\) with locationmean, scale matrixcovanddfdegrees of freedom, a positive integer (df=Nonegives a Gaussian). A proposal of your own hassample(draws)andlog_density(x), the normalized density of whatsampledraws, positive whereversamplecan land; alog_densitythat returns NaN or+infraisesValueErrorwith the point.tunesets a Student-\(t\) with 5 degrees of freedom, located at the pilot’s mean, with the pilot’s covariance as scale matrix. The report’smax_weight_ratiois the largest weight \(\pi/q\) among the pilot’s states, relative to their median; a large value announces heavy-tailed meeting times.A tuned proposal covers only the modes that the tuning chains reached. On a target with well-separated modes, both chains of a pair then accept proposals in that mode and meet within a few tens of steps, and the estimates can be confidently wrong, in some runs without any warning: fast meeting says nothing about a region the proposal does not cover (A tuned proposal that covers one mode). When the modes are known, give
proposalexplicitly so that it covers them all.
The proposal must be positive wherever the target is. The kernel never moves a chain to
where \(q\) is 0, so, used alone, a proposal that misses part of the target’s support
never reaches that part, and the estimates are biased from any start, without a
warning. On \(\mathcal N(0, 1)\) with
a proposal uniform on \((-2, 2)\), 500 replicates started in \((-1, 1)\) estimate
\(E[x^2] = 1\) as 0.778 with a standard error of 0.0093, which agrees within its error
with the value 0.774 of \(\mathcal N(0, 1)\) restricted to \((-2, 2)\). A chain started
where the target is positive and the proposal is 0 rejects every proposal: started at
3, the same run reports \(E[x] = 3\) with a standard error of 0. Inside a
telescopic.kernels.Mixture with a kernel that reaches the rest of the support,
chains do arrive at such points: the independence component rejects every proposal from
there, which is the rule that keeps the target invariant, and the other kernel moves
them on.
The meeting times have geometric tails only when the weights \(\pi/q\) are bounded, so the proposal needs tails at least as heavy as the target’s. With unbounded weights the sampler is not geometrically ergodic (Mengersen & Tweedie 1996): a chain that reaches a point of weight \(w\), for \(\pi\) and \(q\) normalized, stays there for \(w\) steps or more on average. The replicates that carry the bias correction for the region where \(\pi/q\) is large are then too rare to occur in a run, and the variance of the estimates can be infinite. A run usually gives that region too little mass, with error bars that are too small and often without a warning.
On the target Exp(1), whose mean is 1, with a normal proposal \(\mathcal N(1, 1)\) floored at 0, a chain stays for 51 steps on average at \(x = 5\) and for 1,671 at \(x = 6\). Of 200 runs of 1,000 replicates started in \((0, 2)\), the median estimate of the mean was 0.970, 72.5% of the estimates were more than two standard errors below 1 and none was that far above, and 142 runs raised no warning, 135 of them with an estimate that low. With a Student-\(t\) proposal with 3 degrees of freedom in place of the normal, whose weights are bounded, the median was 0.999 and 1.5% of the estimates were that low.
Setup of these runs: telescopic at commit d014ac1, Python 3.13.18, NumPy 2.5.4 and SciPy
1.18.1, OMP_NUM_THREADS=1, on an Intel Xeon processor at 2.10 GHz with 4 logical cores.
Gibbs¶
telescopic.kernels.Gibbs updates blocks of coordinates in turn, each drawn from
its full conditional. conditional(x, b) receives a read-only point x of shape (d,)
and a block number b, and returns the distribution of block b given the other
coordinates of x: an object with rvs(random_state=...) and a normalized logpdf, or
logpmf, such as a frozen SciPy distribution. blocks lists index arrays that
partition the coordinates 0, ..., d - 1. The coupled step couples each block’s two
conditionals:
coupling="maximal", the default: the rejection maximal coupling. Withetabelow 1 the meeting probability is capped ateta, and the number of draws it takes has the bounded variance of Atchadé & Jacob (2024, Algorithm 2).coupling="crn": common random numbers. For a block of one coordinate whose two conditionals haveppf, one uniform goes through both. For any other block, each chain draws from its own conditional withrvs, from generators in the same state, so each keeps its conditional’s law whatever its type. Common random numbers can bring the chains together, but make them equal only by rounding;"two-scale"adds the maximal coupling.coupling="two-scale": common random numbers for pairs farther apart thanthresholdat the start of a sweep, and the maximal coupling for the others, as in Biswas, Bhattacharya, Jacob & Johndrow (2022).
Where the two chains agree on every coordinate outside a block, both get the same draw.
Under "crn", the two draws of a block drawn with rvs are close when rvs reads a
fixed count of numbers from the generator and maps them smoothly in the conditional’s
parameters. A normal block drawn as
mean + np.linalg.cholesky(cov) @ random_state.standard_normal(k), or with
random_state.multivariate_normal(mean, cov, method="cholesky"), does: from
generators in the same state, draws of two normals of 3 coordinates whose covariances
differ in shape by 1% are 0.0056 apart on average, against 2.2 for independent draws.
NumPy’s default method, a singular value decomposition of the covariance, which SciPy’s
multivariate_normal calls, does not: its signs and order can change between nearby
covariances, so the same draws are 0.063 apart on average, and for covariances near a
multiple of the identity, 2.42 apart, as far as independent ones. In a robust
regression whose block of 3 coefficients has a normal conditional, pairs meet after a
median of 147.1 sweeps, averaged over 5 seeds, with NumPy’s Cholesky method, as many as
with the Cholesky factor written out, and 205.4 with SciPy’s multivariate_normal.
Setup of these runs: telescopic at commit 9be9024, Python 3.13.18, NumPy 2.5.4 and SciPy
1.18.1, OMP_NUM_THREADS=1, on an Intel Xeon processor at 2.10 GHz with 4 logical cores.
A Gibbs kernel needs no log-density, so log_prob can be None, and has nothing to
tune:
rho = 0.8
def conditional(x, block):
# One coordinate given the other: a standard bivariate normal, correlation rho.
return stats.norm(rho * x[1 - block], np.sqrt(1 - rho**2))
gibbs = kernels.Gibbs(conditional, blocks=[[0], [1]])
init = telescopic.initial.Normal([0.0, 0.0], [4.0, 4.0])
sampler = telescopic.CoupledSampler(None, init, kernel=gibbs, rng=0)
np.quantile(sampler.meeting_times(), [0.5, 0.99]) # of 100 pilot pairs' meeting times
array([ 3. , 10.01])
A sweep calls conditional once per chain and block, in Python, so building the
distributions can dominate its cost. A small class with only the methods used is faster
than a frozen SciPy distribution, as in telescopic.examples.pumps(). Worked
example: Gibbs.
Proposals and coupling objects¶
The random walk, MALA and the independence kernel are one Metropolis-Hastings kernel,
telescopic.kernels.MetropolisHastings, with three proposals. Each proposal draws
\(x' \sim q(\cdot \mid x)\) and gives the log acceptance ratio
\(\log\pi(x') - \log\pi(x) + \log q(x \mid x') - \log q(x' \mid x)\), and a coupling
object draws the proposals of both chains of a pair. MetropolisHastings(proposal, coupling) raises ValueError unless the coupling supports the proposal. The couplings
of telescopic.couplings support these proposals, matched by their exact class, so
that a subclass whose draws differ from its parent’s is refused rather than coupled as
its parent:
Coupling |
Proposal |
The kernel it gives |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Here \(B\) is a lower-triangular factor of the proposal covariance \(BB^\top\), and inverse
is \(B^{-1}\). These are the compositions with a published analysis (Jacob, O’Leary &
Atchadé 2020, §4.1, §4.4 and Algorithm 2; O’Leary, Wang & Jacob 2021). A kernel with a
proposal of another kind is written as a kernel of its own, with its own coupling
(Write a custom kernel).
from telescopic import couplings
cov = np.eye(2)
chol = np.linalg.cholesky(cov)
walk = kernels.RandomWalkProposal(chol, np.linalg.inv(chol))
kernels.MetropolisHastings(walk, couplings.Maximal())
MetropolisHastings(RandomWalkProposal(factor=<2x2>), Maximal())
Mixtures¶
telescopic.kernels.Mixture applies at each step one of its kernels, chosen by
a uniform with probabilities weights. Coupled chains take the same component and its
coupling. The choice never depends on the states, which keeps each chain’s moves those
of the mixture (Atchadé & Jacob 2024, §4.2). tune tunes the untuned components on one
pilot, and the start of the chains checks that every component works in their
dimension. HMC is a mixture of its trajectories and its meeting step.