Run in parallel

Replicates are independent, so they run in parallel without communicating. The pool argument of telescopic.sample() and telescopic.CoupledSampler decides where the meeting-time pilot and the replicates run, and n_workers how many workers a pool of your own has; the kernel is tuned in this process (Tuning).

Pools

pool takes:

  • None, the default: the replicates run in this process;

  • an integer: that many worker processes (at most 61 on Windows), which telescopic starts with the spawn method for each call of run or meeting_times, and stops when the call ends. They start before the tuning, so that their start overlaps it, and serve the pilot and the run;

  • an executor with submit, such as a concurrent.futures.ProcessPoolExecutor;

  • an object with map, such as a multiprocessing.Pool or the schwimmbad pools that emcee takes.

Starting worker processes takes time, so a pool pays off only for runs that take longer than the start. Each worker starts Python and imports telescopic, which imports NumPy and SciPy’s linear algebra, sparse arrays and special functions. The functions that need SciPy’s statistics, optimization or integration, none of which runs in a worker, import them at their first call. telescopic starts and stops only the workers of an integer pool. The workers of an executor or a pool of your own live as long as it does and serve every run given it, and you close it. The executor below spawns its workers, as telescopic does: forking a process that runs threads, such as a notebook’s kernel or a multithreaded BLAS, can deadlock. With progress=True, the sampler shows the progress of its pilot pairs and of each run (Progress):

import multiprocessing
from concurrent.futures import ProcessPoolExecutor

import numpy as np

import telescopic

gaussian = telescopic.examples.gaussian(2)  # evaluated one point at a time here
spawn = multiprocessing.get_context("spawn")
with ProcessPoolExecutor(2, mp_context=spawn) as executor:
    sampler = telescopic.CoupledSampler(
        gaussian.log_prob, gaussian.initial, pool=executor, progress=True, rng=3
    )
    first = sampler.run(100)
    both = sampler.run(100)
both.n_replicates
telescopic: tuning: 2000 of 2000 steps finished in 0 s
telescopic: pilot pairs: 100 of 100 replicates finished in 1 s
telescopic: replicates: 100 of 100 replicates finished in 0 s
telescopic: replicates: 100 of 100 replicates finished in 0 s
200

The second run ran 100 more replicates on the same workers, with the settings of the first, and returned the result of all the replicates so far. To split a run across machines, run separate ranges of replicate indices with one seed and the same settings, sampler.run(n, start=i) for the indices i to i + n - 1, and join the results (Merging runs); a checkpoint directory does both for the tasks of a cluster job (Run on a cluster).

Tuning

Tuning runs in this process, one step after another, before the pilot and the replicates, while the workers wait (The automatic pipeline and A slow log-density give its length). With a log-density evaluated point by point on many workers, these sequential steps can take longer than a worker’s share of the run. A job that passes a tuned kernel and its k skips both the tuning and the meeting-time pilot, as the second of those sections explains, so several jobs on one target can tune once. A saved result holds only the kernel’s description (Saving and loading), so a job in another process gets the kernel itself by pickle, here through bytes, as it would through a file:

import pickle

tuned = pickle.dumps(first.kernel)  # the kernel that the first run above tuned
job = telescopic.sample(
    gaussian.log_prob,
    gaussian.initial,
    kernel=pickle.loads(tuned),
    k=first.k,
    rng=4,
)
job.tuning, job.pilot
(None, None)

The job ran no tuning and no pilot.

Chunks and workers

A pool runs chunks of consecutive replicate indices: one per worker at least, more where a chunk would hold more than 256 replicates, the lanes that the engine advances together, and four per worker at most, unless a chunk would then hold more than 1,024 replicates. For \(R\) replicates on \(W\) workers, that is \(\max(\lceil R / 1024 \rceil, \min(R, 4W, \max(W, \lceil R / 256 \rceil)))\) chunks, of sizes that differ by at most one. Up to 4,096 replicates per worker, the limit of 1,024 changes nothing: 2,000 replicates on 4 workers make 8 chunks of 250. Beyond it, the chunks hold at most 1,024 replicates whatever the number of workers: 100,000 replicates on 4 workers make 98 chunks of 1,020 or 1,021, and 1,000,000 on 4 or 64 workers make 977 of 1,023 or 1,024. An executor receives every chunk at once, in index order; a pool with only map receives them in waves of one chunk per worker, so a long run on such a pool takes many waves, each as long as its slowest chunk.

telescopic reads the number of workers of an integer pool, a concurrent.futures executor, a multiprocessing pool and a schwimmbad pool. It counts any other pool as having as many workers as this process may use CPUs, so the chunks of a larger pool, such as a cluster’s, can leave workers idle. The argument n_workers states the number of workers of an executor or a pool, and replaces the size that the pool reports, if any. It sets the chunks and the waves, and with a log-density evaluated point by point it changes no replicate. State the pool’s real number of workers: a larger value makes smaller chunks, which run fewer replicates together. The executor below shows only submit, as a cluster’s may, so telescopic cannot read its two workers:

