Futureverse · Session 1
No slides, no spoilers: just you. In pairs, spend 4 minutes writing down everything you associate with parallelising R code. Don’t filter:
We’ll collect your answers on the board, group them, and the session builds from there.
Pair-share (≈10 min total). 4 min in pairs, then we gather. There are no wrong answers; “I’ve never parallelised anything” is the most common — and a fine starting point.
## Class brainstorm {.paper}
::: {.paper-card}
**No slides, no spoilers: just you.** In pairs, spend **4 minutes** writing down everything you associate with *parallelising R code*. Don't filter:
- Have you ever made R use more than one core? How, and how did it go?
- What stopped you — setup, exports, platform quirks, fear of breaking something?
- Have you waited for a long loop thinking *"why isn't this using all my CPU?"*
We'll collect your answers on the board, group them, and the session builds from there.
:::
<div class="paper-adv">
<button type="button" class="paper-adv-btn">Going further</button>
<div class="paper-adv-backdrop" hidden></div>
<div class="paper-adv-modal" hidden>
<div class="paper-adv-head"><strong>Going further</strong><button type="button" class="paper-adv-close" aria-label="Close">×</button></div>
<div class="adv-body">
<p><strong>Pair-share (≈10 min total).</strong> 4 min in pairs, then we gather. There are no wrong answers; "I've never parallelised anything" is the most common — and a fine starting point.</p>
</div>
</div>
</div>
Henrik’s useR! 2026 tutorial opens with polls. Let’s steal them:
mclapply(), parLapply(), foreach %dopar%, {mirai}, Futureverse… or none?Keep your answer: every wall you just named has a name in this course.
## Why are you here? {.inv}
Henrik's useR! 2026 tutorial opens with polls. Let's steal them:
::: {}
- **Which tools have you tried?** `mclapply()`, `parLapply()`, `foreach %dopar%`, `{mirai}`, Futureverse… or none?
- **Where does your code run today?** laptop, shared workstation, cloud, HPC cluster?
- **Why are you attending?** make it faster, use more memory, keep an app responsive?
Keep your answer: **every wall you just named has a name in this course.**
:::
plan(), apply/map idioms, then the one-pipe trick: futurize() + progressify(); errors, RNG, and when parallelising does not help.{mirai}, the memory wall of parallel processes, and shared-memory {mori} / {mizu}.{purrr} & {tidymodels}: parallelism built into your pipelines (in_parallel(), parallel_over).One thread runs through all three: your code keeps its shape — only where and how fast it runs changes.
## This course at a glance {.inv}
::: {}
- **[Session 1 · The Futureverse]{.green}** — futures and `plan()`, apply/map idioms, then the *one-pipe* trick: `futurize()` + `progressify()`; errors, RNG, and when parallelising does *not* help.
- **[Session 2 · mirai, mori & mizu]{.amber}** — the async engine `{mirai}`, the **memory wall** of parallel processes, and shared-memory `{mori}` / `{mizu}`.
- **[Session 3 · Parallel data science]{.indigo}** — `{purrr}` & `{tidymodels}`: parallelism built into your pipelines (`in_parallel()`, `parallel_over`).
:::
::: {.callout-desc .fragment}
One thread runs through all three: **your code keeps its shape** — only *where* and *how fast* it runs changes.
:::
Everything this course is about, in one line (Henrik, COMPUTE! 2026, Paris):
“From sequential to parallel in ~10 years… That’s it.” The code you already write gets parallel with one pipe and a live progress bar with another — and runs unchanged on your laptop, your lab’s workstation, or a Slurm cluster.
## The promise {.inv}
Everything this course is about, in one line (Henrik, *COMPUTE! 2026*, Paris):
::: {.codewindow .r name="one-line.R"}
```r
res <- lapply(patients, fit_model) |> futurize() |> progressify()
```
:::
::: {.callout-desc .fragment}
**"From sequential to parallel in ~10 years… That's it."** The code you already write gets parallel with one pipe and a live progress bar with another — and runs unchanged on your laptop, your lab's workstation, or a Slurm cluster.
:::
Say an analysis takes 2 minutes:
The pieces of a sum can be computed in any order — that’s all parallelisation needs: independent parts. Nothing about the answer changes, only how many processes compute it.
## The seed idea: split the work {.inv}
Say an analysis takes **2 minutes**:
::: {.codewindow .r name="sum-split.R"}
```r
x <- 1:1e7
h <- function(x) sum(x, na.rm = TRUE)
## 1 process 2 min
y <- h(x)
## 2 processes 1 min
y <- h(x[1:5e6]) + h(x[5e6 + 1:5e6])
## 4 processes 30 s
y <- h(x[1:2.5e6]) + h(x[2.5e6 + 1:2.5e6]) +
h(x[5e6 + 1:2.5e6]) + h(x[7.5e6 + 1:2.5e6])
```
:::
::: {.callout-desc .fragment}
The pieces of a sum can be computed **in any order** — that's all parallelisation needs: *independent* parts. Nothing about the answer changes, only how many processes compute it.
:::
Real tasks aren’t perfectly uniform (we’ll meet chunking for that). The principle stands: more independent workers, less wall-clock time.
## The speed-up, drawn {.inv}
<div class="tile-stage">
<div class="tile-panel">
<div class="tile-cue">1 worker · 2 min</div>
<div class="tile-grid" style="grid-template-columns: repeat(1, 1fr);">
<div class="tile-row">
<div class="tile" style="background:#8B94A0">sum(x)</div>
</div>
</div>
</div>
<div class="tile-arrow fragment" data-fragment-index="1"><span class="cap">split</span>→</div>
<div class="tile-panel fragment" data-fragment-index="1">
<div class="tile-cue">2 workers · 1 min</div>
<div class="tile-grid" style="grid-template-columns: repeat(2, 1fr);">
<div class="tile-row">
<div class="tile" style="background:#2E7D6B">sum(x[1:5e6])</div>
<div class="tile" style="background:#4A5899">sum(x[5e6+1:5e6])</div>
</div>
</div>
</div>
<div class="tile-arrow fragment" data-fragment-index="2"><span class="cap">split</span>→</div>
<div class="tile-panel fragment" data-fragment-index="2">
<div class="tile-cue">4 workers · 30 s</div>
<div class="tile-grid" style="grid-template-columns: repeat(4, 1fr);">
<div class="tile-row">
<div class="tile" style="background:#2E7D6B">1</div>
<div class="tile" style="background:#4A5899">2</div>
<div class="tile" style="background:#E8A33D">3</div>
<div class="tile" style="background:#8B94A0">4</div>
</div>
</div>
</div>
</div>
::: {.callout-desc .fragment}
Real tasks aren't perfectly uniform (we'll meet *chunking* for that). The principle stands: **more independent workers, less wall-clock time.**
:::
## Four good reasons {.inv}
::: {.spread .spread-md .spread-evenly}
1. **[Speed]{.green}** — finish in minutes instead of hours by using the cores you already have.
2. **[Memory footprint]{.amber}** — split a big computation across workers so each process holds less.
3. **[Avoid transfers]{.indigo}** — move the computation to the data, not gigabytes to the computation.
4. **[Async UI]{.indigo}** — keep an app (or your console) responsive while work is running.
:::
Parallelising is not free — each task must be shipped to a worker. The common no-gos:
{purrr}’s rule).{mori} / {mizu}.)Measure first. system.time() (or tictoc::tic/toc) before and after. Small tasks can be grouped — that’s chunking, later today.
## When NOT to parallelize {.inv}
Parallelising is not free — each task must be shipped to a worker. The common no-gos:
::: {}
- **[Tasks too small]{.green}** — if one iteration is microseconds, shipping overhead dominates. Rule of thumb: iterations worth at least ≈ 1 ms (we refine this in Session 3 with `{purrr}`'s rule).
- **[Large data]{.amber}** — if every worker needs a full copy of a huge object, copying beats computing. (This exact wall is Session 2's problem: `{mori}` / `{mizu}`.)
- **[Bottleneck isn't CPU]{.indigo}** — I/O, network or memory latency won't speed up with more cores.
- **[Already vectorized]{.indigo}** — BLAS and many C-level functions already use all your cores.
:::
::: {.callout-desc .fragment}
**Measure first.** `system.time()` (or `tictoc::tic/toc`) before and after. Small tasks can be *grouped* — that's **chunking**, later today.
:::
The Futureverse’s promise: the same code runs on every rung. What changes is only where work goes — one function call: plan() (in a few minutes).
## The ladder: laptop → HPC {.inv}
::: {.spread .spread-md .spread-evenly}
1. **[Your laptop]{.green}** — 4–16 cores, already under your fingers.
2. **[Shared workstation]{.amber}** — your lab's big machine; be nice to your colleagues.
3. **[Cloud]{.indigo}** — rent machines on demand.
4. **[HPC cluster]{.indigo}** — Slurm / SGE / TORQUE-PBS; thousands of cores.
:::
::: {.callout-desc .fragment}
The Futureverse's promise: **the same code runs on every rung.** What changes is only *where* work goes — one function call: `plan()` (in a few minutes).
:::
parallel::mclapply() is the tempting drop-in: “just” fork the process N ways.
fork(), so mclapply() simply does not work there.fork() copies the entire process — memory, connections, RNG — once per worker.parallel) has long warned that forked children inherit live state and can corrupt the parent.mclapply() looks like a drop-in. But “works on my Mac, not my colleague’s Windows” is exactly the platform friction that made parallel code rare.
## mclapply(): fork, and its limits {.inv}
::: {.split-2}
`parallel::mclapply()` is the tempting drop-in: "just" fork the process N ways.
- **Unix-only** — Windows has no `fork()`, so `mclapply()` simply does not work there.
- `fork()` copies the *entire* process — memory, connections, RNG — once per worker.
- Forking from inside GUIs or apps is fragile; Simon Urbanek (author of `parallel`) has long warned that forked children inherit live state and can corrupt the parent.
- One crashing child can take your whole R session with it.
:::
::: {.codewindow .r name="mclapply.R"}
```r
options(mc.cores = 8)
res <- parallel::mclapply(xs, f) # Unix only
```
:::
::: {.callout-desc .fragment}
`mclapply()` *looks* like a drop-in. But "works on my Mac, not my colleague's Windows" is exactly the **platform friction** that made parallel code rare.
:::
makeCluster() + parLapply() works everywhere — including Windows — at the price of choreography:
clusterEvalQ(cl, ...) to load packages on workers;clusterExport(cl, "x") to ship data and functions;stopCluster(cl) at the end.This is the setup tax — and it kills readability for real analyses.
## parLapply(): sockets, and chores {.inv}
::: {.split-2}
`makeCluster()` + `parLapply()` works everywhere — including Windows — at the price of *choreography*:
- `clusterEvalQ(cl, ...)` to load packages on workers;
- `clusterExport(cl, "x")` to ship data and functions;
- `stopCluster(cl)` at the end.
- Forget one export → "object not found" on workers that "works locally".
This is the **setup tax** — and it kills readability for real analyses.
:::
::: {.codewindow .r name="parLapply.R"}
```r
cl <- makeCluster(8)
clusterEvalQ(cl, library(future.apply))
clusterExport(cl, "fit_model")
res <- parLapply(cl, xs, fit_model)
stopCluster(cl)
```
:::
COMPUTE! 2026 pictures pre-Futureverse parallelism:
Every analysis that wanted both platforms paid this branching tax; code coverage only ever exercised one branch; every change to fit meant re-exporting and re-testing. The barrier was never the hardware — it was friction.
## The refactoring tax {.inv}
*COMPUTE! 2026* pictures pre-Futureverse parallelism:
::: {.codewindow .r name="before.R"}
```r
res <- if (parallel) {
if (.Platform$OS.type == "windows") {
cl <- makeCluster(8)
on.exit(stopCluster(cl))
parLapply(cl, xs, fit)
} else {
options(mc.cores = 8L)
mclapply(xs, fit)
}
} else {
lapply(xs, fit)
}
```
:::
::: {.callout-desc .fragment}
Every analysis that wanted both platforms paid this **branching tax**; code coverage only ever exercised one branch; every change to `fit` meant re-exporting and re-testing. **The barrier was never the hardware — it was friction.**
:::
The Futureverse approach (“keep the code parallel and readable”) caught on:
Then someone went further: “we can simplify it even more.” The rest of this session: futures — and then the one-pipe trick.
## The community verdict {.inv}
The Futureverse approach ("keep the code parallel *and* readable") caught on:
::: {}
- **+40% reverse dependencies every year** — ~575 packages depend directly, ~1,300 recursively (boot, glmnet, lme4, mlr3, DESeq2…).
- **Top 0.6%** of the most-downloaded R packages.
- Niceties other parallelism does not give you: **auto-exported globals, auto-relayed messages/warnings/errors, proper parallel RNG**.
:::
::: {.callout-desc .fragment}
Then someone went further: *"we can simplify it even more."* The rest of this session: **futures** — and then the one-pipe trick.
:::
Futures are from the 1970s (Friedman & Wise 1976/1977; also Hibbard 1976; Baker & Hewitt 1977): a future is a placeholder for a value that is being computed — possibly elsewhere.
The mental shift.
An ordinary expression is its value:
A future expression describes a value that arrives later:
A Future is: an object representing a value that will be available later — queryable (resolved(f)), awaitable (value(f)), and one per expression.
Today, “futures” in R means the {future} package. You write what to compute once; plan() decides how/where it runs.
## The oldest idea in this talk {.inv}
**Futures are from the 1970s** (Friedman & Wise 1976/1977; also Hibbard 1976; Baker & Hewitt 1977): a *future* is a placeholder for a value that is being computed — possibly elsewhere.
::: {.split-2}
**The mental shift.**
An ordinary expression *is* its value:
::: {.codewindow .r name="value.R"}
```r
v <- sum(x) # v IS the number
```
:::
A future expression *describes* a value that arrives later:
::: {.codewindow .r name="future.R"}
```r
f <- future(sum(x)) # f is a handle
v <- value(f) # blocks until ready
```
:::
**A Future is:** an object representing a value *that will be available later* — queryable (`resolved(f)`), awaitable (`value(f)`), and one per *expression*.
:::
::: {.callout-desc .fragment}
Today, "futures" in R means the `{future}` package. You write *what* to compute once; `plan()` decides *how/where* it runs.
:::
v <- expr — evaluate now, block, get result.f <- future(expr); v <- value(f) — start now, block later.v %<-% expr — same, sugar-coated: “v will be expr”.%<-% is called the future-assignment operator. Two lines of code, and parts of a sum run on different cores — the splitting we drew earlier, with zero manual choreography.
## Value vs future: side by side {.inv}
::: {.spread .spread-md .spread-evenly}
1. **[Sequential]{.green}** — `v <- expr` — evaluate now, block, get result.
2. **[Future]{.amber}** — `f <- future(expr); v <- value(f)` — start now, block later.
3. **[Future-assignment]{.indigo}** — `v %<-% expr` — same, sugar-coated: "v **will be** expr".
:::
::: {.codewindow .r name="fut-assign.R"}
```r
library(future)
plan(multisession)
a %<-% h(x[1:5]) # starts immediately
b %<-% h(x[6:10]) # runs in parallel
y <- a + b # waits for both
```
:::
::: {.callout-desc .fragment}
`%<-%` is called the **future-assignment operator**. Two lines of code, and parts of a sum run on different cores — the splitting we drew earlier, with zero manual choreography.
:::
Questions the seminar’s futures answer:
resolved(f) is non-blocking; poll it any time.value(f) blocks until ready, then returns it (and re-raises errors).plan() swaps the how/where, code stays identical.In Session 2 you’ll meet {mirai}, which makes the same promise with a different engine — the concepts carry over, and that’s the point of building both futures and mirai into one course.
## A Future is… (Henrik's unpacking) {.inv}
Questions the seminar's futures answer:
::: {}
- **Started?** — yes, immediately upon creation (unlike some other languages' lazy futures).
- **Finished?** — `resolved(f)` is *non-blocking*; poll it any time.
- **Result?** — `value(f)` *blocks* until ready, then returns it (and re-raises errors).
- **Same everywhere?** — futures are *backend-agnostic*: `plan()` swaps the how/where, code stays identical.
:::
::: {.callout-desc .fragment}
In Session 2 you'll meet `{mirai}`, which makes the same promise with a different engine — the *concepts* carry over, and that's the point of building both futures and mirai into one course.
:::
Separate WHAT (the developer’s future_lapply / %<-% code) from HOW/WHERE (the user’s plan()).
plan(sequential) # single process, default
plan(multisession, workers = 4) # 4 local R processes
plan(multicore, workers = 4) # fork — Unix only
plan(future.callr::callr, workers = 4) # isolated, memory returned early
plan(cluster, workers = c("n1", "vm.cloud.org", "hpc.uni.edu"))
plan(batchtools_slurm, workers = 100) # HPC schedulerFrom the user’s menu to the laptop→HPC ladder from earlier: each rung is one plan(). The code above it never changes.
## The one function that changes everything {.inv}
Separate **WHAT** (the developer's `future_lapply` / `%<-%` code) from **HOW/WHERE** (the user's `plan()`).
::: {.codewindow .r name="plans.R"}
```r
plan(sequential) # single process, default
plan(multisession, workers = 4) # 4 local R processes
plan(multicore, workers = 4) # fork — Unix only
plan(future.callr::callr, workers = 4) # isolated, memory returned early
plan(cluster, workers = c("n1", "vm.cloud.org", "hpc.uni.edu"))
plan(batchtools_slurm, workers = 100) # HPC scheduler
```
:::
::: {.callout-desc .fragment}
From the user's menu to the laptop→HPC ladder from earlier: **each rung is one `plan()`**. The code above it never changes.
:::
The user-facing table (from Henrik’s COMPUTE! 2026):
| Backend | Where | Notes |
|---|---|---|
sequential |
one machine | default, debugging |
multisession |
one machine | parallel cores |
mirai_multisession |
one machine | powered by {mirai} (S2) |
mizu_multisession |
one machine | shared memory via {mizu} (S2) |
cluster |
many machines | SSH / explicit hosts |
batchtools_slurm |
HPC | Slurm / SGE / LSF / TORQUE schedulers |
New array since 2026: mirai_multisession (low latency) and mizu_multisession (shared memory) — both covered hands-on in Session 2.
## plan() as a menu {.inv}
The user-facing table (from Henrik's *COMPUTE! 2026*):
| Backend | Where | Notes |
|---|---|---|
| `sequential` | one machine | default, debugging |
| `multisession` | one machine | parallel cores |
| `mirai_multisession` | one machine | powered by `{mirai}` (S2) |
| `mizu_multisession` | one machine | shared memory via `{mizu}` (S2) |
| `cluster` | many machines | SSH / explicit hosts |
| `batchtools_slurm` | HPC | Slurm / SGE / LSF / TORQUE schedulers |
::: {.callout-desc .fragment}
New array since 2026: `mirai_multisession` (low latency) and `mizu_multisession` (shared memory) — both covered hands-on in Session 2.
:::
The same code, proving “write once”:
And then came the transpiler that removes even the future_ / future_map rename — the next two slides’ futurize().
## Sum of a vector, 4 ways {.inv}
The same code, proving "write once":
::: {.codewindow .r name="identical.R"}
```r
## sequential
res <- lapply(xs, slow_sqrt)
## parallel, same shape
res <- future_lapply(xs, slow_sqrt) # future.apply
## future-assignment
a %<-% h(x[1:5]); b %<-% h(x[6:10])
y <- a + b
## future-lapply is a drop-in
res <- furrr::future_map(xs, slow_sqrt) # furrr
```
:::
::: {.callout-desc .fragment}
And then came the **transpiler** that removes even the `future_` / `future_map` rename — the next two slides' `futurize()`.
:::
How do workers see fit_model and x? The Futureverse inspects your code’s AST (the abstract syntax tree) and finds free variables:
{future} walks lobstr::ast() — here { → slow_sum → x — captures exactly the referenced objects, and ships them. Manual globals = c("fit_model","x") is still possible when the magic misses (loops, indexing).
## Globals: exported for you {.inv}
How do workers see `fit_model` and `x`? The Futureverse **inspects your code's AST** (the abstract syntax tree) and finds free variables:
::: {.codewindow .r name="globals.R"}
```r
future_lapply(xs, fit_model)
# -> detects `fit_model` and `xs` as globals,
# serialises and exports them automatically
```
:::
::: {.callout-desc .fragment}
`{future}` walks `lobstr::ast()` — here `{` → `slow_sum` → `x` — captures exactly the referenced objects, and ships them. Manual `globals = c("fit_model","x")` is still possible when the magic misses (loops, indexing).
:::
Henrik asks you to see these four as one idea:
“Take-home: they’re all the same.” A loop that returns values — same shape, same result. That single insight is why one parallelisation can cover all four.
## They're all the same {.inv}
Henrik asks you to see these four as *one idea*:
::: {.codewindow .r name="all-same.R"}
```r
## base R
ys <- lapply(xs, slow_sum)
## purrr
ys <- map(xs, slow_sum)
## plyr
ys <- llply(xs, slow_sum)
## foreach (NOT a for loop!)
ys <- foreach(x = xs) %do% slow_sum(x)
```
:::
::: {.callout-desc .fragment}
"**Take-home: they're all the same.**" A loop that *returns* values — same shape, same result. That single insight is why one parallelisation can cover all four.
:::
Start sequential, end parallel — without changing the function:
parallel_map() is buildable in two loops: fire all future()s, then collect all value()s. (Prefer value(fs) over lapply(fs, value) — it stops early on failure and cancels outstanding tasks.)
## "Your turn": draw an owl {.inv}
Start sequential, end parallel — without changing the *function*:
::: {.codewindow .r name="owl.R"}
```r
xs <- 1:10
ys <- xs |> map(slow_sqrt) # sequential today
ys <- xs |> parallel_map(slow_sqrt) # parallel tomorrow
```
:::
::: {.callout-desc .fragment}
`parallel_map()` is buildable in two loops: fire all `future()`s, then collect all `value()`s. (Prefer `value(fs)` over `lapply(fs, value)` — it stops early on failure and cancels outstanding tasks.)
:::
The two loops that make up every parallel map:
This is the entire conceptual core of the Futureverse: futures + a map. Everything else in the ecosystem (future_lapply, future_map, %dofuture%, mirai_map, purrr::in_parallel()) is this function wearing different clothes.
## parallel_map(), by hand {.inv}
The two loops that make up every parallel map:
::: {.codewindow .r name="parallel-map.R"}
```r
parallel_map <- function(xs, f, ...) {
fs <- lapply(xs, function(x) future(f(x), ...)) # fire all
value(fs) # collect all
}
## benchmark vs sequential
t_seq <- system.time(ys <- lapply(xs, slow_sqrt))
t_par <- system.time(ys <- parallel_map(xs, slow_sqrt))
```
:::
::: {.callout-desc .fragment}
This is the entire conceptual core of the Futureverse: **futures + a map**. Everything else in the ecosystem (`future_lapply`, `future_map`, `%dofuture%`, `mirai_map`, `purrr::in_parallel()`) is this function wearing different clothes.
:::
The classic trap:
Like lapply/map, foreach returns values — assignment inside the body vanishes. Same rule, parallel or not.
## foreach() is NOT a for loop {.inv}
The classic trap:
::: {.split-2}
::: {.codewindow .r name="foreach-danger.R"}
```r
## WRONG: %dopar% with a side effect
res <- foreach(i = seq_len(n)) %dopar% {
res[i] <- f(xs[i]) # nobody sees this!
}
```
:::
::: {.codewindow .r name="foreach-good.R"}
```r
## RIGHT: collect the value
res <- foreach(i = seq_len(n),
.combine = c) %dopar% f(xs[i])
```
:::
:::
::: {.callout-desc .fragment}
Like `lapply`/`map`, `foreach` **returns values** — assignment *inside* the body vanishes. Same rule, parallel or not.
:::
Futureverse’s newest idea (since January 2026) — a transpiler that rewrites your pipe:
future.apply, furrr and doFuture “are now only used in the background” — you don’t call them anymore. Your existing code plus one pipe.
## The 2026 headline {.inv}
Futureverse's newest idea (since January 2026) — a *transpiler* that rewrites your pipe:
::: {.codewindow .r name="futurize.R"}
```r
ys <- lapply(xs, slow_sqrt) |> futurize()
ys <- map(xs, slow_sqrt) |> futurize()
ys <- foreach(x = xs) %do% slow_sum(x) |> futurize()
ys <- llply(xs, slow_sum) |> futurize()
ys <- bplapply(xs, slow_sum) |> futurize()
```
:::
::: {.callout-desc .fragment}
`future.apply`, `furrr` and `doFuture` "**are now only used in the background**" — you don't call them anymore. Your existing code plus *one pipe*.
:::
How can a pipe rewrite the call it receives? Lazy evaluation:
futurize() does the same swap: it receives lapply(xs, f), rewrites the root symbol to future_lapply, and executes the parallel version. futurize(eval = FALSE) shows you the generated call instead.
## Under the hood: a transpiler {.inv}
How can a pipe rewrite the call it receives? **Lazy evaluation**:
::: {.codewindow .r name="evil-eval.R"}
```r
evil_eval <- function(expr) {
expr <- substitute(expr) # receive the CODE, not the result
expr[[1]] <- as.name("-") # swap + for -
eval(expr, parent.frame())
}
evil_eval(1 + 2) # 1 - 2 = -1
```
:::
::: {.callout-desc .fragment}
`futurize()` does the same swap: it receives `lapply(xs, f)`, rewrites the root symbol to `future_lapply`, and executes the parallel version. `futurize(eval = FALSE)` shows you the generated call instead.
:::
futurize(eval = FALSE) is inspectable:
Same for map → future_map, boot → makeClusterFuture + boot(parallel = "snow"). Teaching aid, debugging aid — and your insurance that you stay in control.
## What the transpiler generates {.inv}
`futurize(eval = FALSE)` is inspectable:
::: {.codewindow .r name="transpiled.R"}
```r
lapply(xs, slow_sqrt) |> futurize(eval = FALSE)
# future.apply::future_lapply(
# xs, slow_sqrt,
# future.seed = FALSE,
# future.globals = TRUE,
# future.stdout = TRUE,
# future.conditions = "condition",
# future.scheduling = 1,
# future.label = "fz:base::lapply-%d"
# )
```
:::
::: {.callout-desc .fragment}
Same for `map` → `future_map`, `boot` → `makeClusterFuture` + `boot(parallel = "snow")`. Teaching aid, debugging aid — and your insurance that you stay in control.
:::
The same |> futurize() line, five backends:
plan(sequential) # debug
plan(multisession, workers = 4) # local cores
plan(future.mirai::mirai_multisession, workers = 4) # low latency (S2)
plan(future.callr::callr, workers = 4) # memory returns early
plan(cluster, workers = c("m1","m2","server.uni.edu"))
plan(batchtools_slurm, workers = 100) # HPCWrite once, run anywhere — the pitch slide of the Futureverse. Sessions 2–3 will put mirai_multisession, mizu_multisession, in_parallel() and parallel_over in that same slot.
## Futures can be resolved anywhere {.inv}
The same `|> futurize()` line, five backends:
::: {.codewindow .r name="anywhere.R"}
```r
plan(sequential) # debug
plan(multisession, workers = 4) # local cores
plan(future.mirai::mirai_multisession, workers = 4) # low latency (S2)
plan(future.callr::callr, workers = 4) # memory returns early
plan(cluster, workers = c("m1","m2","server.uni.edu"))
plan(batchtools_slurm, workers = 100) # HPC
```
:::
::: {.callout-desc .fragment}
Write once, run anywhere — the pitch slide of the Futureverse. Sessions 2–3 will put `mirai_multisession`, `mizu_multisession`, `in_parallel()` and `parallel_over` in that same slot.
:::
Since January 2026, progress bars join the same pipeline:
progressify() = progressr + sensible defaults. On the cluster it shows near-live progress — because futures relay condition messages as they go.
## The other new pipe {.inv}
Since January 2026, progress bars join the same pipeline:
::: {.codewindow .r name="progressify.R"}
```r
library(progressify)
## must be enabled once, per session
handlers(global = TRUE)
ys <- lapply(xs, slow_sqrt) |> progressify()
## ...and together with parallelisation
ys <- lapply(xs, slow_sqrt) |> progressify() |> futurize()
```
:::
::: {.callout-desc .fragment}
`progressify()` = `progressr` + sensible defaults. On the cluster it shows **near-live progress** — because futures relay condition messages as they go.
:::
utils::txtProgressBar (=>>), erased on completion.cli — ■■■ 80% | ETA: 1s, live-updating.cli + beepr — same bar, plus a sound when done.tutorial — keeps output for copy-pasting notes.tutorial + newline — keeps every update: [0s] 0% … [5s] 100%.Per-session: handlers(global = TRUE) once. Demo live (30s): 10 slow sqrts, cli handler, then tutorial+newline, then + beepr if you like audio.
## The handlers menu {.inv}
::: {}
- **default** — `utils::txtProgressBar` (=\>\>), erased on completion.
- **`cli`** — `■■■ 80% | ETA: 1s`, live-updating.
- **`cli` + `beepr`** — same bar, plus a sound when done.
- **`tutorial`** — keeps output for copy-pasting notes.
- **`tutorial` + `newline`** — keeps *every* update: `[0s] 0% … [5s] 100%`.
:::
::: {.callout-desc .fragment}
Per-session: `handlers(global = TRUE)` once. Demo live (30s): 10 slow sqrts, `cli` handler, then `tutorial+newline`, then `+ beepr` if you like audio.
:::
COMPUTE! 2026’s demo went from ETA 12m → 23s once parallelised:
Progress across workers: one bar for the whole job, updated as futures resolve. That’s messages-relaying (next section) doing real work in the UI.
## Same call, plus one pipe — on the cluster {.inv}
*COMPUTE! 2026*'s demo went from **ETA 12m → 23s** once parallelised:
::: {.codewindow .r name="cluster-progress.R"}
```r
handlers("cli", global = TRUE)
plan(cluster, workers = c("m1","m2","m3","server.uni.edu"))
ys <- lapply(xs, slow_sqrt) |> progressify() |> futurize()
```
:::
::: {.callout-desc .fragment}
Progress *across* workers: one bar for the whole job, updated as futures resolve. That's messages-relaying (next section) doing real work in the UI.
:::
Henrik’s g() throws all three at once:
Parallel map_dbl terminates identically on the first bad input; messages (x = 1, x = 2…) and warnings (NaNs produced) are relayed to your console in order. With mclapply/parLapply/doParallel, output is muffled or lost.
## Business as usual — in parallel {.inv}
Henrik's `g()` throws all three at once:
::: {.codewindow .r name="g.R"}
```r
g <- function(x) {
message("x = ", x)
if (x < 0) stop("x must be non-negative: ", x)
if (x > 10) warning("large x: ", x)
x
}
ys <- map_dbl(c(1, 2, -3, 4), g) # sequential: error on -3
ys <- map_dbl(c(1, 2, -3, 4), g) |> futurize() # SAME: error on -3
```
:::
::: {.callout-desc .fragment}
Parallel `map_dbl` **terminates identically** on the first bad input; messages (`x = 1`, `x = 2`…) and warnings (`NaNs produced`) are relayed to your console **in order**. With `mclapply`/`parLapply`/`doParallel`, output is muffled or lost.
:::
plan().Under the hood this is future.conditions marshalling — the topic of the course FAQ.
## Relayed, not swallowed {.inv}
::: {.spread .spread-md .spread-evenly}
1. **[Futureverse]{.green}** — messages/warnings/errors **relayed** as they happen, in order.
2. **[mclapply / parLapply / doParallel]{.amber}** — output **muffled or lost**; errors opaque.
3. **[That's the difference]{.indigo}** — parallel code that still *talks to you*; debugging doesn't stop at `plan()`.
:::
::: {.callout-desc .fragment}
Under the hood this is `future.conditions` marshalling — the topic of the [course FAQ](faq/futureverse-faq.html).
:::
future.seed = TRUE gives each task its own reproducible stream — the parallel analogue of set.seed(). Parallel simulation (bootstrap, CV, MCMC…) needs it to be trustworthy.
## Errors that matter, RNG that's reproducible {.inv}
::: {.codewindow .r name="rng.R"}
```r
## proper parallel RNG
ys <- lapply(xs, slow_sqrt) |> futurize(seed = TRUE)
# L'Ecuyer-CMRG: reproducible STREAMS per worker
## without it, you get a warning
# UNRELIABLE VALUE: Future(...) unexpectedly generated random numbers
# without specifying argument 'seed'
```
:::
::: {.callout-desc .fragment}
`future.seed = TRUE` gives each task its own reproducible stream — the parallel analogue of `set.seed()`. Parallel simulation (bootstrap, CV, MCMC…) needs it to be trustworthy.
:::
mirai_map, Session 3 in_parallel()).{mori}, {mizu}).And one more, from the tutorial: already-vectorized code — BLAS-backed C loops already use all cores.
## The three walls {.inv}
::: {}
- **Small tasks** — overhead dominates (ship + start + collect). Fix: **chunking** (Session 2 lab meets `mirai_map`, Session 3 `in_parallel()`).
- **Big shared data** — every worker copies it (Session 2: `{mori}`, `{mizu}`).
- **Non-CPU bottleneck** — I/O, network, memory bandwidth: more cores ≠ faster.
:::
::: {.callout-desc .fragment}
And one more, from the tutorial: **already-vectorized code** — BLAS-backed C loops already use all cores.
:::
Group elements so each worker does more per trip (diagram = 4 workers, 8 tasks):
future.scheduling / future.chunk.size tune this. Uniform tasks → larger chunks; variable tasks → smaller chunks keeps the pipe full.
## The fix when tasks are tiny: chunking {.inv}
Group elements so each worker does more per trip (diagram = 4 workers, 8 tasks):
<div class="tile-stage">
<div class="tile-panel">
<div class="tile-cue">chunk.size = 1 (8 trips)</div>
<div class="tile-grid" style="grid-template-columns: repeat(8, 1fr);">
<div class="tile-row">
<div class="tile" style="background:#2E7D6B">1</div><div class="tile" style="background:#4A5899">2</div>
<div class="tile" style="background:#E8A33D">3</div><div class="tile" style="background:#8B94A0">4</div>
<div class="tile" style="background:#2E7D6B">5</div><div class="tile" style="background:#4A5899">6</div>
<div class="tile" style="background:#E8A33D">7</div><div class="tile" style="background:#8B94A0">8</div>
</div>
</div>
</div>
<div class="tile-arrow fragment" data-fragment-index="1"><span class="cap">fewer trips</span>→</div>
<div class="tile-panel fragment" data-fragment-index="1">
<div class="tile-cue">chunk.size = 2 (4 trips)</div>
<div class="tile-grid" style="grid-template-columns: repeat(4, 1fr);">
<div class="tile-row">
<div class="tile" style="background:#2E7D6B">1,2</div><div class="tile" style="background:#4A5899">3,4</div>
<div class="tile" style="background:#E8A33D">5,6</div><div class="tile" style="background:#8B94A0">7,8</div>
</div>
</div>
</div>
</div>
::: {.callout-desc .fragment}
`future.scheduling` / `future.chunk.size` tune this. Uniform tasks → larger chunks; variable tasks → smaller chunks keeps the pipe full.
:::
Some R objects cannot be serialised to another process:
xgboost, torch, keras, Rcpp objects.reticulate Python sessions.future.globals.onReference = "error" turns the silent failure (weird behaviour in workers) into an immediate, named error. The recipe: build the connection inside the task.
## Objects that can't travel {.inv}
Some R objects cannot be serialised to another process:
::: {}
- **DBI connections** — a live database handle lives in *this* process.
- **External pointers** — `xgboost`, `torch`, `keras`, Rcpp objects.
- **`reticulate`** Python sessions.
:::
::: {.codewindow .r name="onref.R"}
```r
## catch it early
options(future.globals.onReference = "error")
## fix: create the resource ON the worker
future_lapply(files, function(path) {
con <- DBI::dbConnect(RSQLite::SQLite(), path) # per worker
on.exit(DBI::dbDisconnect(con))
DBI::dbGetQuery(con, "SELECT * FROM t")
})
```
:::
::: {.callout-desc .fragment}
`future.globals.onReference = "error"` turns the *silent* failure (weird behaviour in workers) into an immediate, named error. The recipe: build the connection **inside** the task.
:::
The whole point: your existing call, unchanged, plus one pipe:
~30 packages on CRAN — boot, caret, glmnet, lme4, mgcv, mlr3, DESeq2… — plus Bioconductor’s BiocParallel family. “Your existing call, plus one pipe.”
## Bootstraps, fits, cross-validation {.inv}
The whole point: *your existing call*, unchanged, plus one pipe:
::: {.codewindow .r name="domain.R"}
```r
## boot
b <- boot::boot(data, statistic = fit_glm, R = 1000) |>
progressify() |> futurize()
## glmnet / caret / mgcv / lme4…
cv <- glmnet::cv.glmnet(x, y) |> futurize()
tr <- caret::train(...) |> futurize()
b <- mgcv::bam(...) |> futurize()
mb <- lme4::bootMer(...) |> futurize()
```
:::
::: {.callout-desc .fragment}
~30 packages on CRAN — boot, caret, glmnet, lme4, mgcv, mlr3, DESeq2… — plus Bioconductor's BiocParallel family. **"Your existing call, plus one pipe."**
:::
COMPUTE! 2026’s demo: R = 100e3, then:
Identical because futures with seed = TRUE use reproducible per-worker RNG and relay results faithfully — parallel changes time, not answers.
## Bootstrap, 100,000 resamples {.inv}
*COMPUTE! 2026*'s demo: `R = 100e3`, then:
::: {.codewindow .r name="bootstrap.R"}
```r
b <- boot::boot(data, statistic = fit_glm, R = 100e3) |>
futurize()
## sequential: hours 32 workers: minutes
## results: IDENTICAL
```
:::
::: {.callout-desc .fragment}
Identical because futures with `seed = TRUE` use reproducible per-worker RNG and relay results faithfully — parallel changes *time*, not *answers*.
:::
Futures inside futures work, but multiply processes multiplicatively:
Use one level of parallelism in production; reserve nesting for when inner tasks are heavy. (Session 3: tune’s two strategies are exactly about where to put the parallelism.)
## Nested parallelization — with care {.inv}
Futures inside futures work, but multiply processes multiplicatively:
::: {.codewindow .r name="nested.R"}
```r
## sequential 4 workers nested 5×3
## 10s 2.8s (over-parallelized)
```
:::
::: {.callout-desc .fragment}
Use one level of parallelism in production; reserve nesting for when inner tasks are heavy. (Session 3: `tune`'s two strategies are exactly about *where* to put the parallelism.)
:::
From Henrik’s 2026 decks:
{mori}) — “same machine only” today, but aiming for fully automatic; existing code improves for free.ys <- lapply(xs, fit) |> resources(memory = 2*GiB, gpu = TRUE, time = 5*hours) |> futurize().|> resources(by = "08:00", budget = 25*USD).Resources lets the maintainer declare resources(fit_model) <- resources(memory = 1.5 * size_of(patient)) once — and every user inherits it. Sessions 2–3 are the rest of this roadmap: {mirai}, {mori}, {mizu}, and pipeline-native parallelism.
## Roadmap: the Futureverse is still moving {.inv}
From Henrik's 2026 decks:
::: {}
- **Shared memory by default (via `{mori}`)** — "same machine only" today, but aiming for fully automatic; existing code improves for free.
- **Declarative Resource API** `ys <- lapply(xs, fit) |> resources(memory = 2*GiB, gpu = TRUE, time = 5*hours) |> futurize()`.
- **Fail fast** — "Cannot meet resources(memory = 8 GiB): this R session has only 4 GiB"; auto-select workers ("6 of 32 cores = 48 GiB fits in 50 GiB").
- **Intent-based computing** — `|> resources(by = "08:00", budget = 25*USD)`.
:::
::: {.callout-desc .fragment}
Resources lets the *maintainer* declare `resources(fit_model) <- resources(memory = 1.5 * size_of(patient))` once — and every user inherits it. Sessions 2–3 are the rest of this roadmap: `{mirai}`, `{mori}`, `{mizu}`, and pipeline-native parallelism.
:::
Take-home cheat sheet (also in the lab and the FAQ):
plan(multisession) (or sequential to debug).|> futurize().|> progressify(); make it reproducible: futurize(seed = TRUE).future() / value() / %<-%.Next, the lab: you’ll build parallel_map(), watch futurize() transpile, and race 2/4/6/8 workers with progressify running. Then in Session 2, we ask “how does this actually move data?” — and meet mirai, mori and mizu.
## What you can do now {.inv}
Take-home cheat sheet (also in the lab and the FAQ):
::: {}
1. **Choose the backend**: `plan(multisession)` (or `sequential` to debug).
2. **Parallelise**: *just add a pipe* — `|> futurize()`.
3. **Watch it**: `|> progressify()`; **make it reproducible**: `futurize(seed = TRUE)`.
4. **Remember the building blocks**: `future()` / `value()` / `%<-%`.
:::
::: {.callout-desc .fragment}
Next, the lab: you'll build `parallel_map()`, watch `futurize()` transpile, and race 2/4/6/8 workers with `progressify` running. Then in Session 2, we ask *"how does this actually move data?"* — and meet mirai, mori and mizu.
:::
A. Stamm aymeric.stamm@cnrs.fr · Futureverse · Session 1