Write the log-density and constraints

A run needs two inputs: the log-density of the target, and the initial distribution from which each pair of chains starts (Choose an initial distribution).

The log-density

log_prob(x, *args, **kwargs) takes one point x of shape (d,) and returns its log-density, up to an additive constant, as a float. The arguments args and kwargs of telescopic.sample() are passed on to it: args is a tuple or a list, such as (data,), and any other args, such as an array, raises TypeError. With vectorize=True it takes a batch of shape (n, d) and returns shape (n,), so that a step of many chains costs one call instead of one per point. An output whose shape differs from the expected one only by axes of length 1, such as the shape () that SciPy’s multivariate_normal.logpdf returns for a batch of one point, is reshaped; a function called point by point may return a float at some points and an array of one element at others. Integers, booleans and real numbers held as objects, such as Fractions or Decimals, convert to float64. Any other shape raises ValueError, as does an output that is not numbers, such as None or emcee’s (log_prob, blobs) tuple: quantities derived from the parameters are computed after the run, with telescopic.Result.estimate(). A complex output whose imaginary part is exactly 0, as complex-step derivatives give, counts as its real part; any other complex output raises. telescopic computes in float64: a function that returns float32 values, as JAX does unless jax.config.update("jax_enable_x64", True) is called first, rounds the target, so it emits an InputWarning, once per target and naming the dtype. On a pool, each worker process evaluates its own copy of the target and warns there, so the warning appears in the workers’ output rather than in this process, unless this process also evaluates the target, as tuning does.

import numpy as np
from scipy import stats

import telescopic


def log_prob(x, mean, sd):
    return -0.5 * np.sum(((x - mean) / sd) ** 2)


def log_prob_batch(x, mean, sd):
    return -0.5 * np.sum(((x - mean) / sd) ** 2, axis=1)


mean, sd = np.array([1.0, -2.0]), np.array([0.5, 2.0])

grad is the gradient of the log-density, with the same signature, returning shape (d,), or (n, d) with vectorize=True. MALA and HMC need it (Kernels and couplings). Both functions receive read-only arrays, so one that writes to its input raises instead of corrupting the chains, and what they return is copied, so one may reuse its output array from call to call.

telescopic.Target holds these functions. telescopic.sample() and telescopic.CoupledSampler build one from their arguments; it is needed directly only with the building blocks, such as kernels, the engine and telescopic.testing.check_coupling(). Its log_prob takes a batch of shape (n, d), whether or not the function is vectorized, and counts the evaluations:

points = np.array([[0.0, 0.0], [1.0, 0.0], [2.0, 1.0]])
one = telescopic.Target(log_prob, args=(mean, sd))
batch = telescopic.Target(
    log_prob_batch, kwargs={"mean": mean, "sd": sd}, vectorize=True
)
one.log_prob(points), batch.log_prob(points), one.n_log_prob
(array([-2.5  , -0.5  , -3.125]), array([-2.5  , -0.5  , -3.125]), 3)

With vectorize=True, the kernels also compute their matrix products with BLAS, for a batch of chains at once, so a replicate’s results can differ by rounding with how the replicates are batched and with the number of BLAS threads, and through an acceptance or a meeting that the rounding moves, in its whole output; the estimates agree within their error bars (Parallel runs).

The value and the gradient in one call

A function that computes the log-density and its gradient together, sharing the work of the two, can be passed as log_prob_and_grad in place of grad. It takes the arguments of log_prob, args and kwargs included, and returns a pair, the value first: the value, a float, and the gradient, of shape (d,), at one point, or with vectorize=True the values of shape (n,) and the gradients of shape (n, d) of a batch. JAX’s value_and_grad returns them in this order; PyTorch’s torch.func.grad_and_value is documented to return the gradient first, so its pair must be swapped. Wherever the chains of MALA, HMC or a mixture with one of them need a gradient, it is called once, where with grad the target calls log_prob and then grad. Passing both grad and log_prob_and_grad raises ValueError.

log_prob is still needed, and its values must be those of log_prob_and_grad: the evaluations that need no gradient call it, such as the steps of tuning’s pilot chains. Each part of the pair is checked and converted as the output of log_prob or grad is, and an error names the part and the function. Where the value is -inf, the gradient must still be real numbers of the gradient’s shape, but its values are not used: states there carry a gradient of 0, as with grad, so a placeholder such as zeros will do and None raises. The counts of evaluations keep their meaning: each point counts in n_log_prob, and in n_grad where its value is finite. For the Gaussian above, a function written by hand computes the standardized point once for both:

def log_prob_and_grad_batch(x, mean, sd):
    z = (x - mean) / sd
    return -0.5 * np.sum(z**2, axis=1), -z / sd


both = telescopic.Target(
    log_prob_batch,
    log_prob_and_grad=log_prob_and_grad_batch,
    args=(mean, sd),
    vectorize=True,
)
values, gradients = both.log_prob_and_grad(points)
values, gradients, both.n_log_prob, both.n_grad
(array([-2.5  , -0.5  , -3.125]),
 array([[ 4.  , -0.5 ],
        [-0.  , -0.5 ],
        [-4.  , -0.75]]),
 3,
 3)

What it saves depends on how much work the two functions share. On two regressions in 10 dimensions, a whole sample call with MALA or HMC, tuning included, made 0.51 to 0.73 times as many calls of the user’s functions with log_prob_and_grad. On a linear regression whose log_prob and grad repeated a third of their arithmetic, it took 0.70 to 0.82 times as long, the medians of five timed pairs of runs for each kernel and form of the functions, every ratio of which was below 0.85. On a logistic regression whose costly part, a logarithm or an exponential of each observation, is not shared, the time ratios of three of the four configurations ranged across 1, so the saving of calls did not show in the time there; MALA point by point took 0.905 times as long (0.879 to 0.978).

With JAX, jax.value_and_grad gives such a function, for one point, and jax.vmap of it one for a batch:

import jax
import jax.numpy as jnp

jax.config.update("jax_enable_x64", True)  # float64, as telescopic computes


def log_prob_jax(x):
    return -0.5 * jnp.sum(x**2)


log_prob = jax.jit(jax.vmap(log_prob_jax))
log_prob_and_grad = jax.jit(jax.vmap(jax.value_and_grad(log_prob_jax)))
init = telescopic.initial.Normal(np.zeros(2), np.eye(2))
result = telescopic.sample(
    log_prob, init, log_prob_and_grad=log_prob_and_grad, vectorize=True, kernel="mala"
)

Special values

  • -inf means zero density. Every Metropolis test rejects a proposal there, so the log-density should return it outside the support.

  • NaN and +inf raise ValueError with the point.

SciPy returns NaN for a negative scale, so a model of 20 observations whose scale is not restricted fails at the first chain that proposes one:

y = np.random.default_rng(2).normal(1.0, 2.0, size=20)


def log_prob_unrestricted(theta, y):
    location, scale = theta
    return np.sum(stats.norm.logpdf(y, location, scale))


unrestricted = telescopic.Target(log_prob_unrestricted, args=(y,))
try:
    unrestricted.log_prob(np.array([[0.0, -1.0]]))
except ValueError as error:
    print(error)
log_prob returned nan at x = [0.0, -1.0]

Returning -inf outside the support fixes it:

def log_prob_restricted(theta, y):
    location, scale = theta
    if scale <= 0:
        return -np.inf
    return np.sum(stats.norm.logpdf(y, location, scale))


restricted = telescopic.Target(log_prob_restricted, args=(y,))
restricted.log_prob(np.array([[0.0, 1.0], [0.0, -1.0]]))
array([-57.5139513,        -inf])

For the gradient:

  • Where the log-density is -inf, the gradient is not evaluated, so it may fail there. States there carry a gradient of 0, so MALA and HMC propose from them without drift.

  • Where the log-density is finite, a gradient that is not finite raises ValueError with the point at the states that chains start from: a MALA chain could not leave such a start, since a move back is accepted only if the reverse proposal, which carries the full drift, could return. Tuning’s step-size search starts its chains from the pilot’s last states, not from the initial distribution, and takes it as 0 there, since only the step size depends on those chains. Elsewhere it is taken as 0 too, which keeps MALA and HMC exact but takes their drift away there. The pilot pairs and the replicates of a run that meet one warn, in this process as soon as they do and on a pool when the run ends, and Result.n_grad_zeroed counts the replicates’ ones. Tuning does not warn: its search for a step size reaches far into the tails.

  • Such a gradient costs nothing where the chains do not go, as with a mixture’s responsibilities computed from densities, which underflow far in the tails. Where they go, it slows them, and HMC pairs that lose their drift over much of the target may not meet. A gradient computed in log space avoids both, such as responsibilities from scipy.special.logsumexp. In this process, warnings.simplefilter("error", telescopic.InputWarning) stops a run at the first such gradient after tuning.