class Unsized:
    """An executor that does not report its number of workers."""

    def __init__(self, executor):
        self.submit = executor.submit


with ProcessPoolExecutor(2, mp_context=spawn) as executor:
    stated = telescopic.sample(
        gaussian.log_prob, gaussian.initial, pool=Unsized(executor), n_workers=2, rng=3
    )
stated.n_replicates
100

n_workers is only for an executor or a pool of your own: with pool=None or an integer, which already is the number of workers, it raises ValueError.

Each chunk carries the whole job: the target with its args and kwargs, the kernel, the initial distribution, the root seed and the settings. The results are joined in index order; n_log_prob and n_grad add up the workers’ counts, and wall_time is this process’s.

A task in the main thread of another process runs with BLAS limited to one thread, so that the workers do not compete for the cores, and ignores Ctrl-C, which this process handles. A task in this process, such as one on a thread pool, leaves the process’s settings alone.

Reproducibility

R = 2,000 replicates, 4 workers: 8 chunks of 25005001,0001,5002,000chunk 1: indices 0 to 249, run together012345…each from the root seed and its index: a stream of its own

A run of 2,000 replicates on a pool of 4 workers: its indices cut into 8 chunks of 250 consecutive indices, the first opened below, where each index has a random stream of its own, derived from the root seed and the index.

Each replicate draws from a random stream of its own, derived from the root seed and its index, so its output does not depend on where it runs. With a log-density evaluated point by point (vectorize=False, the default), the replicates are bitwise identical in any pool, with any number of workers and chunks, on one machine with the same NumPy and SciPy versions; generator algorithms, SciPy’s samplers and BLAS builds can change between versions and machines.

With a vectorized log-density (vectorize=True), the kernels also compute their matrix products for a batch of chains at once, with BLAS: whole runs of 256 replicates on a Gaussian target of 200 dimensions took 2.1 times less processor time with RandomWalk, whose pairs all ran to the iteration cap, and 3.4 times less with MALA. BLAS can round a chain’s products differently with the other chains of its batch and with the number of BLAS threads. A vectorized run is therefore bitwise identical when repeated only with the same seed and settings, the same pool and n_workers, which set how the replicates are batched, the same BLAS build and the same number of BLAS threads. A vectorized run on a pool can differ from one in this process for two reasons: the pool runs the replicates in chunks, which are other batches unless it makes a single chunk, and worker processes run BLAS on one thread, which this process does only when limited to one, with threadpoolctl.threadpool_limits(1). Between such runs, as between runs with other numbers of workers or chunks, merged runs and a sampler’s later calls, a replicate can differ by rounding, and a difference of rounding can change an acceptance or the step at which the two chains become equal: the replicate’s meeting time, and with it its whole output, can then differ. The estimates agree within their error bars. With HMC with a fixed step (jitter=0) on a Gaussian of 2 dimensions, the same 64 replicates run one at a time and all at once differed in 17 meeting times, and the estimates of the mean from all 64 by at most 0.067 standard errors.

A sampler that resumes a result (telescopic.CoupledSampler.resume()) adopts its seed and indices. With a log-density evaluated point by point, its replicates are bitwise those of the same indices in one uninterrupted run, whatever the pool, the number of workers or the batches, and with a kernel tuned again from the result’s seed too. With a vectorized one, a resumed run(n) is bitwise the original sampler’s next run(n) under the same pool, n_workers, BLAS build and number of BLAS threads, since both batch the same indices in the same way, and it can differ by rounding from one run of all the replicates, with estimates that agree within their error bars.

Functions of your own that call multithreaded BLAS or LAPACK, such as a SciPy multivariate normal of 200 dimensions as the initial distribution, can also differ by rounding between this process and workers with a log-density evaluated point by point, since this process keeps its BLAS threads. Limiting it to one thread makes them agree again. We compare the first run above, on two workers, with the same run in this process:

here = telescopic.sample(gaussian.log_prob, gaussian.initial, rng=3)
(
    np.array_equal(here.meeting_times, first.meeting_times),
    np.array_equal(here.measure.atoms, first.measure.atoms),
    np.array_equal(here.measure.weights, first.measure.weights),
)
(True, True, True)

Pickling and the main guard

Every pool, a thread pool included, runs the pilot pairs and the replicates on pickled copies of the target, the kernel and the initial distribution; tuning runs in this process, on your objects. Side effects of the log-density on a pool, such as a call counter or a cache, therefore happen on the copies and are not seen on your objects. An object that cannot be pickled, such as one that holds a threading.Lock, cannot run on a pool: telescopic raises TypeError. The copies travel with every chunk, once per 1,024 replicates in a long run, so keep the data that a log-density holds small; data that it reads from a global of a module the workers import is not sent.

With cloudpickle installed (the parallel extra), telescopic pickles them with cloudpickle, which also sends lambdas and functions defined in a notebook or a script. Without cloudpickle, the standard pickle needs functions defined at the top level of an importable module, as the log-density of telescopic.examples.gaussian() above: a lambda raises TypeError, and a function that a worker cannot import, such as one defined in a notebook, raises RuntimeError, each with that advice.

