24  Parallel Computing in R

24.1 Prerequisites

Answer the following questions to see if you can bypass this chapter. The answers appear at the end of the chapter in Section 24.17.

  1. What is the primary advantage of parallel computing for statistical problems?
  2. What kind of statistical computation is most suitable for parallel processing, and why?
  3. Why is using the maximum number of available cores not always the optimal choice?

24.2 Learning objectives

By the end of this chapter you should be able to:

  • Distinguish between embarrassingly parallel, data-parallel, and inherently sequential problems.
  • Parallelize a simulation or bootstrap with future.apply or furrr.
  • Pick an appropriate backend (multisession, multicore, cluster) for your platform.
  • Generate reproducible random numbers in parallel via future.seed = TRUE (which uses the L’Ecuyer-CMRG generator).
  • Report speedup and efficiency, accounting for overhead and Amdahl’s law.
  • Avoid common pitfalls: incorrect RNG streams, global state, large object serialization, BLAS thread oversubscription.

24.3 Orientation

Most simulations and bootstraps are embarrassingly parallel. That is, each iteration is independent of the others. Running them in parallel often produces near-linear speedup with a trivial code change. In this chapter we shall show how to do that correctly and how to recognize the cases in which parallelism does not help.

The modern R parallel ecosystem centers on the future package by Henrik Bengtsson. Together, future, future.apply, and furrr provide a unified API that abstracts over the choice of backend (cores on a single machine, multiple machines, HPC clusters). Older packages (parallel, foreach, doParallel) still work and are widely deployed. Nevertheless, future is the recommended modern interface for most applications.

We begin with the judgments that fall to the statistician and with the question of when parallelism helps at all. We then present the future framework, the future.apply and furrr interfaces, and the measurement of speedup. The chapter closes with common pitfalls, a worked parallel bootstrap, and the cases in which we should not parallelize.

24.4 The statistician’s contribution

Parallelism is a tool for trading developer time for machine time. The judgments concern when that trade is worth making.

Profile before parallelizing. A simulation that takes 30 seconds in serial does not need parallelism, since the time spent setting up future.apply exceeds the saving. A simulation that takes 30 minutes is worth parallelizing, and one that takes 30 hours makes parallelism essential. We profile first to learn which case applies.

Reproducibility is non-trivial. Naive parallel code with set.seed() does not produce reproducible results across workers. Each worker may draw from the same RNG stream, which produces correlated (or identical) results. Alternatively, the workers may draw from independent streams set up with the L’Ecuyer-CMRG generator. Detecting the difference is the analyst’s responsibility, because software defaults vary across packages.

Mind the data. Parallel workers receive copies of the global state. A 5 GB dataset in the R session becomes 5 GB on each worker, so 8 workers use 40 GB of memory. For small data this is acceptable. For large data, the data should instead be loaded inside the worker function, or shared-memory techniques should be used.

Mind the BLAS. R’s matrix operations dispatch to BLAS, which may itself be multi-threaded (OpenBLAS, MKL). Running 8 R workers, each with 8 BLAS threads, means 64 threads competing on probably 8 physical cores. The typical fix is to call RhpcBLASctl::blas_set_num_threads(1) inside the worker, so that BLAS does not spawn additional threads. Unfortunately, this pitfall stays invisible until we measure the timing and find the ‘parallel’ code slower than serial.

24.5 When does parallelism help?

But when does parallelism actually help? We distinguish three categories of problem.

Embarrassingly parallel. Each task is independent of the others. Examples are bootstrap resamples, Monte Carlo simulation replicates, and fitting the same model to many strata. Speedup scales nearly linearly with the number of cores, up to overhead. This is the dominant case in statistical computing.

Data parallel. A single computation can be split across cores by partitioning the data. Examples are matrix multiplication, a large-scale sum, and distributed gradient descent. This form is useful but harder to implement, and modern BLAS handles small-scale data parallelism automatically. For massive data, frameworks such as Spark or arrow are typically more appropriate.

Inherently sequential. Each step depends on the previous one. Examples are a single MCMC chain, a stochastic gradient descent trajectory, and a forward simulation of a dynamical system. No amount of parallel hardware can speed up a serial dependency.

For sequential problems we can sometimes parallelize at a higher level. A common case is to run several MCMC chains in parallel. Another is to split the data into independent batches and fit separate models to each. Either approach requires finding the boundary at which independence holds.

24.6 The future framework

future provides a unified interface across parallel backends:

library(future)

