CoupledSampler

class telescopic.CoupledSampler(
log_prob,
init,
*,
args=(),
kwargs=None,
grad=None,
log_prob_and_grad=None,
vectorize=False,
kernel='auto',
names=None,
pool=None,
n_workers=None,
progress=False,
check_grad=True,
rng=None,
)

Unbiased MCMC with coupled chains: tuning, pilot meeting times and runs.

The pipeline tunes the kernel’s unset parameters on adaptive pilot chains, chooses k, m and the lag from the meeting times of 100 lag-1 pilot pairs, then runs replicates of coupled chains whose signed measures give unbiased estimates of any expectation under the target.

Parameters:
log_probcallable() or None

\(\log\pi\) up to a constant: log_prob(x, *args, **kwargs) for x of shape (d,), or of shape (n, d) with vectorize=True. None only with a kernel that needs no log-density: a Gibbs kernel or a mixture of them.

init

The initial distribution \(\pi_0\): an object with rvs(random_state=rng) (such as a frozen SciPy distribution or telescopic.initial.Normal), a callable init(rng), or an array of points of shape (n, d). Every \(\pi_0\) from which the chain converges keeps the estimates unbiased (Guarantees and their limits, in Theory); one wider than the target and covering all its modes keeps them reliable.

argstuple or list

Extra positional arguments of log_prob, grad and log_prob_and_grad, such as (data,).

kwargsmapping, optional

Extra keyword arguments of these functions.

gradcallable(), optional

\(\nabla\log\pi\) with the signature of log_prob. Only the kernels that need it, MALA and HMC, evaluate it; "auto" is random-walk Metropolis.

log_prob_and_gradcallable(), optional

In place of grad: the pair \((\log\pi, \nabla\log\pi)\) from one call with the signature of log_prob, as JAX’s value_and_grad gives, which MALA and HMC then call wherever they need a gradient; log_prob, whose values it must match, still serves tuning’s pilot chains. See Target.

vectorizebool

Whether log_prob, grad and log_prob_and_grad take a batch of points. The kernels then also compute their matrix products for a batch of chains at once, with BLAS, so a run repeats bitwise only with the same seed and settings, pool and n_workers, BLAS build and number of BLAS threads. Otherwise a replicate can differ by rounding, which can move its meeting time and its whole output, and the estimates agree within their error bars (Reproducibility, in Run in parallel).

kernelKernel or str

A kernel, or one of "auto" and "rwmh" (random-walk Metropolis with the reflection-maximal coupling), "mala" and "hmc" (which need grad or log_prob_and_grad) and "independence".

namessequence of str, optional

Parameter names for summaries.

poolNone, int, executor or pool

Where the pilot pairs and the replicates run: None in this process; an integer, that many worker processes, started for each call of run() or meeting_times(); or an object with submit, such as a concurrent.futures.Executor, or with map, such as an emcee or schwimmbad pool. A pool runs chunks of consecutive indices, at most four per worker; a task in a worker process runs with BLAS pinned to one thread and Ctrl-C ignored. With a log-density evaluated point by point, no replicate depends on the pool. With a vectorized one, a run on a pool can differ by rounding from one in this process, through its chunks and through the one BLAS thread of its workers (Reproducibility, in Run in parallel).

n_workersint, optional

The number of workers of an executor or a pool, which sets how many chunks it gets: one per worker at least, and four at most unless a chunk would then hold more than 1,024 replicates, the most it ever holds; for a pool with only map, waves of one per worker. Given, it replaces the size that the pool reports; None reads that size, or else counts the CPUs this process may use, which leaves idle the workers of a larger pool that does not report its size, such as a cluster’s. Only for an executor or a pool: with pool None or an integer it raises ValueError. State the pool’s real number of workers: a larger value makes smaller chunks, which run fewer replicates together. With a log-density evaluated point by point, no replicate depends on it.

progressbool

Show the progress of tuning, of the pilot and of each run: a tqdm bar when tqdm is installed, lines on stderr otherwise.

check_gradbool

Compare the gradient with differences of the log-density at 8 draws of the initial distribution when the sampler is built, if the kernel evaluates a gradient, and warn where they disagree (Checking the gradient, in Write the log-density and constraints): grad with differences of log_prob, or the gradient of log_prob_and_grad with differences of its own values. With grad it costs 40 evaluations of log_prob and 8 of grad for float64 values, 8 more of each for a float32 grad and again for a float32 log_prob, and a second sweep for a log_prob whose values narrow after the first draw; with log_prob_and_grad, 40 evaluations of it for float64 values, and for narrower ones at most as many as of log_prob with the same dtypes, unless its gradient is narrower only where its value is -inf. It draws 48 points of the initial distribution and changes no result.

rngNone, int, numpy.random.SeedSequence or numpy.random.Generator

The root of every random stream.

Attributes:
kernelKernel

The kernel, replaced by its tuned copy when tuned.

gradient_checktelescopic.diagnostics.GradientCheck or None

What the gradient check compared; None when it did not run.

tuningTuningReport or None

The report of the tuning pilot; None before tuning or with nothing to tune.

pilotndarray or None

The meeting times of every lag-1 pilot pair run so far; None before the first.

seednumpy.random.SeedSequence

The root seed.

ndimint

The dimension of the target.

meeting_times(n=100, *, max_iter=100000)

Meeting times of n new pilot pairs with lag 1.

Each call runs new pilot replicates, continuing their indices, and adds them to pilot. The first tunes the kernel when it needs tuning, with the warnings of tune().

Parameters:
nint

Pilot pairs to add, at least 1.

max_iterint

The cap, above 1; a pair still unmet there is censored.