Under the spawn and forkserver start methods, the worker processes import the main script, and telescopic’s own workers always use spawn. A script that runs on such a pool must keep its work under the if __name__ == "__main__": guard; without it, each worker runs the script again, and the run fails. A notebook needs no guard.

import numpy as np

import telescopic


def log_prob(theta):
    return -0.5 * np.sum(theta**2)


if __name__ == "__main__":
    init = telescopic.initial.Normal([0.0, 0.0], [4.0, 4.0])
    result = telescopic.sample(log_prob, init, pool=4, rng=1)
    print(result.summary())

Interrupting a run

The first Ctrl-C during the replicates of a run starts no new replicate and lets those in progress finish. In this process they run 256 at a time, so a run of 256 or fewer has started them all, and Ctrl-C then waits for them. The run then returns a result flagged interrupted, with every replicate that started, and telescopic prints that a second Ctrl-C stops at once. Its estimates are consistent but not exactly unbiased, since the number of replicates that ran depends on their costs, and its summary says so. The sampler’s next run starts with the missing replicates, so a run of as many as are missing completes the requested set, which restores exact unbiasedness:

sampler = telescopic.CoupledSampler(gaussian.log_prob, gaussian.initial, rng=1)
result = sampler.run(1000)  # Ctrl-C once while it runs
result.interrupted  # True: some of the 1000 replicates never started
result = sampler.run(1000 - len(result.index))  # the missing replicates
result.interrupted  # False

A first Ctrl-C after the replicates, while the result is built, lets the run finish too. A second Ctrl-C raises KeyboardInterrupt at once, without a result, and stops the workers that telescopic started. The tuning and the meeting-time pilot have no result to return early, so Ctrl-C there does what your handler does, by default raise KeyboardInterrupt. telescopic handles Ctrl-C only in the main thread; a run in another thread leaves it alone, and so does a process that ignores Ctrl-C, such as a worker of your own pool, or whose Ctrl-C handler was not set by Python, such as R’s through reticulate.

On a pool, telescopic’s workers start no new replicate after the first Ctrl-C, and a chunk that starts afterwards runs nothing, unless it is the first, so that the result holds at least one replicate. On an executor of your own, the running chunks finish and the chunks not yet started are canceled, except those that the executor has already queued for its workers: a ProcessPoolExecutor queues up to one more chunk than it has workers. Those chunks run in full and the result includes their replicates, so the run can take up to two chunk durations longer to return. A pool with only map returns the waves it completed. How the rest of a pool of your own reacts to Ctrl-C is up to the pool. A process pool of your own should ignore Ctrl-C in its workers, as telescopic’s do: ProcessPoolExecutor(4, initializer=signal.signal, initargs=(signal.SIGINT, signal.SIG_IGN)). Otherwise Ctrl-C kills its idle workers and breaks the pool: the run returns the chunks that had finished, flagged interrupted, or raises BrokenProcessPool if none had, and the pool cannot run again.

Errors

An error in a worker, such as one of the log-density, stops the run as a first Ctrl-C does, except that no chunk starts afterwards, not even the first: the running chunks finish, and the replicates of every chunk that returned are kept, with those finished before the error in its own chunk. The error is raised again in this process with the result of the kept replicates attached (Continuing after an error). An error that cannot be unpickled in this process, such as one whose class needs two arguments, is replaced by a RuntimeError that names its type and message, and an error from a worker process carries a note with the traceback in the worker. When several chunks fail, the error of the lowest-indexed one is raised and the note counts the others. A pool that breaks without a Ctrl-C, and an error raised in this process while it waits, such as a warning made an error by a warnings filter, stop the run in the same way. On a ProcessPoolExecutor of your own the chunks it has already queued run in full, and a pool with only map loses the other results of a wave whose map raised.

Progress

progress=True, given to telescopic.sample(), to telescopic.CoupledSampler or to one call of run, shows the progress of tuning, in steps of its chains, and of the meeting-time pilot and each run, in replicates finished: a tqdm text bar on stderr with the progress extra, and otherwise a line on stderr every 10 seconds and when each phase ends. Tuning runs in this process, as two phases for MALA and HMC: the adaptive pilot chains, then the step size. On a pool, the count of replicates moves as chunks finish.

Memory

The workers send the signed measures of their replicates back to this process, which holds them all. A worker holds those of one chunk at a time, at most 1,024 replicates, and sends them back when the chunk ends, so its memory does not grow with the number of replicates; the memory of this process does, since it keeps every chunk’s replicates and then joins them. Settings gives their size, the telescopic.InputWarning that the sampler emits when the run and its first estimates would take more than 1 GB, and thin and keep, which store fewer. With keep, each engine also holds the sums of the moments of its 256 lanes, 20.9 MB at \(d = 100\), so an integer pool holds that once per worker.