# choose a backend
plan(sequential)        # no parallelism (default)
plan(multisession)      # multiple R sessions on this machine
plan(multicore)         # forking, Linux/macOS only
plan(cluster, workers = 4)
plan(future.batchtools::batchtools_slurm)   # HPC cluster

multisession is the cross-platform default. It starts \(k\) fresh R processes, and each receives a copy of the workspace as needed.

multicore (Linux/macOS only) uses operating-system forking. It has faster startup than multisession and shares memory until a worker writes (copy-on-write). It does not work in RStudio because of fork-safety issues.

cluster lets us specify worker machines explicitly, which is useful for HPC.

The ‘plan’ is set globally for the session. Code using the future API (or future.apply, or furrr) then runs according to the current plan without code changes.

24.7 future.apply and furrr

These packages re-implement the apply and purrr families on top of future:

library(future)
library(future.apply)

plan(multisession, workers = 4)

# parallel sapply / lapply / mapply / vapply
results <- future_sapply(1:1000,
                         FUN = function(i) {
                           # one bootstrap replicate
                           x <- sample(data, length(data), replace = TRUE)
                           mean(x)
                         },
                         future.seed = TRUE)

future.seed = TRUE activates the L’Ecuyer-CMRG generator internally, which ensures that each worker uses an independent, non-overlapping RNG stream. Without it, we may get correlated (or identical) sequences across workers.

furrr does the same for the purrr map functions:

library(furrr)
plan(multisession, workers = 4)

results <- future_map_dbl(1:1000,
                          ~ {
                            x <- sample(data, length(data), replace = TRUE)
                            mean(x)
                          },
                          .options = furrr_options(seed = TRUE))

For most modern code, furrr is the recommended choice because its API matches purrr. Existing serial code using map_dbl becomes parallel by replacing it with future_map_dbl.

Question. You parallelize a bootstrap with future_map_dbl(1:1000, my_boot_fn) without furrr_options(seed = TRUE). The results across runs are not reproducible, and worse, two workers sometimes produce identical sequences of bootstrap statistics. What is going on?

Answer.

Without explicit parallel-safe RNG handling, each worker inherits the parent process’s RNG state at the moment of forking. Depending on the backend, it may instead start with an undefined state. Two workers can therefore end up using identical seeds and produce correlated or identical sequences. The solution is furrr_options(seed = TRUE) (or future.seed = TRUE for future_*apply). This activates the L’Ecuyer-CMRG generator and assigns each worker an independent stream. The behavior is deterministic given the parent seed, so re-running with the same parent seed produces identical results across workers and across re-runs. Forgetting this option is among the most common bugs in parallel R code. Part of the reason is that it produces results that look reasonable but are silently miscalibrated.

24.8 Measuring speedup

Three quantities matter:

  • Speedup: \(T_1 / T_n\), the ratio of serial to parallel time.
  • Efficiency: speedup divided by the number of workers. 100% means linear scaling; below 100% means overhead is reducing returns.
  • Amdahl’s law: the maximum speedup is bounded by \(1 / (s + (1 - s)/n)\), where \(s\) is the serial fraction and \(n\) is the number of workers. If 10% of the computation is inherently serial, the maximum speedup is 10× no matter how many workers we have.
# serial
t_serial <- system.time({
  results_serial <- purrr::map_dbl(1:1000, my_boot_fn)
})

# parallel
plan(multisession, workers = 4)
t_par <- system.time({
  results_par <- furrr::future_map_dbl(1:1000, my_boot_fn,
                                        .options = furrr_options(seed = TRUE))
})

speedup <- t_serial[3] / t_par[3]
efficiency <- speedup / 4
c(speedup = speedup, efficiency = efficiency)

Typical patterns for embarrassingly parallel code are as follows:

  • Tiny per-iteration work (microseconds): parallelism is net slower because of serialization overhead.
  • Moderate per-iteration work (milliseconds to seconds): near-linear speedup up to about \(n_\text{cores}\).
  • Heavy per-iteration work (minutes): linear speedup up to saturation; possibly diminishing returns beyond.

For the modest per-iteration work typical of a bootstrap or simulation, we expect 70 to 90% efficiency on 4 to 8 cores. Efficiency is lower on 16+ cores because of overhead and contention.

24.9 Common pitfalls

RNG. We covered this above; the remedy is future.seed = TRUE / furrr_options(seed = TRUE).

Global state. Workers receive a copy of the workspace needed to run the function. Variables not mentioned in the function body are not copied, which saves time and memory. However, variables hidden in environments may be missed. The modern future API tries to detect dependencies automatically, and for unusual cases we use furrr_options(globals = ...).

