sim_slope = function(n, slope, beta = 0.5) {
x = rnorm(n)
y = beta * x + rnorm(n)
slope(x, y)
}
slope_lm = function(x, y) lm(y ~ x) |> coef() |> _[["x"]]Lecture 19
Intuition about where a program spends its time is often wrong.
Before rewriting anything,
profile the whole task to find the slow part,
benchmark alternatives for that part,
then decide whether parallelization is worth it.
Most of the time the fix is a better algorithm or a vectorized call, not more cores.
The sampling distribution of a regression slope. sim_slope() simulates one dataset and hands it to a function that estimates the slope, and we repeat that 20,000 times,
A few seconds for 20,000 fits of 100 points each. Is it the random numbers, the fit, or the map?
profvisprofvis::profvis() runs an expression while recording the call stack every 10 ms, then reports how often each line and function was on the stack. The functions are defined inside the profiled block so their lines appear in the code panel.
The code panel attributes time and memory to each line. Nearly all of it lands on the lm() line, and the random draws barely register.
The flame graph shows the call stack over time, zoomed here to a 175 ms window. Inside lm() the time goes to model.frame(), model.matrix(), and evaluating the formula. lm.fit(), which does the arithmetic, is a thin slice.
Hovering a bar gives the function and its time, and the Data tab gives the same information as a tree.
The formula interface costs about 100 µs per call however small the data. lm.fit() takes the design matrix directly, and a simple regression slope is just cov(x, y) / var(x),
Both are about ten times faster. The profile pointed at the overhead around the fit, not the fit itself.
bench::mark()Once there are alternatives, bench::mark() runs each expression repeatedly and summarizes the timings and memory use. By default it first checks that every expression returns the same result,
# A tibble: 3 × 6
expression min median `itr/sec` mem_alloc `gc/sec`
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
1 lm 106.93µs 118.65µs 7930. 437.27KB 14.4
2 lm.fit 8.86µs 10µs 88880. 7.34KB 17.8
3 cov_var 7.5µs 8.36µs 110221. 0B 11.0
| Column | Meaning |
|---|---|
min, median |
Fastest and typical time per iteration |
itr/sec |
Iterations per second, the inverse of the mean time |
mem_alloc |
Memory allocated by one iteration |
gc/sec |
Garbage collections per second |
n_itr |
Iterations retained after garbage collection filtering |
n_gc |
Garbage collections across all iterations |
total_time |
Total time of the retained iterations |
Each expression runs until min_time (0.5 s) has passed or max_iterations (10,000) is reached, so slow expressions get few iterations and fast ones get many.
bench::press()How does the cost of one fit change with the number of points?
press() runs the benchmark at every combination of parameter values, here just the five sizes.
Up to a few thousand points the fixed cost of lm() dominates. Past that the arithmetic grows with n and the three converge.
Most machines have many cores and R uses one of them (mostly). Tasks that split into independent pieces can make use of the multiple cores,
simulation studies and bootstrap resampling,
cross validation and tuning grids,
fitting the same model to many groups,
processing many files.
Each piece has a cost beyond the computation itself, starting a process, sending it the data it needs, and sending the result back. Parallelization helps when the pieces are slow relative to that overhead.
detectCores()The parallel package is part of base R and reports the number of cores it can see, as does os in Python,
Treat this number as an upper bound rather than a target,
it counts logical cores. detectCores(logical = FALSE) gives the physical count,
recent CPUs mix performance and efficiency cores, and work on the slow cores runs slower,
a multithreaded BLAS, data.table, duckdb, and polars already use several cores, so workers running them oversubscribe the machine,
on a shared server the count is for the whole machine, and other users need cores too.
Bootstrapping refits a model to repeated resamples of the data. Here the model is a loess smooth of 1,000 noisy points on two cycles of a sine curve, and we want a bootstrap prediction band for new observations on a grid of x values,
boot_fit() fits the smooth to one resample, predicts on the grid, and adds a resampled residual to each prediction to simulate a new observation. The resamples themselves are drawn up front,
boot_fit = function(b, grid, span = 0.3) {
fit = loess(y ~ x, data = b, span = span)
pred = predict(fit, newdata = tibble::tibble(x = grid))
tibble::tibble(
span = span,
x = grid,
y_new = pred + sample(residuals(fit), length(grid), replace = TRUE)
)
}
boots = map(
seq_len(1000),
\(i) slice_sample(d, prop = 1, replace = TRUE)
)mclapply()Each replicate is independent and 1,000 take a while,
parallel::mclapply() is lapply() across forked copies of the session,
user system elapsed
0.003 0.022 1.455
fork() duplicates the running process. The child is a copy of the parent at that instant, with the same objects, packages, and point of execution.
The copy is cheap. Memory is shared copy-on-write, so data that is only read costs nothing extra per worker.
Nothing is sent to a worker. Each child computes its share, sends the result back through a pipe, and exits.
Windows has no fork(), so mclapply() runs sequentially there. parLapply() and mirai start fresh R sessions instead and send them what they need.
Only the calling thread is copied, so forking from a session with other threads (a GUI, a multithreaded BLAS) can leave the child broken. RStudio warns about this.
Each forked worker starts from a copy of the parent’s RNG state. With the default generator, mclapply() reseeds each worker from the clock, so results change from run to run even after set.seed().
miraimirai is a framework for asynchronous and parallel evaluation of R code,
code is sent to persistent background R processes (daemons) and the result is collected when needed,
works the same on every operating system, and daemons can run on remote machines or an HPC cluster,
errors in a task are returned as values rather than stopping everything,
it is the engine behind parallel maps in purrr and tidymodels, and asynchronous tasks in Shiny.
daemons()Daemons are set once per session. They sit idle until given work, so there is no reason to start and stop them.
daemons(0) stops and removes all existing daemons.
Calling daemons(n) creates n new daemons.
daemons(sync = TRUE) runs every task in the current session, which is useful for debugging.
mirai()mirai() sends an expression to a daemon and returns immediately. The session is free while the task runs.
A mirai is unresolved until the daemon returns a value. m[] waits (blocks) for the result, and m$data holds it once resolved.
The expression runs in a fresh R process, not in your session, so everything it uses must be sent along or loaded there.
Named arguments after the expression are assigned in the daemon. Use .args = list(...) instead for objects that should be local to that one evaluation.
This is why the previous call passed boot_fit, b, and grid. A forked worker would have inherited them, but a daemon starts empty, so the function and its data must be shipped along with the expression.
Functions from packages must be namespaced, sent along like any other object, or the package attached on the daemons with everywhere(),
Each task runs in a fresh environment, and afterwards the daemon restores its global environment, packages, and options. With one daemon both tasks below run in the same process,
mirai_map()mirai_map() is lapply() where each element becomes its own mirai. Arguments that are the same for every task go in .args,
mclapply() blocks until every result is back, so wrapping it in system.time() measured the whole job. mirai_map() returns as soon as the tasks are submitted, so the timer has to run from submission through collection with [].
Starting daemons also takes a moment, since each one is a new R process. everywhere(NULL, .min = workers) evaluates a no-op on every daemon, and collecting it waits until all of them have connected, which keeps startup out of the timing.
# A tibble: 9 × 4
method workers seconds speedup
<chr> <dbl> <dbl> <dbl>
1 lapply 1 2.83 1
2 mclapply 2 1.46 1.94
3 mclapply 4 0.841 3.36
4 mclapply 6 0.625 4.52
5 mclapply 8 0.485 5.83
6 mirai_map 2 1.65 1.72
7 mirai_map 4 0.945 2.99
8 mirai_map 6 0.803 3.52
9 mirai_map 8 0.636 4.45
The speedup is sublinear in the number of workers for both, and mclapply() edges out mirai_map() at every count. This is close to an ideal case for forking. The workers inherit the resamples, the grid, and boot_fit() for free, where mirai has to send each resample to a daemon.
Eight tasks on four workers, where each task does nothing but sleep for a set number of seconds.
How long does this take if the tasks are dealt out in order (round robin) or if instead each task goes to the first free worker?
The same code runs with daemons on remote machines. The host listens at a URL and the daemons dial in, launched over SSH or submitted through a cluster scheduler.
mirai and the tidyversein_parallel()purrr’s in_parallel() wraps the function given to any map() variant. When daemons are set the map runs through mirai, otherwise it runs sequentially.
in_parallel() creates a self-contained function (a crate) that is serialized and sent to the daemons.
mirai_map() can be called directly instead, and over a data frame it maps across rows like pmap(). in_parallel() works with the whole map() family, so it fits inside mutate() and keeps purrr’s type-stable variants.
Use of in_parallel() has similar limits to direct use of mirai(),
Package functions must be namespaced, dplyr::filter() rather than filter(), or the package attached inside the function.
Objects and helper functions from your session must be passed to in_parallel() by name, as in in_parallel(\(x) f(x), f = f). Helpers passed this way must themselves be self-contained.
map()’s ... is not available for a parallel map, so map(boots, in_parallel(boot_fit), grid = grid) does not work. Fix extra arguments inside the lambda instead, as in \(b) boot_fit(b, grid), with grid passed to in_parallel() by name.
Unnest the fits and summarize by x to get the bootstrap prediction band, shown in red. The blue band is the prediction interval from the loess() fit to the original data,
For small calculations, compare a vectorized call, a sequential map, and a parallel map,
# A tibble: 3 × 2
expression median
<bch:expr> <bch:tm>
1 vectorized 25.26µs
2 sequential 2.05ms
3 parallel 1.03s
The workflow is the same, measure first and then decide whether workers are worth it. The Python equivalents are mostly in the standard library,
| Task | R | Python |
|---|---|---|
| Profile | profvis |
cProfile and pstats |
| Time a call | bench::mark() |
timeit |
| Pools of workers | mclapply(), mirai_map() |
concurrent.futures |
| Persistent workers, session functions | mirai daemons, in_parallel() |
joblib |
The rest of this section repeats the bootstrap, profiles a replicate, and then compares sequential, thread, and process execution of the same tasks.
boot_fit() in PythonThe smoother is now lowess() from statsmodels. Compared to the R version, boot_fit() takes a seed rather than a resample and draws the resample itself. A seed is a small thing to send to a worker, where a 1,000 row data frame is not, and the next slides use it to make each task reproducible.
The function lives in its own module, data/boot_fit.py, because a pool of processes imports the task function in each worker instead of copying the session the way a fork does,
import numpy as np
from statsmodels.nonparametric.smoothers_lowess import lowess
def boot_fit(seed, d, grid, span = 0.3):
rng = np.random.default_rng(seed)
b = d.sample(frac = 1, replace = True, random_state = rng)
fitted = lowess(b["y"], b["x"], frac = span, it = 0, return_sorted = False)
pred = lowess(b["y"], b["x"], frac = span, it = 0, xvals = grid)
return pred + rng.choice(b["y"].to_numpy() - fitted, len(grid))The same points and prediction grid as in R, and one replicate from the imported function,
cProfile is Python’s profiler and pstats summarizes what it recorded. Profiling 100 replicates and sorting the calls by cumulative time shows where the time goes,
515018 function calls (513618 primitive calls) in 0.413 seconds
Ordered by: cumulative time
List reduced from 172 to 4 due to restriction <4>
ncalls tottime percall cumtime percall filename:lineno(function)
100 0.002 0.000 0.413 0.004 boot_fit.py:4(boot_fit)
200 0.300 0.001 0.395 0.002 smoothers_lowess.py:15(lowess)
73036 0.024 0.000 0.078 0.000 fromnumeric.py:2342(sum)
73436 0.026 0.000 0.051 0.000 fromnumeric.py:66(_wrapreduction)
Nearly all of the time is inside the two lowess() calls. That is library code we cannot rewrite, so the practical option here is more workers.
Each worker process has its own copy of the global generator, either copied from the parent or freshly seeded, so np.random.seed() in the session does not make the results reproducible. This is the same problem as with forked R workers.
The fix mirrors L’Ecuyer streams. SeedSequence.spawn() derives independent streams from one seed, and boot_fit() builds its generator from the stream it is given,
A stream belongs to its task, so worker count and scheduling do not change the draws,
Every strategy below is compared against a sequential run, the Python counterpart of the lapply() timing. partial() fixes the arguments shared by every task, so fit(seed) is a complete task with a single argument, which is what map() and the worker pools expect.
timeit.timeit() with number = 1 times one run and discards its result, so the fits are kept from a separate call,
R’s forks and daemons are both processes. Python also offers threads, which share one interpreter, and whether they help depends on the global interpreter lock (GIL),
With the GIL enabled, only one thread runs Python code at a time. Threads overlap waiting, but do not speed up computation written in Python.
Compiled code can release the GIL while it runs, but only if it was written to. Measure rather than assume.
Processes have separate interpreters and GILs. Starting them and transferring inputs and results costs time.
concurrent.futures provides a thread pool and a process pool with the same interface. The with block starts the workers and shuts them down at the end, and pool.map() spreads the calls across them and returns the results in input order,
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def run(executor):
with executor(max_workers = 4) as pool:
return list(pool.map(fit, seeds))
runs = [("sequential", sequential_seconds)]
for executor in [ThreadPoolExecutor, ProcessPoolExecutor]:
seconds = timeit.timeit(lambda: run(executor), number = 1)
assert np.array_equal(run(executor), sequential)
runs.append((executor.__name__, seconds))The timings include pool startup and shutdown. timeit discards the return value, so each executor runs a second time to check every fitted value against the sequential run. Only the execution changes, not the tasks or their results.
Speedup is the sequential time divided by each method’s time,
Threads take as long as the sequential run. lowess() is Python code, so only one thread holds the GIL at a time.
Four processes finish in well under half the time, and that includes starting four interpreters that each import statsmodels. The next slides measure that startup cost.
joblib and repeated callsjoblib is the package scikit-learn uses for parallel work, and it lifts two limits of the process pool. Its default backend can send functions defined in the session, like in_parallel()’s crate, and it keeps the workers alive between calls, like daemons.
delayed(fit)(seed) records a call without running it and Parallel runs the batch. Timing two calls in a row shows the effect of reusing the workers,
The first call starts four workers that each import the task’s modules. The repeated call reuses them, so it is faster again. Both calls run the same tasks and reproduce the sequential results.
For a one-off script, include startup in the comparison. For repeated work in a session, also measure a call with workers already running.
Profile before optimizing. profvis attributes time to lines of your code, and the slow line is rarely the one you expect. A better algorithm usually beats more cores.
Check that alternatives do the same work before comparing speed. bench::mark() checks results, and bench::press() varies input size and group count.
mclapply() forks the session for parallel lapply() on Unix. Its default fixed assignment can leave cores idle; mc.preschedule = FALSE schedules tasks as slots free up.
Time asynchronous work from submission through collection. mirai returns errors as values, so successful results can be kept while failed tasks are repaired and retried.
purrr::in_parallel() and mirai_map() put parallel work inside pipelines. Assign reproducible random streams to tasks so worker count does not change the results.
In Python, measure threads and processes on the real workload, accounting for pool startup and worker reuse. Threads only help when the hot code releases the GIL.
In Jupyter and IPython, %timeit chooses the number of loops and repeats itself,
With timeit.repeat(), take the minimum as an estimate of execution time with the least interference from other work on the machine.
A timeout returns an error value. With a dispatcher, it also cancels the task.
.timeout is in milliseconds. stop_mirai() cancels a task explicitly.
purrr suggests roughly 100 µs to 1 ms of work per task as a starting point for considering parallelization. Measure on your own workload.
Some libraries already use multiple threads, including data.table, polars, duckdb, and optimized BLAS libraries.
Running multithreaded code in several worker processes can create more runnable threads than available cores. Limit internal threads or reduce the worker count, then measure again.
future and furrr are an older framework with the same idea, a plan is set once and future_map() runs on it. mirai is now one of its backends.
foreach with doParallel or doMC is a loop based interface that is still common in older code and packages.
parallel::parLapply() and makeCluster() create socket workers that work on Windows but need explicit clusterExport() of every object.
mizumizu is a new package from the author of mirai for parallel R on a single machine,
workers are background R processes, like daemons, but tasks and results move through shared memory rather than sockets,
a task round trip takes about a microsecond, against roughly 100 for mirai, so work can be split much more finely,
a parallel map places the function and data in shared memory once, and the workers divide the elements among themselves,
.seed gives each element of a map its own random number stream, so results do not depend on the number of workers,
shared memory only reaches the same machine, so mirai is still the tool for remote machines and clusters.
mizu_pool() and mizu_map()mizu_pool() starts the workers, fresh R processes like daemons. mizu_map() returns a handle immediately and mizu_collect() waits for the results, a list as with lapply(). Here ten tasks each draw a million normals and return their standard deviation,
<mizu_map: 10 elements, inline blob, submitted>
Adding .template = numeric(1) returns a double vector directly, as vapply() or map_dbl() would.
To compare the three, fix the total work at ten million draws and cut it into more and smaller pieces. Each method gets four workers and the same function, and each piece returns a single number.
# A tibble: 5 × 5
pieces lapply mclapply mirai_map mizu_map
<dbl> <dbl> <dbl> <dbl> <dbl>
1 10 0.170 0.0920 0.0640 0.0510
2 100 0.168 0.0750 0.0580 0.0480
3 1000 0.272 0.0890 0.122 0.0450
4 10000 0.200 0.0940 1.08 0.0550
5 100000 0.475 0.221 10.6 0.141
mclapply() deals the pieces out in four batches, one per forked worker, so more pieces cost it almost nothing.
mirai_map() sends every piece as its own task, at roughly 100 µs each. That is 10 seconds for 100,000 pieces.
mizu_map() workers claim pieces in batches from shared memory, so its time follows the work even at 100,000 pieces.
By the last row the pieces are so small that 100,000 calls to f() cost more than the draws, which slows every method.
pymizu is the Python side of mizu. A pool given mizu_py_launcher() has Python processes as its workers, here from the course environment where pymizu is installed.
mizu_call() names a Python function and its arguments, unnamed ones positional and named ones as keywords. mtcars$mpg arrives as a NumPy array and the result returns as an R vector.
Values convert to their natural counterpart. Vectors and matrices arrive as NumPy arrays, length 1 vectors as scalars, character vectors as lists of str, and named lists as dicts.
Large values are written to shared memory once and both sides read them in place, so nothing is serialized or copied again. Summing 80 MB of doubles in a Python worker takes about as long as sum() in the session,
A .source string runs a block of Python with the named arguments bound as variables, and its last expression is the result. A data frame arrives as a pymizu.Frame, which polars, pyarrow, and pandas can read, and a frame returned comes back as a data frame,
With a mizu_call() as the function, mizu_map() runs Python over an R vector. Each element is bound to x, and .template collects the results into a double vector. These are the ten pieces of a million draws from before, now drawn by NumPy,
Sta 523 - Fall 2026