Returns:
ndarray, shape (n,)

Meeting times, inf for a censored pair.

plan(
n_replicates=None,
*,
k='auto',
m='auto',
lag='auto',
thin=None,
max_iter=None,
keep=None,
checkpoint=None,
progress=None,
)

Fix the settings of the runs without running replicates, and write them as a plan.

As the first run() would, it tunes the kernel and, for an automatic k, completes the pilot to 100 pairs; the runs then keep these settings. With checkpoint, it writes them as the plan of that directory, which the tasks of a cluster job adopt. A sampler whose settings are fixed returns them.

Parameters:
n_replicatesint, optional

With checkpoint: the replicates the run will hold, the indices 0 to n_replicates - 1, so that the result loaded from the directory is interrupted until all of them have finished, even those of a task that never started. A checkpoint that already holds a plan of another total raises.

k, m, lag, thin, max_iter, keep

As for run().

checkpointstr or path-like, optional

As for run().

progressbool, optional

Show the progress of the tuning and the pilot; None takes the sampler’s setting.

Returns:
telescopic.engine.Settings
resume(result)

Continue the run of a result: its replicates, seed, settings, tuning and pilot.

The next call of run() first runs the requested replicates that result lacks, then new indices above the highest it requested, with its k, m, lag, thin and max_iter, and returns the result of all of them.

The sampler must have been built with the target, the initial distribution and the kernel of that run. Only the dimension and the kernel’s class can be checked; a different target or kernel goes unnoticed and mixes replicates of two runs. Pass result.kernel when it is a kernel. A loaded result holds only the kernel’s description: pass the kernel as it was built, untuned, and resume tunes it again from the result’s seed. It warns when the kernel’s tuning or description differs from the result’s; everything is adopted before any warning.

Parameters:
resultResult

The result to continue: returned by a run, loaded, or merged.

run(
n_replicates,
*,
k='auto',
m='auto',
lag='auto',
thin=None,
max_iter=None,
keep=None,
start=None,
checkpoint=None,
progress=None,
)

Run n_replicates more replicates and return the result of all of them so far.

The first call tunes the kernel, completes the pilot to 100 pairs for an automatic k, and fixes the settings of the later calls. The result warns about the conditions listed under Warnings, in Warnings and errors.

The first Ctrl-C during the replicates lets those in progress finish and returns a result flagged interrupted; the next call runs the missing replicates first. A second Ctrl-C raises KeyboardInterrupt at once, without a result.

An error during the replicates, such as one of the log-density, is raised again once the sampler keeps the replicates finished before it, with its attribute telescopic_result set to the result of all of them so far (None if none finished) and a note; the next call runs the missing replicates first. An error in tuning or in the pilot is raised as it is.

Parameters:
n_replicatesint

The number of replicates to add, at least 1.

k, m, lagint or “auto”

"auto" derives a value on the first call: the pilot’s quantile for k, then lag = max(1, k) and m = 10 k. A value given explicitly is kept. On later calls "auto" keeps the first call’s value.

thinint, optional

Average every thin-th state from k: 1 on the first call, and the first call’s value on later ones.

max_iterint, optional

Censor pairs still unmet at this time. None runs every pair until it meets on the first call, and keeps the first call’s cap on later ones.

keepint, optional

Store the signed measures and distances of the replicates of index below keep only, and the moments of every replicate, from which the mean, the variances and the covariance (up to 100 dimensions) come; the quantiles, histograms and estimate() come from the kept replicates. None stores every replicate’s signed measure on the first call, and keeps the first call’s setting on later ones.

startint, optional

Run the replicates of indices start to start + n_replicates - 1, none of which this sampler may have requested before, as one task of a run split into ranges of indices. None runs first the requested replicates that have not run, then indices above the highest requested so far.

checkpointstr or path-like, optional

A directory, made if missing, to which the run writes its replicates as they finish: every 256 in this process, each chunk on a pool. A sampler without settings adopts the plan the directory holds, as resume() adopts a result, without a pilot, and settings given must be the plan’s; a sampler with settings must have the plan’s seed and settings. Without a plan, the sampler’s is written there once its tuning and pilot have finished, except with start, which needs the plan of plan(). A plan written by another version of telescopic warns. Replicates of this call’s indices that the directory holds are read from it, not run again, so the same call completes a run that a killed process left unfinished; Result.load of the directory returns the result of every replicate it holds.

progressbool, optional

Show the progress of the run and of the tuning and the pilot it runs; None takes the sampler’s setting.

Returns:
Result

Unbiased for an n_replicates fixed in advance, unless max_iter censors a pair, which biases it and warns, or a Ctrl-C interrupts the run, which leaves it consistent and flagged interrupted; extending a run after looking at it keeps consistency, not exact unbiasedness.

Examples

A second call runs 25 more replicates and returns the result of all 50:

>>> from telescopic import CoupledSampler, examples
>>> example = examples.gaussian(2)
>>> sampler = CoupledSampler(
...     example.log_prob, example.initial, vectorize=True, rng=0
... )
>>> sampler.run(25).n_replicates, sampler.run(25).n_replicates
(25, 50)
property settings

The settings of the runs, fixed by the first run, plan() or resume().

None until then.

Returns:
telescopic.engine.Settings or None
tune()

Tune the kernel’s unset parameters on pilot chains, once, and freeze the kernel.

Warns when the chains disagree, a sign of several modes or of chains that have not converged; chains that agree do not show that the target has one mode. Warns too of a start far wider than the target (A start far wider than the target, in Warnings and errors).

Returns:
TuningReport or None

None when the kernel had nothing to tune.