BLAS oversubscription. Calling RhpcBLASctl::blas_set_num_threads(1) inside the worker prevents BLAS from spawning additional threads:

plan(multisession, workers = 4)

future_map_dbl(1:1000, function(i) {
  RhpcBLASctl::blas_set_num_threads(1)
  RhpcBLASctl::omp_set_num_threads(1)
  # ... heavy linear algebra computation ...
})

Large data copies. A 5 GB dataset replicated across 8 workers consumes 40 GB. There are three remedies:

  1. Load data inside the worker function rather than from the global environment.
  2. Use a shared-memory backend (e.g., bigmemory), or keep the data on disk and read it on demand (e.g., Parquet files opened with arrow).
  3. Reduce the data: workers operate on a summary or a subset.

Oversubscription from over-parallelization. Spawning more processes than cores is rarely useful and often counter-productive. parallelly::availableCores() reports the canonical ‘how many cores can I use’ value, and it respects HPC scheduler limits.

24.10 Worked example: parallel bootstrap

library(future)
library(furrr)
library(palmerpenguins)

plan(multisession, workers = 4)

penguins_clean <- na.omit(penguins)

boot_one <- function(i, data) {
  resampled <- data[sample(nrow(data), replace = TRUE), ]
  mean(resampled$body_mass_g)
}

set.seed(1)
boot_means <- future_map_dbl(
  1:10000,
  ~ boot_one(.x, penguins_clean),
  .options = furrr_options(seed = TRUE)
)

quantile(boot_means, c(0.025, 0.5, 0.975))

For 10,000 bootstrap replicates, each taking ~1 ms, this parallelizes cleanly across 4 cores, with about a 4× speedup compared to a serial version.

For the same data and a larger per-iteration cost (e.g., fitting a model on each resample), the speedup approaches \(n_\text{cores}\). The reason is precisely that the per-iteration cost dominates the per-iteration overhead.

24.11 When not to parallelize

  • Computation already fast. Code that runs in 5 seconds is not worth the engineering effort.
  • Sequential dependencies dominate. Examples are a single MCMC chain, or a reduce/scan that mathematically requires sequential evaluation.
  • Memory pressure. If the data are large and the per-iteration work is small, the cost of copying the data to workers exceeds the work saved.
  • Many small tasks with serialization overhead. future_map_dbl(1:10000, function(i) i^2) is slower than the serial version, because the overhead per task exceeds the work per task.

The general rule is to parallelize when the per-iteration work is dominant and the iterations are independent.

24.12 Collaborating with an LLM on parallel R

LLMs handle the basic parallel APIs reasonably well. They often fall short, however, on the subtle correctness issues (RNG, BLAS, memory).

Prompt 1: parallelizing a serial loop. Paste the serial loop and ask: ‘parallelize this with furrr and ensure reproducible random numbers.’

What to watch for. The LLM should produce code with furrr_options(seed = TRUE). If it does not, push back explicitly, since the default behavior (no seed handling) is a silent correctness bug.

Verification. Run twice with the same parent seed and verify that the results are identical. If they differ, the seed handling is wrong.

Prompt 2: diagnosing poor speedup. Describe the benchmark (e.g., ‘4 cores, expected 4× speedup, observed 1.5×’) and ask: ‘what could be limiting parallel efficiency?’

What to watch for. The standard suspects are BLAS oversubscription, large data copies, small per-iteration work, and hyperthreading limits. The LLM should mention several of these. If it fixates on one, push for the full list.

Verification. Apply each fix in turn and remeasure. Sometimes the fix is to give up and accept that this particular problem does not parallelize well.

Prompt 3: choosing a backend. Describe the platform (macOS laptop, Linux HPC, Windows desktop) and ask: ‘which future plan should I use?’

What to watch for. multisession is the safe cross-platform default. multicore is faster on Linux/macOS but does not work in RStudio. cluster backends require more setup. The LLM should know these trade-offs.

Verification. Try the recommended plan and verify that it runs on your platform. If it errors with ‘not supported on Windows’ or similar, switch to multisession.

24.13 Principle in use

Three habits define defensible parallel computation:

  1. Profile before parallelizing. Do not add parallel overhead to code that is already fast enough.
  2. Always use seed-aware parallel APIs. Use future.seed = TRUE or furrr_options(seed = TRUE). Without them, results are silently miscalibrated.
  3. Mind the BLAS. For matrix-heavy parallel code, set per-worker BLAS threads to 1 to prevent oversubscription.