The log-density must be deterministic: the same point must always give the same value. Pairs meet when their states are equal, and a log-density estimated by simulation breaks the couplings.

Checking the gradient

MALA and HMC stay exact with a wrong gradient: their Metropolis tests correct any drift. A wrong gradient makes them slow instead, and their pairs can take hundreds of times longer to meet. So when telescopic.CoupledSampler or telescopic.sample() is built with grad and a kernel that evaluates it, MALA, HMC or a mixture with one of them, it compares grad with differences of log_prob before tuning. At each of 8 draws \(x\) of the initial distribution, along the direction \(u\) between two further draws, it compares the change of \(\log\pi\) that grad predicts, \(\nabla\log\pi(x)\cdot u\), with central differences of log_prob at steps \(hu\), where \(h = \epsilon^{1/3}\) for the epsilon \(\epsilon\) of the values log_prob returns. A line disagrees when the gap between the two exceeds 10 times the estimated error of the comparison: the truncation of the differences, from a second difference at steps \(2hu\), and the rounding of log_prob and of grad. It costs 40 evaluations of log_prob and 8 of grad at any dimension, and 8 more of each when grad returns float32 values, and again when log_prob does; a log_prob whose values narrow to float32 only after the first draw costs a second sweep at float32. It draws 48 points of the initial distribution, in two passes of 24, from a random stream of its own, and it changes no result: a run is the same with and without it. A sampler built with log_prob_and_grad compares its gradient with differences of its own values, which are those the chains use, and does not call log_prob; its warnings then name the gradient and the log-density of log_prob_and_grad. It evaluates log_prob_and_grad at most at the points where a check of log_prob and grad returning the same dtypes evaluates log_prob: 40 for float64 values, and for narrower ones sometimes fewer, since it reads the gradient’s dtype at draws of zero density too. The exception is a gradient narrower than float64 only where the value is -inf, which the check of two functions never sees: the combined check then evaluates a few more points and compares with a wider tolerance.

A gradient with its sign wrong warns before any pair runs, with the size of the disagreement:

import warnings


def log_prob_gaussian(x):
    return -0.5 * np.sum((x - 1.0) ** 2, axis=-1)


def grad_wrong_sign(x):
    return x - 1.0


init = telescopic.initial.Normal(np.zeros(5), 4 * np.eye(5))
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    sampler = telescopic.CoupledSampler(
        log_prob_gaussian, init, grad=grad_wrong_sign, vectorize=True, kernel="mala", rng=0
    )
print(caught[0].message)
grad disagrees with differences of log_prob: on a line through draw 6 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 62.1 nats, 2 times the predicted change, and 2.04e+08 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. The sizes are in nats along \(u\), which spans the spread of the initial distribution. The sampler keeps what the check compared, as a telescopic.diagnostics.GradientCheck, in sampler.gradient_check: the gap, the tolerance and the predicted change of each line, the draw it starts from, and the ratio of gap to tolerance. The check warns when a gap exceeds its tolerance, and here each of the 8 lines does:

check = sampler.gradient_check
print(f"{len(check.gap)} lines, the smallest ratio {check.ratio.min():.3g}")
8 lines, the smallest ratio 1.41e+07

check_grad=False turns the check off, and gradient_check is then None. A check that could compare no line warns too, since it leaves the gradient unchecked: every draw has zero density or a gradient that is not finite, or every line reaches zero density, as from a start on a boundary of the support, or takes steps that round away in the dtype of log_prob, as from a float32 log_prob and a start whose spread is tiny beside its distance from 0. An error raised inside the check, by the functions it evaluates or about what they return, is raised as it is, with a note that it was raised in the gradient check, which evaluates them at draws of the initial distribution when the sampler is built.

