Henrik Bengtsson
Parallel & distributed processing can be used to:
speed up processing (wall time)
decrease memory footprint (per machine)
avoid data transfers
Comment: I'll focuses on the first two in this talk.
Friedman & Wise (1976, 1977), Hibbard (1976), Baker & Hewitt (1977)
v <- expr
v <- expr
f <- future(expr) v <- value(f)
> library(future)> plan(multiprocess)
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )>
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )>
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )> 1:3[1] 1 2 3>
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )> 1:3[1] 1 2 3> value(fa)
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )> 1:3[1] 1 2 3> value(fa)[1] 1275
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )> 1:3[1] 1 2 3> value(fa)[1] 1275> value(fb)[1] 3775
> library(future)> plan(multiprocess)> fa <- future( slow_sum( 1:50 ) )> fb <- future( slow_sum(51:100) )> 1:3[1] 1 2 3> value(fa)[1] 1275> value(fb)[1] 3775> value(fa) + value(fb)[1] 5050
v <- expr
v %<-% expr
> library(future)> plan(multiprocess)> a %<-% slow_sum( 1:50 )> b %<-% slow_sum(51:100)> 1:3[1] 1 2 3> a + b[1] 5050
plan(sequential)plan(multiprocess)plan(cluster, workers = c("n1", "n2", "n3"))plan(cluster, workers = c("remote1.org", "remote2.org"))...
plan(sequential)plan(multiprocess)plan(cluster, workers = c("n1", "n2", "n3"))plan(cluster, workers = c("remote1.org", "remote2.org"))...
> a %<-% slow_sum( 1:50 )> b %<-% slow_sum(51:100)> a + b[1] 5050
╔════════════════════════════════════════════════════════╗ ║ < Future API > ║ ║ ║ ║ future(), value(), %<-%, ... ║ ╠════════════════════════════════════════════════════════╣ ║ future ║ ╠════════════════════════════════╦═══════════╦═══════════╣ ║ parallel ║ globals ║ (listenv) ║ ╠══════════╦══════════╦══════════╬═══════════╬═══════════╝ ║ snow ║ Rmpi ║ nws ║ codetools ║ ╚══════════╩══════════╩══════════╩═══════════╝
x <- list(a = 1:50, b = 51:100)y <- lapply(x, FUN = slow_sum)
x <- list(a = 1:50, b = 51:100)y <- lapply(x, FUN = slow_sum)
y <- parallel::mclapply(x, FUN = slow_sum)
x <- list(a = 1:50, b = 51:100)y <- lapply(x, FUN = slow_sum)
y <- parallel::mclapply(x, FUN = slow_sum)
library(parallel)cluster <- makeCluster(4)y <- parLapply(cluster, x, fun = slow_sum)stopCluster(cluster)
The Future API encapsulates heterogeneity
Philosophy:
Provides atomic building blocks for richer parallel constructs, e.g. 'foreach' and 'future.apply'
Easy to implement new backends, e.g. 'future.batchtools' and 'future.callr'
x <- rnorm(n = 100)y <- future({ slow_sum(x) })
x <- rnorm(n = 100)y <- future({ slow_sum(x) })
Globals identified and exported:
slow_sum()
- a function (also searched recursively)x <- rnorm(n = 100)y <- future({ slow_sum(x) })
Globals identified and exported:
slow_sum()
- a function (also searched recursively)x
- a numeric vector of length 100x <- rnorm(n = 100)y <- future({ slow_sum(x) })
Globals identified and exported:
slow_sum()
- a function (also searched recursively)x
- a numeric vector of length 100╔═══════════════════════════════════════════════════╗ ║ < Future API > ║ ╠═══════════════════════════════════════════════════╣ ║ future <-> future.batchtools ║ ╠═════════════════════════╦═════════════════════════╣ ║ parallel ║ batchtools ║ ╚═════════════════════════╬═════════════════════════╣ ║ SGE, Slurm, TORQUE, ... ║ ╚═════════════════════════╝
raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% DNAseq::align(raw[i])}aligned <- as.list(aligned)
raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% DNAseq::align(raw[i])}aligned <- as.list(aligned)
plan(multiprocess)
plan(cluster, workers = c("n1", "n2", "n3"))
plan(batchtools_sge)
Comment: The use of `listenv` is non-critical and only needed for implicit futures when assigning them by index (instead of by name).
lapply()
, vapply()
, replicate()
, ...╔═══════════════════════════════════════════════════════════╗ ║ future_lapply(), future_vapply(), future_replicate(), ... ║ ╠═══════════════════════════════════════════════════════════╣ ║ < Future API > ║ ╠═══════════════════════════════════════════════════════════╣ ║ "wherever" ║ ╚═══════════════════════════════════════════════════════════╝
aligned <- lapply(raw, DNAseq::align)
lapply()
, vapply()
, replicate()
, ...╔═══════════════════════════════════════════════════════════╗ ║ future_lapply(), future_vapply(), future_replicate(), ... ║ ╠═══════════════════════════════════════════════════════════╣ ║ < Future API > ║ ╠═══════════════════════════════════════════════════════════╣ ║ "wherever" ║ ╚═══════════════════════════════════════════════════════════╝
aligned <- future_lapply(raw, DNAseq::align)
lapply()
, vapply()
, replicate()
, ...╔═══════════════════════════════════════════════════════════╗ ║ future_lapply(), future_vapply(), future_replicate(), ... ║ ╠═══════════════════════════════════════════════════════════╣ ║ < Future API > ║ ╠═══════════════════════════════════════════════════════════╣ ║ "wherever" ║ ╚═══════════════════════════════════════════════════════════╝
aligned <- future_lapply(raw, DNAseq::align)
plan(multiprocess)
plan(cluster, workers = c("n1", "n2", "n3"))
plan(batchtools_sge)
╔═══════════════════════════════════════════════════════╗ ║ foreach API ║ ╠════════════╦══════╦════════╦═══════╦══════════════════╣ ║ doParallel ║ doMC ║ doSNOW ║ doMPI ║ doFuture ║ ╠════════════╩══╦═══╩════════╬═══════╬══════════════════╣ ║ parallel ║ snow ║ Rmpi ║ < Future API > ║ ╚═══════════════╩════════════╩═══════╬══════════════════╣ ║ "wherever" ║ ╚══════════════════╝
doFuture::registerDoFuture()plan(batchtools_sge)aligned <- foreach(x = raw) %dopar% { DNAseq::align(x)}
┌───────────────────────────────────────────────────────┐ │ │ │ caret, gam, glmnet, plyr, ... (1,200 pkgs) │ │ │ ╠═══════════════════════════════════════════════════════╣ ║ foreach API ║ ╠══════╦════════════╦════════╦═══════╦══════════════════╣ ║ doMC ║ doParallel ║ doSNOW ║ doMPI ║ doFuture ║ ╠══════╩════════╦═══╩════════╬═══════╬══════════════════╣ ║ parallel ║ snow ║ Rmpi ║ < Future API > ║ ╚═══════════════╩════════════╩═══════╬══════════════════╣ ║ "wherever" ║ ╚══════════════════╝
doFuture::registerDoFuture()plan(future.batchtools::batchtools_sge)library(caret)model <- train(y ~ ., data = training)
## 2018-05-12> db <- utils::available.packages()> direct <- tools::dependsOnPkgs("foreach", recursive=FALSE, installed=db)> str(direct) chr [1:443] "adabag" "admixturegraph" "ADMMsigma" "Arothron" "ashr" ...> all <- tools::dependsOnPkgs("foreach", recursive=TRUE, installed=db)> str(all) chr [1:1200] "adabag" "admixturegraph" "ADMMsigma" "Arothron" "ashr" ...
tasks <- drake_plan( raw_data = readxl::read_xlsx(file_in("raw-data.xlsx")), data = raw_data %>% mutate(Species = forcats::fct_inorder(Species)) %>% select(-X__1), hist = ggplot(data, aes(x = Petal.Width, fill = Species)) + geom_histogram(), fit = lm(Sepal.Width ~ Petal.Width + Species, data), rmarkdown::render(knitr_in("report.Rmd"), output_file = file_out("report.pdf")))future::plan("multiprocess")make(tasks, parallelism = "future")
Unified API
Portable code
Worry-free
Developer decides what to parallelize - user decides how to
For beginners as well as advanced users
Nested parallelism on nested heterogeneous backends
Protects against recursive parallelism
Easy to add new backends
Easy to build new frontends
example()
:s
from foreach, NMF, TSP, glmnet, plyr, caret, etc.
(example link)raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% { chrs <- listenv() for (j in 1:24) { chrs[[j]] %<-% DNAseq::align(raw[i], chr = j) } merge_chromosomes(chrs) }}
raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% { chrs <- listenv() for (j in 1:24) { chrs[[j]] %<-% DNAseq::align(raw[i], chr = j) } merge_chromosomes(chrs) }}
plan(batchtools_sge)
raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% { chrs <- listenv() for (j in 1:24) { chrs[[j]] %<-% DNAseq::align(raw[i], chr = j) } merge_chromosomes(chrs) }}
plan(batchtools_sge)
plan(list(batchtools_sge, sequential))
raw <- dir(pattern = "[.]fq$")aligned <- listenv()for (i in seq_along(raw)) { aligned[[i]] %<-% { chrs <- listenv() for (j in 1:24) { chrs[[j]] %<-% DNAseq::align(raw[i], chr = j) } merge_chromosomes(chrs) }}
plan(batchtools_sge)
plan(list(batchtools_sge, sequential))
plan(list(batchtools_sge, multiprocess))
By default all futures are resolved using eager evaluation, but the developer has the option to use lazy evaluation.
Explicit API:
f <- future(..., lazy = TRUE)v <- value(f)
Implicit API:
v %<-% { ... } %lazy% TRUE
Identification of globals from static-code inspection has limitations (but defaults cover a large number of use cases):
False negatives, e.g. my_fcn
is not found in do.call("my_fcn", x)
. Avoid by using do.call(my_fcn, x)
.
False positives - non-existing variables, e.g. NSE and variables in formulas. Ignore and leave it to run-time.
x <- "this FP will be exported"data <- data.frame(x = rnorm(1000), y = rnorm(1000))fit %<-% lm(x ~ y, data = data)
Comment: ... so, the above works.
Automatic (default):
x <- rnorm(n = 100)y <- future({ slow_sum(x) }, globals = TRUE)
By names:
y <- future({ slow_sum(x) }, globals = c("slow_sum", "x"))
As name-value pairs:
y <- future({ slow_sum(x) }, globals = list(slow_sum = slow_sum, x = rnorm(n = 100)))
Disable:
y <- future({ slow_sum(x) }, globals = FALSE)
Automatic (default):
x <- rnorm(n = 100)y %<-% { slow_sum(x) } %globals% TRUE
By names:
y %<-% { slow_sum(x) } %globals% c("slow_sum", "x")
As name-value pairs:
y %<-% { slow_sum(x) } %globals% list(slow_sum = slow_sum, x = rnorm(n = 100))
Disable:
y %<-% { slow_sum(x) } %globals% FALSE
x <- lapply(1:100, FUN = function(i) rnorm(1024 ^ 2))y <- list()for (i in seq_along(x)) { y[[i]] <- future( mean(x[[i]]) )}
gives error: "The total size of the 2 globals that need to be exported for the future expression ('mean(x[[i]])') is 800.00 MiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). There are two globals: 'x' (800.00 MiB of class 'list') and 'i' (48 bytes of class 'numeric')."
x <- lapply(1:100, FUN = function(i) rnorm(1024 ^ 2))y <- list()for (i in seq_along(x)) { y[[i]] <- future( mean(x[[i]]) )}
gives error: "The total size of the 2 globals that need to be exported for the future expression ('mean(x[[i]])') is 800.00 MiB. This exceeds the maximum allowed size of 500.00 MiB (option 'future.globals.maxSize'). There are two globals: 'x' (800.00 MiB of class 'list') and 'i' (48 bytes of class 'numeric')."
for (i in seq_along(x)) { x_i <- x[[i]] ## Fix: subset before creating future y[[i]] <- future( mean(x_i) )}
Comment: Interesting research project to automate via code inspection.
Implicit futures are always resolved:
a %<-% sum(1:10)b %<-% { 2 * a }print(b)## [1] 110
Implicit futures are always resolved:
a %<-% sum(1:10)b %<-% { 2 * a }print(b)## [1] 110
Explicit futures require care by developer:
fa <- future( sum(1:10) )a <- value(fa)fb <- future( 2 * a )
Implicit futures are always resolved:
a %<-% sum(1:10)b %<-% { 2 * a }print(b)## [1] 110
Explicit futures require care by developer:
fa <- future( sum(1:10) )a <- value(fa)fb <- future( 2 * a )
For the lazy developer - not recommended (may be expensive):
options(future.globals.resolve = TRUE)fa <- future( sum(1:10) )fb <- future( 2 * value(fa) )
Future class and corresponding methods:
abstract S3 class with common parts implemented,
e.g.
globals and protection
new backends extend this class and implement core methods,
e.g. value()
and resolved()
built-in classes implement backends on top the parallel package
future | parallel | foreach | batchtools | BiocParallel | |
---|---|---|---|---|---|
Synchronous | ✓ | ✓ | ✓ | ✓ | ✓ |
Asynchronous | ✓ | ✓ | ✓ | ✓ | ✓ |
Uniform API | ✓ | ✓ | ✓ | ✓ | |
Extendable API | ✓ | ✓ | ✓ | ✓ | |
Globals | ✓ | (✓) | |||
Packages | ✓ | ||||
Map-reduce ("lapply") | ✓ | ✓ | foreach() |
✓ | ✓ |
Load balancing | ✓ | ✓ | ✓ | ✓ | ✓ |
For loops | ✓ | ||||
While loops | ✓ | ||||
Nested config | ✓ | ||||
Recursive protection | ✓ | mc | mc | mc | mc |
RNG stream | ✓+ | ✓ | doRNG | (soon) | SNOW |
Early stopping | ✓ | ✓ | |||
Traceback | ✓ | ✓ |
availableCores()
is a "nicer" version of parallel::detectCores()
that returns the number of cores allotted to the process by acknowledging known settings, e.g.
getOption("mc.cores")
NSLOTS
, PBS_NUM_PPN
, SLURM_CPUS_PER_TASK
, ..._R_CHECK_LIMIT_CORES_
availableWorkers()
returns a vector of hostnames based on:
PE_HOSTFILE
, PBS_NODEFILE
, ...rep("localhost", availableCores())
Provide safe defaults to for instance
plan(multiprocess)plan(cluster)
makeClusterPSOCK()
:
Improves upon parallel::makePSOCKcluster()
Simplifies cluster setup, especially remote ones
Avoids common issues when workers connect back to master:
Makes option -l <user>
optional (such that ~/.ssh/config
is respected)
With 'future.batchtools' one can also specify computational resources, e.g. cores per node and memory needs.
plan(batchtools_sge, resources = list(mem = "128gb"))y %<-% { large_memory_method(x) }
Specific to scheduler: resources
is passed to the job-script template
where the parameters are interpreted and passed to the scheduler.
With 'future.batchtools' one can also specify computational resources, e.g. cores per node and memory needs.
plan(batchtools_sge, resources = list(mem = "128gb"))y %<-% { large_memory_method(x) }
Specific to scheduler: resources
is passed to the job-script template
where the parameters are interpreted and passed to the scheduler.
Each future needs one node with 24 cores and 128 GiB of RAM:
resources = list(l = "nodes=1:ppn=24", mem = "128gb")
> library(future)> plan(cluster, workers = "remote.org")
> library(future)> plan(cluster, workers = "remote.org")
## Plot remotely> g %<-% R.devices::capturePlot({ filled.contour(volcano, color.palette = terrain.colors) title("volcano data: filled contour map") })
> library(future)> plan(cluster, workers = "remote.org")
## Plot remotely> g %<-% R.devices::capturePlot({ filled.contour(volcano, color.palette = terrain.colors) title("volcano data: filled contour map") })
## Display locally> g
> library(future)> plan(cluster, workers = "remote.org")
## Plot remotely> g %<-% R.devices::capturePlot({ filled.contour(volcano, color.palette = terrain.colors) title("volcano data: filled contour map") })
## Display locally> g
recordPlot()
+ replayPlot()
> plan(cluster, workers = "remote.org")> dat <- data.frame(+ x = rnorm(50e3),+ y = rnorm(50e3)+ )## Profile remotely> p %<-% profvis::profvis({+ plot(x ~ y, data = dat)+ m <- lm(x ~ y, data = dat)+ abline(m, col = "red")+ })
> plan(cluster, workers = "remote.org")> dat <- data.frame(+ x = rnorm(50e3),+ y = rnorm(50e3)+ )## Profile remotely> p %<-% profvis::profvis({+ plot(x ~ y, data = dat)+ m <- lm(x ~ y, data = dat)+ abline(m, col = "red")+ })
## Browse locally> p
> plan(cluster, workers = "remote.org")> dat <- data.frame(+ x = rnorm(50e3),+ y = rnorm(50e3)+ )## Profile remotely> p %<-% profvis::profvis({+ plot(x ~ y, data = dat)+ m <- lm(x ~ y, data = dat)+ abline(m, col = "red")+ })
## Browse locally> p
"... framework for building web servers in R. ... from serving static
content to full-blown dynamic web-apps"
plan(multisession)mtcars %>% split(.$cyl) %>% map(~ future(lm(mpg ~ wt, data = .x))) %>% values %>% map(summary) %>% map_dbl("r.squared")## 4 6 8 ## 0.5086326 0.4645102 0.4229655
Comment: This approach not do load balancing. I have a few ideas how support for this may be implemented in future framework, which would be beneficial here and elsewhere.
library(googleComputeEngineR)vms <- lapply(paste0("node", 1:10), FUN = gce_vm, template = "r-base")cl <- as.cluster(lapply(vms, FUN = gce_ssh_setup), docker_image = "henrikbengtsson/r-base-future")plan(cluster, workers = cl)
data <- future_lapply(1:100, montecarlo_pi, B = 10e3)pi_hat <- Reduce(calculate_pi, data)print(pi_hat)## 3.1415
For any type of futures, the develop may wish to control:
future(..., memory = 8e9)
remote = FALSE
dependencies = c("R (>= 3.5.0)", "rio"))
mounts = "/share/lab/files"
vars = c("gene_db", "mtcars")
container = "docker://rocker/r-base"
tokens = c("a", "b")
Risk for bloating the Future API: Which need to be included? Don't want to reinvent the HPC scheduler and Spark.
Parallel & distributed processing can be used to:
speed up processing (wall time)
decrease memory footprint (per machine)
avoid data transfers
Comment: I'll focuses on the first two in this talk.
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
Esc | Back to slideshow |