24.14 Exercises

  1. Run a 10,000-replicate simulation sequentially with purrr::map(). Parallelize it with furrr::future_map() and a multisession plan. Time both and compute the speedup on your machine.
  2. Repeat exercise 1 using a multicore plan on macOS or Linux. Compare to multisession. Explain any difference in speed.
  3. Construct an example where parallelism slows the computation down (hint: small per-iteration work, large data copying). Document why.
  4. Fit a logistic regression on each bootstrap resample in parallel. Use furrr_options(seed = TRUE) and verify reproducibility. Confirm BLAS is not oversubscribing your cores.
  5. Run a parallel benchmark with 1, 2, 4, 8, and 16 workers (or as many as you have). Plot the speedup vs. workers. Where does efficiency drop sharply?

24.15 Further reading

  • The future ecosystem documentation at futureverse.org, the modern parallel-R reference.
  • (Bengtsson, 2021), the JSS paper on future.
  • (Rizzo, 2019) Chapter 16, parallel and foreach in the context of simulation studies.
  • Eddelbuettel (2021), ‘Parallel computing with R: a brief review’, WIREs Computational Statistics 13(2), e1515.

24.16 Practice test

The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.

24.16.1 Question 1

What is the primary advantage of using parallel computing in R for statistical applications?

    1. It always makes code run faster regardless of the problem size
    1. It allows multiple independent computations to be performed simultaneously, reducing total execution time for suitable problems
    1. It automatically optimizes R code without requiring any programming changes
    1. It eliminates the need for writing loops in R

B. Parallel computing speeds up problems that decompose into independent tasks. It is not a universal speedup.

24.16.2 Question 2

Which type of statistical computation is most suitable for parallel processing?

    1. Sequential iterative algorithms where each step depends on the previous result
    1. Simple arithmetic on small datasets
    1. Embarrassingly parallel problems such as bootstrap resampling where computations are completely independent
    1. Interactive data exploration

C. Embarrassingly parallel problems have no serial dependence between tasks and scale almost linearly with the number of workers.

24.16.3 Question 3

What is the most important consideration when deciding how many processor cores to use?

    1. Always use the maximum number of cores available
    1. The number of cores should equal the number of observations
    1. Balance overhead against gains; using fewer than maximum is often optimal for system responsiveness and avoids BLAS oversubscription
    1. The number of cores has no effect on performance

C. Saturating every core incurs overhead and degrades system responsiveness. The optimal worker count balances these costs against the gains.

24.16.4 Question 4

You parallelize a bootstrap with future_map but forget furrr_options(seed = TRUE). What is the most likely consequence?

    1. The code will not run.
    1. Workers may use correlated or identical RNG streams, biasing the bootstrap distribution.
    1. The parallel speedup is reduced.
    1. Memory usage increases.

B. Without explicit parallel-safe RNG, the seed state across workers is undefined or correlated, and the results are silently miscalibrated.

24.16.5 Question 5

You see only 1.5× speedup on 4 cores for a parallel linear-algebra-heavy computation. The most likely cause is:

    1. RNG misconfiguration.
    1. BLAS oversubscription: each worker spawns multiple BLAS threads, so 4 workers × 4 BLAS threads contend for 4 physical cores.
    1. Insufficient workers.
    1. The serial code is faster than parallel.

B. The standard fix is to call RhpcBLASctl::blas_set_num_threads(1) inside each worker. Contention from competing BLAS threads often appears as ‘parallel is barely faster than serial’ on linear-algebra-heavy code.

24.17 Prerequisites answers

  1. Parallel computing allows multiple independent computations to run simultaneously on multiple cores or machines. This reduces total wall-clock time for suitable problems. It is not a universal speedup, since problems with strong serial dependencies cannot benefit.
  2. Embarrassingly parallel problems, whose work decomposes into fully independent tasks, are most suitable. Bootstrap resampling and simulation replicates are canonical examples. Problems with serial dependence (e.g., a single MCMC chain) are not. Multi-chain MCMC, however, is embarrassingly parallel at the chain level.
  3. Each parallel task incurs overhead (worker startup, data serialization, result collection). Using every core can therefore slow a small computation rather than speed it up. System responsiveness also degrades when every core is saturated. For matrix-heavy code, BLAS oversubscription compounds the problem: \(k\) workers each spawning \(m\) BLAS threads is \(km\) threads competing on (typically) \(k\) physical cores.