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,mand 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_prob
callable()orNone \(\log\pi\) up to a constant:
log_prob(x, *args, **kwargs)forxof shape(d,), or of shape(n, d)withvectorize=True.Noneonly with a kernel that needs no log-density: aGibbskernel or a mixture of them.- init
The initial distribution \(\pi_0\): an object with
rvs(random_state=rng)(such as a frozen SciPy distribution ortelescopic.initial.Normal), a callableinit(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.- args
tupleorlist Extra positional arguments of
log_prob,gradandlog_prob_and_grad, such as(data,).- kwargsmapping, optional
Extra keyword arguments of these functions.
- grad
callable(), 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_grad
callable(), optional In place of
grad: the pair \((\log\pi, \nabla\log\pi)\) from one call with the signature oflog_prob, as JAX’svalue_and_gradgives, which MALA and HMC then call wherever they need a gradient;log_prob, whose values it must match, still serves tuning’s pilot chains. SeeTarget.- vectorizebool
Whether
log_prob,gradandlog_prob_and_gradtake 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,poolandn_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).- kernel
Kernelorstr A kernel, or one of
"auto"and"rwmh"(random-walk Metropolis with the reflection-maximal coupling),"mala"and"hmc"(which needgradorlog_prob_and_grad) and"independence".- namessequence of
str, optional Parameter names for summaries.
- pool
None,int, executor or pool Where the pilot pairs and the replicates run:
Nonein this process; an integer, that many worker processes, started for each call ofrun()ormeeting_times(); or an object withsubmit, such as aconcurrent.futures.Executor, or withmap, 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_workers
int, 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;Nonereads 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: withpoolNone or an integer it raisesValueError. 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):
gradwith differences oflog_prob, or the gradient oflog_prob_and_gradwith differences of its own values. Withgradit costs 40 evaluations oflog_proband 8 ofgradfor float64 values, 8 more of each for a float32gradand again for a float32log_prob, and a second sweep for alog_probwhose values narrow after the first draw; withlog_prob_and_grad, 40 evaluations of it for float64 values, and for narrower ones at most as many as oflog_probwith 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.- rng
None,int,numpy.random.SeedSequenceornumpy.random.Generator The root of every random stream.
- log_prob
- Attributes:
- kernel
Kernel The kernel, replaced by its tuned copy when tuned.
- gradient_checktelescopic.diagnostics.GradientCheck or
None What the gradient check compared;
Nonewhen it did not run.- tuning
TuningReportorNone The report of the tuning pilot;
Nonebefore tuning or with nothing to tune.- pilot
ndarrayorNone The meeting times of every lag-1 pilot pair run so far;
Nonebefore the first.- seed
numpy.random.SeedSequence The root seed.
- ndim
int The dimension of the target.
- kernel
- meeting_times(n=100, *, max_iter=100000)¶
Meeting times of
nnew 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 oftune().
- 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 automatick, completes the pilot to 100 pairs; the runs then keep these settings. Withcheckpoint, 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_replicates
int, optional With
checkpoint: the replicates the run will hold, the indices 0 ton_replicates - 1, so that the result loaded from the directory isinterrupteduntil 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().- checkpoint
stror path-like, optional As for
run().- progressbool, optional
Show the progress of the tuning and the pilot;
Nonetakes the sampler’s setting.
- n_replicates
- Returns:
- 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 thatresultlacks, then new indices above the highest it requested, with itsk,m,lag,thinandmax_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.kernelwhen it is a kernel. A loaded result holds only the kernel’s description: pass the kernel as it was built, untuned, andresumetunes 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:
- result
Result The result to continue: returned by a run, loaded, or merged.
- result
- run(
- n_replicates,
- *,
- k='auto',
- m='auto',
- lag='auto',
- thin=None,
- max_iter=None,
- keep=None,
- start=None,
- checkpoint=None,
- progress=None,
Run
n_replicatesmore 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 raisesKeyboardInterruptat 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_resultset to the result of all of them so far (Noneif 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_replicates
int The number of replicates to add, at least 1.
- k, m, lag
intor “auto” "auto"derives a value on the first call: the pilot’s quantile fork, thenlag = max(1, k)andm = 10 k. A value given explicitly is kept. On later calls"auto"keeps the first call’s value.- thin
int, optional Average every
thin-th state fromk: 1 on the first call, and the first call’s value on later ones.- max_iter
int, optional Censor pairs still unmet at this time.
Noneruns every pair until it meets on the first call, and keeps the first call’s cap on later ones.- keep
int, optional Store the signed measures and distances of the replicates of index below
keeponly, and the moments of every replicate, from which the mean, the variances and the covariance (up to 100 dimensions) come; the quantiles, histograms andestimate()come from the kept replicates.Nonestores every replicate’s signed measure on the first call, and keeps the first call’s setting on later ones.- start
int, optional Run the replicates of indices
starttostart + n_replicates - 1, none of which this sampler may have requested before, as one task of a run split into ranges of indices.Noneruns first the requested replicates that have not run, then indices above the highest requested so far.- checkpoint
stror 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 withstart, which needs the plan ofplan(). 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.loadof 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;
Nonetakes the sampler’s setting.
- n_replicates
- Returns:
ResultUnbiased for an
n_replicatesfixed in advance, unlessmax_itercensors a pair, which biases it and warns, or a Ctrl-C interrupts the run, which leaves it consistent and flaggedinterrupted; 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()orresume().Noneuntil then.- Returns:
- 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:
TuningReportorNoneNonewhen the kernel had nothing to tune.