A warning means that the gradient is not the derivative of the log-density as computed, along the spread of the initial distribution, by more than the check can attribute to rounding: at least \(10 \times 64\,\epsilon\,|\log\pi| / h = 640\,\epsilon^{2/3}|\log\pi|\) nats, which is \(2\times10^{-8}\,|\log\pi|\) with float64 values and \(1.5\times10^{-2}\,|\log\pi|\) with float32 ones. It does not mean that the gradient slows the chains. The rates below come from a test whose criteria were fixed before it ran, with MALA pairs measuring how much a wrong gradient slows meeting, and from an independent attempt to refute it:

  • Exact gradients of smooth code stay quiet. On 109 targets whose grad is the exact derivative of log_prob, 300 draws of the check each, it never warned: Gaussians with scales from \(10^{-8}\) to \(10^{8}\) and conditioning to \(10^{12}\), heavy tails, kinks such as a Laplace density in 10,000 dimensions, tables, and float32 values. The largest ratio was 0.39.

  • Wrong gradients warn. Of 49 wrong gradients that slowed the meeting of MALA pairs by a factor of 2 or more, it warned in every check on 46: wrong signs, factors of 2, terms left out, and one wrong coordinate among 10,000. The other 3 started much tighter than the target in the wrong coordinate (below).

  • Gradients that are approximate by design warn too: the exact gradient of a log-density computed by an iterative solver at a relative tolerance of \(10^{-3}\) or \(10^{-5}\), a gradient 1.005 times too large, a logistic regression’s gradient without its prior (300 of 300 each); a gradient computed in float32 and returned as float64 (195 to 200 of 200 on seven of ten targets, 30 of 200 on one more, none on the other two); forward differences as grad (194 to 200 of 200 on three of four targets, none of 50 on the fourth); a log-density from an adaptive ODE solver at a tolerance of \(10^{-6}\) with the gradient of the exact solution (100 of 100). The solver, the factor 1.005, the missing prior and the float32 gradient, on the two targets where it was measured, slowed the meeting of MALA pairs by no measurable amount; for forward differences and the ODE solver that was not measured. Such a gradient warns once per sampler; pass check_grad=False once its accuracy is known to be enough.

  • A correct gradient can warn on a strongly periodic or finely tabulated log-density from a wide start: with \(10^5\) periods per unit across a start of standard deviation 1, 48 of 200 checks warned, with \(10^6\), all 200; a piecewise-linear table with knots \(10^{-5}\) apart, from a start of standard deviation 2, warned 143 times in 200.

  • Silence is weak evidence. The check compares at 8 draws where the chains start. It saw nothing in 200 checks each of a wrong-sign gradient from a start at the mode, of a gradient wrong only away from a small ball of starts, of a log_prob offset by \(-10^{10}\), and, with float32 values of log_prob and one coordinate’s sign wrong, it warned in 196 of 200 checks in 200 dimensions, 37 of 200 in 1,000 and none of 100 in 10,000. A start much tighter than the target in the wrong coordinate also weakens it: 100 times tighter in 10,000 dimensions, it warned in 518 of 1,000 checks.

The rates of the first two items, of the solver, the factor 1.005 and the missing prior, and of the start 100 times tighter come from the test fixed in advance, run with its own code, which the package’s check reproduces line for line; the others were measured with the package’s check.

Setup of these runs: telescopic at commit 3029130 (7b2c992 for the test fixed in advance), 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.

Constrained parameters

A parameter with a bound, such as a scale \(\sigma > 0\), can be sampled through an unconstrained transform, such as \(s = \log\sigma\). The log-density of \(s\) adds the logarithm of the Jacobian \(d\sigma/ds = \sigma\), which is \(s\). The chains then never reach a boundary, and every point of the initial distribution lies inside the support. We sample the model above with flat priors on the location and the scale:

def log_prob_log_scale(theta, y):
    location, log_scale = theta
    log_jacobian = log_scale
    return np.sum(stats.norm.logpdf(y, location, np.exp(log_scale))) + log_jacobian


init = telescopic.initial.Normal([0.0, 0.0], [1.0, 1.0])
result = telescopic.sample(
    log_prob_log_scale, init, args=(y,), names=["location", "log_scale"], rng=0
)

An expectation of \(\sigma\) is an expectation of a function of \(s\), so the same run gives it:

result.estimate(lambda t: np.exp(t[:, 1]))
Estimate(1.92682 ± 0.0041, R=100)

Quantiles and credible intervals gives the quantiles of the sampled coordinates and of derived quantities. To sample \(\sigma\) itself instead, return -inf where \(\sigma \le 0\), as above, and draw the initial distribution inside the support (Choosing one).