1.6 Reproducible Random Numbers in Parallel
1.6.1 Motivation
Simulations, bootstrap resamples, and permutation tests depend on reproducible random numbers. Parallel execution complicates that, and setting one seed is not enough. What matters is which streams the workers draw from and when they advance them, and a design that works for four workers must still give identical results for eight or forty.
1.6.2 The problem
Consider a simulation running on sixteen workers. Each worker draws one thousand random deviates. If every worker starts with the same seed and calls rnorm() in the same order, each worker produces identical results. The simulation is wrong.
set.seed(1)
results <- parallel_map(1:16, function(i) {
rnorm(1000) # same seed, different output needed
})If each worker independently reseeds from a global seed counter, the counter races. Two workers draw the same sequence number, call rnorm(), and get the same values. Results duplicate unexpectedly.
A harder requirement is that results reproduce at any worker count. A simulation reproducible with four workers must produce identical tail statistics with forty workers. This means the Random Number Generator (RNG) state must not depend on the number of workers, task scheduling, or whether a task retries.
1.6.3 Mental model: independent streams
The solution is independent random streams. Each task receives its own stream of random numbers: task 1 uses stream 1, task 2 uses stream 2, and no two streams overlap across any realistic number of draws.
The streams are slices of one very long sequence. In R’s L’Ecuyer-CMRG implementation, each stream starts 2^127 (about 1.7 × 10^38) positions after the start of the one before, far more than any task will draw. Because the index belongs to the task and not to the worker, it does not matter which worker picks a task up, or how many tasks that worker has already run.
Another approach draws all the random numbers once, in the main process, and hands each task its share. The parallel package vignette recommends it where possible, and package boot does it. It needs every number up front, which stops working when tasks draw many numbers or do not know in advance how many they need.
1.6.4 L’Ecuyer-CMRG
R’s stream generator is L’Ecuyer-CMRG (combined multiple recursive generator), which base R provides through RNGkind("L'Ecuyer-CMRG"). Its seed is six integers and its period is about 2^191.
What makes it suitable is that its state can jump ahead. The recursion is linear, so advancing it by a fixed number of steps is one multiplication by a precomputed matrix. parallel::nextRNGStream() uses this to jump 2^127 steps to the start of the next stream, and nextRNGSubStream() jumps 2^76 steps to the next substream. Reaching stream 47 takes 47 such jumps, and none of the numbers in between are generated.
parallel::clusterSetRNGStream() seeds L’Ecuyer-CMRG in the main process, computes one stream per worker with nextRNGStream(), and sets each worker’s .Random.seed to its stream. The streams belong to workers, not to tasks, so the results still depend on which tasks each worker runs.
sunlight assigns streams per task instead. In pmap(), element i gets stream i, which sunlight derives from the pool’s seed in the main process before any scheduling and installs in the worker just before the task runs. The results are bit-identical at any worker count or chunking.
1.6.5 Reproducible results vs. reproducible execution order
Reproducible results means the same numbers on every run. Reproducible execution order means task 47 runs on the same worker each time, and parallel R does not promise that.
Task 47 can run on worker 3 this time and on worker 1 next time, depending on scheduling. With per-task streams the RNG does not care: task 47 draws from stream 47 whichever worker runs it.
Per-task streams isolate the RNG from scheduling noise. Retrying a task, reordering tasks, or changing worker count does not change results.
1.6.6 Failure without independent streams
Shared generator without protection. If worker threads share one global RNG and race to advance it, the sequence becomes unpredictable. (Separate R processes cannot share a generator, but threads in one process can.) Two workers call rnorm() almost simultaneously. Each reads the current state, advances it, and writes the result back. The last writer wins, and the earlier read is lost. Both workers advanced from the same state, so both return the same numbers, and the simulation counts the same draws twice.
Naive independent reseeding. Each worker sets its own seed independently before starting. Workers 1 and 2 both seed with 1 plus their ID, so they draw from different seeds. But the sequence depends on which tasks run in which order. Rerun the simulation with a different task ordering, and the results change, tail of the distribution included.
Per-worker persistent streams without task partition. Each worker maintains one persistent RNG stream for all its tasks. Worker 1 advances its stream once per task. But if task assignment changes, task 50 draws from different positions in the stream. The results depend on scheduling, not task identity. Running tasks in order 1, 2, 3 produces different results than order 3, 2, 1. This is what clusterSetRNGStream() gives you, and what mclapply() gives you with its default prescheduling.
1.6.7 Stakes for scientific work
A reviewer asks you to rerun a published simulation. If your parallel code does not reproduce its own results at the same worker count, much less on a machine with a different count, you cannot show that the numbers in the paper came from the code.
In machine learning, reproducible RNG matters for train-test splits, stochastic gradient descent, and model selection. Changing parallelism strategy must not change learned models.
In production data processing, retries must be idempotent. If a task fails midway through a bootstrap, you retry it. If the retry draws different numbers, the result changes. When failures depend on the draw, for example a resample on which the model does not converge, retrying until success drops those draws and biases the estimate.
1.6.8 Current practice in R
A new PSOCK cluster does not set up streams at all: each worker seeds itself from the clock and its process ID the first time it draws, which gives different streams that cannot be reproduced. clusterSetRNGStream(cl, iseed) makes them reproducible, with one stream per worker. mclapply() gives each forked child the next stream once you select RNGkind("L'Ecuyer-CMRG") and set a seed, so its results reproduce only while the same tasks go to the same children, which with the default prescheduling means the same mc.cores. With mc.preschedule = FALSE it forks one child per element, in index order, so element k gets the k-th stream at any mc.cores of 2 or more, at the cost of one fork per element. With one core, or one element, mclapply() calls lapply() in the parent and forks nothing. Elsewhere, for a stream per task, compute the streams in the main process with nextRNGStream() and pass one to each task.
The future ecosystem computes one L’Ecuyer-CMRG stream per future, or per element, in the main process: future(..., seed = TRUE) in future, future.seed = TRUE in future.apply’s functions, and furrr_options(seed = TRUE) in furrr. With future.apply 1.20.2, future_sapply(..., future.seed = 42) returned identical numbers on two workers, on three workers and sequentially. It is opt-in. A future that draws random numbers without it still runs, with an “UNRELIABLE VALUE” warning.
mirai gives each daemon its own L’Ecuyer-CMRG stream by default, which is statistically sound but not reproducible, since the daemon that runs a task can vary. daemons(n, seed = 42) switches to one stream per task, reproducible whichever daemon evaluates it.
sunlight derives a stream per task from the pool’s seed, as described above, without being asked.
Further reading
- R Core Team, Package ‘parallel’ <https://stat.ethz.ch/R-manual/R-devel/library/parallel/doc/parallel.pdf>, the package vignette. Its section “Random-number generation” covers streams,
clusterSetRNGStream()andmclapply(). - L’Ecuyer, P. (1999). “Good parameters and implementations for combined multiple recursive random number generators.” Operations Research 47(1): 159-164. doi:10.1287/opre.47.1.159 <https://doi.org/10.1287/opre.47.1.159>
- L’Ecuyer, P., Simard, R., Chen, E. J. and Kelton, W. D. (2002). “An object-oriented random-number package with many long streams and substreams.” Operations Research 50(6): 1073-1075. doi:10.1287/opre.50.6.1073.358 <https://doi.org/10.1287/opre.50.6.1073.358>
?RNGkind<https://stat.ethz.ch/R-manual/R-devel/library/base/html/Random.html>, R’s help page for its random number generators, L’Ecuyer-CMRG included.
Where this appears
- sunlight Per-task L’Ecuyer-CMRG RNG streams are bit-identical at any worker count or chunking.
- threaded-r Each interpreter keeps its own RNG state, and clusterSetRNGStream() on a THREAD cluster matches PSOCK bit for bit.