Gradients: MALA and HMC¶
With the gradient of the log-density, telescopic can run the Metropolis-adjusted Langevin
algorithm (telescopic.kernels.MALA) and Hamiltonian Monte Carlo
(telescopic.kernels.HMC), whose proposals follow the gradient. On targets like
the Gaussian below, their pairs of chains meet sooner than those of random-walk
Metropolis. The kernels guide describes each kernel and its
coupling.
A Gaussian in 50 dimensions¶
telescopic.examples.gaussian() gives a Gaussian whose neighboring coordinates have
correlation 0.9, with its log-density, its gradient and the initial distribution
\(\mathcal N(0, 4I)\). Its functions take batches of points, hence vectorize=True. The
three kernels run with the same seed, so their pairs start from the same points. The
random walk’s runs are long, so it averages every tenth state (thin=10), which stores
about a tenth of the atoms; thinning does not shorten a run (Theory).
import numpy as np
import telescopic
from telescopic import examples
gaussian = examples.gaussian(50)
results = {}
for kernel in ("rwmh", "mala", "hmc"):
results[kernel] = telescopic.sample(
gaussian.log_prob,
gaussian.initial,
grad=gaussian.grad,
vectorize=True,
kernel=kernel,
thin=10 if kernel == "rwmh" else None,
rng=1,
)
For each kernel: the median meeting time of the 100 pilot pairs, which run with lag 1
(Result.pilot); the burn-in k, their 99% quantile minus 1; the relative cost
(Theory); and the evaluations of the log-density and of its gradient
per replicate in the main run.
print("kernel median tau k relative cost log_prob grad")
for kernel, result in results.items():
print(
f"{kernel:6} {np.median(result.pilot):10.0f} {result.k:4} "
f"{result.diagnostics()['relative_cost']:13.3f} "
f"{result.n_log_prob / result.n_replicates:8.0f} "
f"{result.n_grad / result.n_replicates:5.0f}"
)
kernel median tau k relative cost log_prob grad
rwmh 877 1842 1.170 19396 0
mala 18 39 1.163 409 409
hmc 54 122 1.164 2496 2496
With gradients the pairs meet sooner, and k, the lag and the run length m shrink with
the meeting times, since the lag equals k and m = 10k. The relative cost is about the
same for the three kernels. They differ in the steps a replicate takes and in what a step
evaluates. MALA evaluates the log-density and its gradient once per chain and step, HMC
at each leapfrog step of its trajectories, n_steps of them:
results["hmc"].kernel
HMC(step_size=0.5357005695066966, n_steps=2, cov=<50x50>, jitter=0.5, meeting_weight=0.05, meeting_scale=0.001)
A standard error of 0.01 needs \(v/0.01^2\) replicates, with \(v\) one replicate’s variance averaged over the 50 means:
print("kernel replicates log_prob")
evaluations = {}
for kernel, result in results.items():
v = result.n_replicates * np.mean(result.mean().standard_error**2)
evaluations[kernel] = v / 0.01**2 * result.n_log_prob / result.n_replicates
print(f"{kernel:6} {v / 0.01**2:10.0f} {evaluations[kernel]:9,.0f}")
kernel replicates log_prob
rwmh 108 2,087,068
mala 266 108,780
hmc 43 107,595
The last column, times \(0.01^2\), is the inefficiency \(\mathbb E[C]\,\mathbb V[H]\)
(Theory) with the cost counted in log-density evaluations. For the
same error bars, MALA and HMC evaluate the log-density 19 and
19 times less often than the random walk, and the gradient as
often as the log-density. Whether that saves time depends on what a gradient costs, and
on how much of its work the log-density shares: a function that returns both, passed as
log_prob_and_grad, is called once where log_prob and grad are called one after the
other (The value and the gradient in one call).
A logistic regression¶
Two hundred binary outcomes \(y_i\) depend on five predictors through
\(P(y_i = 1) = 1/(1 + e^{-x_i^\top\beta})\), where \(x_i\) starts with a 1 for the intercept.
Each of the six coefficients has the prior \(\mathcal N(0, 5^2)\). The log-density and its
gradient take a batch of points \(\beta\) of shape (n, 6), or one point of shape (6,):
from scipy import optimize, special
rng = np.random.default_rng(1)
X = np.column_stack([np.ones(200), rng.normal(size=(200, 5))])
y = (rng.random(200) < special.expit(X @ [0.5, 1.0, -0.5, 0.25, 0.0, -1.0])).astype(float)
def log_prob(beta, X, y):
eta = beta @ X.T
return np.sum(y * eta - np.logaddexp(0, eta), axis=-1) - np.sum(beta**2, axis=-1) / 50
def grad(beta, X, y):
return (y - special.expit(beta @ X.T)) @ X - beta / 25
The pairs start from a Gaussian ten times wider than an optimizer’s error bars (Initial distributions):
fit = optimize.minimize(
lambda beta: -log_prob(beta, X, y), np.zeros(6), jac=lambda beta: -grad(beta, X, y)
)
init = telescopic.initial.Normal(mean=fit.x, cov=100 * fit.hess_inv)
names = ["intercept", "b1", "b2", "b3", "b4", "b5"]
mala = telescopic.sample(
log_prob, init, args=(X, y), grad=grad, vectorize=True, kernel="mala", names=names, rng=2
)
mala.summary()
| mean | standard_error | std | q16 | q50 | q84 | |
|---|---|---|---|---|---|---|
| intercept | 0.416738 | 0.00270595 | 0.173546 | 0.241313 | 0.41767 | 0.589987 |
| b1 | 0.894538 | 0.00322364 | 0.188495 | 0.707996 | 0.889333 | 1.0792 |
| b2 | -0.675539 | 0.00328514 | 0.201194 | -0.872006 | -0.669989 | -0.477202 |
| b3 | 0.256155 | 0.00308823 | 0.165242 | 0.0927041 | 0.255386 | 0.420008 |
| b4 | 0.07421 | 0.00274634 | 0.16637 | -0.0871133 | 0.0718822 | 0.23644 |
| b5 | -0.84926 | 0.00277923 | 0.194053 | -1.04452 | -0.84424 | -0.65327 |
- R = 100, k = 13, m = 130, lag = 13, thin = 1
- kernel: MALA(step_size=1.267, cov=<6x6>)
- meeting times: median 19, 90% 23, 99% 28, max 28; censored 0
- cost per replicate: 136.2 kernel applications, 0.00143 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: 14%, for the variance of b5
hmc = telescopic.sample(
log_prob, init, args=(X, y), grad=grad, vectorize=True, kernel="hmc", names=names, rng=3
)
hmc.summary()
| mean | standard_error | std | q16 | q50 | q84 | |
|---|---|---|---|---|---|---|
| intercept | 0.417174 | 0.0006547 | 0.176174 | 0.242843 | 0.415505 | 0.592772 |
| b1 | 0.894863 | 0.000667863 | 0.190581 | 0.70633 | 0.889504 | 1.08413 |
| b2 | -0.676628 | 0.000712946 | 0.203168 | -0.877822 | -0.673589 | -0.475323 |
| b3 | 0.25819 | 0.000650906 | 0.165619 | 0.0930141 | 0.256922 | 0.422894 |
| b4 | 0.0785025 | 0.000547323 | 0.168084 | -0.0882104 | 0.0770003 | 0.24546 |
| b5 | -0.852176 | 0.000727969 | 0.195281 | -1.04445 | -0.847644 | -0.658694 |
- R = 100, k = 93, m = 930, lag = 93, thin = 1
- kernel: HMC(step_size=0.917, n_steps=2, cov=<6x6>, jitter=0.5, meeting_weight=0.05, meeting_scale=0.001)
- meeting times: median 123, 90% 157, 99% 188, max 230; censored 0
- cost per replicate: 966.8 kernel applications, 0.0186 s; relative cost 1.15
- pairs meeting after k + lag: 3.0% (at most 7.6% at 95%)
- largest share of one replicate in a variance: 12%, for the variance of b1
The two runs have different seeds, so their errors are independent, and the difference of their estimates of each mean, divided by its standard error, should look like a draw from \(\mathcal N(0, 1)\):
a, b = mala.mean(), hmc.mean()
z = (a.value - b.value) / np.hypot(a.standard_error, b.standard_error)
dict(zip(names, z.round(2).tolist()))
{'intercept': -0.16,
'b1': -0.1,
'b2': 0.32,
'b3': -0.64,
'b4': -1.53,
'b5': 1.02}
The differences are of the size of their standard errors: the two kernels agree. Here their automatic step sizes coupled; on some targets, log-concave or not, they do not (When the automatic step fails), and the step size must be given and checked against pilot meeting times (Checking a step size).
A gradient that is not the derivative¶
A sampler built with grad and a gradient kernel first compares grad with differences
of log_prob at 8 draws of the initial distribution, before tuning
(Checking the gradient). A gradient that
leaves out the prior’s term, \(-\beta/25\), is no longer the derivative of log_prob, and
the sampler says so as it is built:
import warnings
def grad_without_prior(beta, X, y):
return (y - special.expit(beta @ X.T)) @ X
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
sampler = telescopic.CoupledSampler(
log_prob,
init,
args=(X, y),
grad=grad_without_prior,
vectorize=True,
kernel="mala",
rng=4,
)
print(caught[0].message)
grad disagrees with differences of log_prob: on a line through draw 4 of 8 of the initial distribution, the change of log_prob across the spread of the initial distribution differs from the one grad predicts by 0.574 nats, 0.0012 times the predicted change, and 7.27e+04 times the comparison's estimated error, so grad is not the derivative of log_prob as computed; look for a wrong sign, a wrong factor or a missing term in grad; a gradient that is approximate by design, as from a solver, numerical differences or single precision, is expected to warn, and check_grad=False turns the check off
The warning is an InputWarning, and nothing else has run yet. MALA and HMC stay exact
with any gradient, so the warning does not mean that the estimates are wrong; it says
that the gradient is not the one of this log-density, which can slow the chains. A
gradient that is approximate on purpose warns too, and check_grad=False turns the
check off.