Which workflow manager?
The previous page recorded what a job ran on. A pipeline is many steps, each reading what earlier steps wrote. Running it again means running each step on the same inputs, in the same environment, or knowing which of its results are still good, and that is what a workflow manager keeps track of. The page on workflow managers in Parallelism ran π through one, and is about running one on a cluster. This section is about using one to run a pipeline again: what it reruns, in which environment, and what it records.
The pipeline you may already have
The π of Parallelism ran in Snakemake, in one environment that had both Snakemake and NumPy, which is fine for two steps that need the same packages. A real pipeline has steps that need different tools, e.g. an aligner, a variant caller, and R for the plots, each with dependencies of its own, which may not even fit in one environment together. Put them all in one anyway, and every step depends on every package in it. Updating R for the plots changes the environment the aligner runs in, and nothing in the pipeline says so.
Each step is a function of its inputs and of the environment it runs in. The workflow manager knows the inputs, since it hands them from one step to the next, and what it knows about the environment depends on which one it is.
The workflow managers
Those I’d point you to:
- make, e.g. GNU make, on every system already. It knows only files and the times they were changed, which is enough for a simple pipeline on one node.
- Snakemake, make’s rules with inputs and outputs, written in Python, and with a conda environment or container for each rule if you want one.
- Nextflow, with a language of its own, where each step is a process and data flows between them through channels. It is the basis of nf-core, a large collection of community-maintained pipelines, mostly in genomics: if your field’s pipeline is one of them, you run it rather than write one.
- Parsl, a Python library, where the steps are Python functions, or commands, decorated as apps, and the dependencies are the futures they return, as in
concurrent.futures, for a workflow that is already a Python program, or that decides what to run next as it goes.
Two questions sort them, and between them account for most of their differences:
| The steps share one environment | Each step names its own | |
|---|---|---|
| Pull: you ask for a result, and it works back to the steps that make it | make | Snakemake, with conda:, container: or envmodules: in each rule |
| Push: each step runs once its inputs are ready, and the program can decide what runs next | Parsl, one environment per executor, set by its provider’s worker_init |
Nextflow, with conda, container or module in each process |
A pull engine starts from the file you ask for, and works back through the rules to the files that file needs, and to the steps that make them, all before it runs anything. A push engine starts from the inputs, and runs each step as soon as everything it needs has arrived, as a pool runs a task as soon as a worker is free.
What follows from them
A dry run. A pull engine has worked out every step before it runs the first, so it can list them without running them: make -n prints the commands it would run, and snakemake -n the jobs. A push engine finds its steps as their inputs arrive. Nextflow’s -preview, with -with-dag, draws its processes and the channels between them, but not the tasks each will run, and Parsl has no dry run, since its graph is the Python program, as it runs.
A graph that depends on results. In the example below, how many batches of points each dimension needs is known only once its first batch has run. In a push engine, that is ordinary code: in Nextflow, an operator that turns each plan into that many tasks, and in Parsl, a function that submits them. A pull engine has to stop and plan again. Snakemake has checkpoints, rules after which it works out the rest of the graph anew, and its dry run lists the steps up to each checkpoint and leaves the rest undetermined. In make, a step can write a makefile that make then reads in and restarts with.
That does not make the run any less reproducible. The number of batches depends on the first batch, whose seed is fixed, so it is the same on every run, and the whole run is a function of its inputs, in the sense of the introduction. It only means that no engine can list all of its steps before the pilots have run.
An environment per step. With one environment for every step, each step depends on every package in it. When each step names its own, it depends only on that one, and you can pin and update each without touching the others. Snakemake and Nextflow create each step’s environment from a file next to it, the first time it is needed, and count it among what decides whether a step has to run again. Parsl runs each app in the environment of the workers it is sent to, which you make yourself and activate with worker_init, one for each executor, so two steps get different environments only by going to different executors. make runs every command in the environment it was started in. Either way, an environment file next to a step is a recipe like any other, and is pinned the same way: a lockfile for a conda environment, and a digest for a container.
Which steps are already done. make reruns a step when one of its inputs is newer than its output. Snakemake also keeps a record of each output, in .snakemake/, and by default reruns a step whose command, parameters, set of inputs or environment has changed since. Nextflow computes a hash of each task, from its inputs, its script and its environment, and with -resume reuses every task whose hash is in the cache of the last run. Parsl reuses the result of an app only if the app is marked cache=True, keyed on its name and the values of its arguments, and keeps those results from one run to the next only if you have it checkpoint them. A script that a step runs counts, in make and Snakemake, only if it is listed as one of the step’s inputs, and Nextflow includes the scripts in the pipeline’s bin directory in its hash. Parsl’s key does not change even when the app’s own code does.
When the files move. On a cluster, a pipeline’s directory is often copied, from scratch to project storage say, and a rerun then starts from the copy. make compares modification times, so copy with rsync -a or cp -p, which keep them. Snakemake reruns every step that has an environment of its own, and every step after it, since an environment’s identity includes the directory it was created in. Nextflow’s hashes include the full path of every file a task uses, the scripts in bin among them, so in a copied directory it reruns every task. Parsl’s cache is keyed on the values of the arguments, so it carries over with the runinfo directory that holds it.
Provenance. Snakemake writes a report of a run on request, with the graph of its rules, each rule’s code and environment file, and how long each job took. Nextflow keeps each task’s script, log and exit status in a directory of its own, lists them with nextflow log, and writes a report, a trace of every task and a timeline on request. Parsl, with its monitoring turned on, records every task in a database: when it was submitted and when it ran, on which executor, and how it ended.
Which to reach for first
If your field’s pipeline is in nf-core, use Nextflow, and run that pipeline rather than write your own. For a pipeline of your own, made of commands that read and write files, I’d recommend Snakemake, which can tell you what it will run before it runs it, and gives each rule an environment of its own. Reach for Parsl when the workflow is already a Python program, passing values rather than files, or decides what to run as it goes, and for make when the pipeline is a few steps on one node, in one environment.
The example: the volume of the unit ball
Every page of this section runs the same pipeline, so that the three compare. It is the π of Parallelism in more dimensions: draw points uniformly in the unit cube, [0, 1]d, and count the hits, the points inside the ball of radius 1 centred on a corner. The fraction of hits, times 2d, is the volume of the ball, Vd, and since the exact volume is known, Vd = πd/2 / Γ(d/2 + 1), where Γ is the gamma function, every run can be checked. π is its d = 2 case, and the volume rises to 5.26 at d = 5, and falls after that.
The fraction of hits falls fast with d, from 0.79 at d = 2 to 0.00033 at d = 12, so the more dimensions, the more points it takes to reach the same accuracy, and how many is best measured with a first batch. So for each d from 2 to 12, the pipeline runs a pilot batch of 226 points, plans from it how many batches give a relative error of 0.1%, runs that many, and adds them up:
for each d from 2 to 12
pilot(d) one batch, seeded with (d, 0) NumPy
plan(d) how many batches d needs, from its pilot known only at run time
count(d, k) batch k, from 1 to that number, seeded (d, k) NumPy
reduce(d) adds up the hits of d's batches standard library
table a row for every d, in volumes.tsv standard library
plot volumes.tsv, drawn in volumes.svg matplotlib
It is all in one Python file, which the three pages run:
#!/usr/bin/env python3
"""The volume of the unit ball in d dimensions, by Monte Carlo, the example
every page on workflow managers runs.
Draw points uniformly in the unit cube [0, 1]^d, and count the hits, the points
inside the ball of radius 1. The fraction of hits is V_d / 2^d.
python ball.py count D K print "hits samples" for batch K of D
python ball.py plan FILE print how many batches a pilot asks for
python ball.py reduce D FILE... add up D's batches, print its row
python ball.py table FILE... print the table, from the rows
python ball.py plot TABLE SVG plot the table
NumPy is imported only by count, and matplotlib only by plot, so the other steps
need nothing but the standard library.
"""
import math
import sys
BATCH = 2**26 # points in a batch
ROOT_SEED = 2026 # the same for every batch: (d, k) tells them apart
CHUNK = 2**16 # points drawn at a time, to keep memory small
TARGET = 1e-3 # the relative standard error to aim for
HEADER = "d\tbatches\tsamples\thits\tvolume\texact\terror"
def count_hits(d, k):
"""Count how many of BATCH random points in [0, 1]^d are in the ball."""
import numpy as np
rng = np.random.default_rng([d, k, ROOT_SEED])
hits = 0
for _ in range(BATCH // CHUNK):
x = rng.random((CHUNK, d))
hits += int(np.count_nonzero((x * x).sum(axis=1) <= 1.0))
return hits
def batches_needed(hits, samples=BATCH, target=TARGET):
"""How many batches give a relative error of `target`, from a pilot."""
p = max(hits, 1) / samples
return math.ceil((1 - p) / (p * target**2 * BATCH))
def exact(d):
return math.pi ** (d / 2) / math.gamma(d / 2 + 1)
def row(d, batches, samples, hits):
"""A row of the table: the estimate of V_d, the exact value, the error."""
volume = 2**d * hits / samples
error = volume / exact(d) - 1
fields = [d, batches, samples, hits, f"{volume:.6f}", f"{exact(d):.6f}"]
return "\t".join(map(str, fields + [f"{error:+.3%}"]))
def table(rows):
"""The table, sorted by d, whichever order the rows came in."""
rows = sorted(rows, key=lambda r: int(r.split("\t")[0]))
return "\n".join([HEADER, *rows])
def plot(table_file, svg_file):
import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
# Fix the two things that would otherwise differ from one run to the next.
plt.rcParams["svg.hashsalt"] = "ball"
with open(table_file) as f:
rows = [line.split("\t") for line in f.read().splitlines()[1:]]
d = [int(r[0]) for r in rows]
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(d, [float(r[5]) for r in rows], color="0.6", label="exact")
ax.plot(d, [float(r[4]) for r in rows], "o", label="Monte Carlo")
ax.set_xlabel("dimension d")
ax.set_ylabel("volume of the unit ball")
ax.legend()
fig.savefig(svg_file, metadata={"Date": None})
def first_fields(files):
"""The numbers on the first line of each file."""
for name in files:
with open(name) as f:
yield [int(x) for x in f.readline().split()]
def main():
command, *args = sys.argv[1:]
if command == "count":
d, k = map(int, args)
print(count_hits(d, k), BATCH)
elif command == "plan":
[(hits, samples)] = first_fields(args)
print(batches_needed(hits, samples))
elif command == "reduce":
d, *files = args
lines = list(first_fields(files))
samples = sum(s for _, s in lines)
print(row(int(d), len(lines), samples, sum(h for h, _ in lines)))
elif command == "table":
rows = []
for name in args:
with open(name) as f:
rows.append(f.readline().rstrip("\n"))
print(table(rows))
elif command == "plot":
plot(*args)
else:
sys.exit(f"unknown command {command!r}: see the top of ball.py")
if __name__ == "__main__":
main()count_hits is a batch: like the task of π, it draws its points in chunks, from a generator seeded with [d, k, ROOT_SEED], so every batch draws different points, and the same ones however it is run. The pilot is batch 0. batches_needed is the plan: from the pilot’s fraction of hits, p, it works out how many batches make the relative standard error of the estimate, √((1 − p) / pN) for N points, at most 0.1%. row is the reduce, and table sorts the rows by d, so the table is the same whatever order they arrive in. NumPy is imported only for count, and matplotlib only for plot, so the other steps need nothing but the standard library, and each of the two has an environment of its own:
channels:
- conda-forge
dependencies:
- python=3.13
- numpychannels:
- conda-forge
dependencies:
- python=3.13
- matplotlib-baseThe pilots say that d = 2 to 8 need one batch each, d = 9 needs 3, d = 10 needs 6, d = 11 needs 17 and d = 12 needs 46. That is 79 batches, plus the 11 pilots, and each engine takes about a minute for them on 8 cores, and ends with the same volumes.tsv:1
d batches samples hits volume exact error
2 1 67108864 52711027 3.141822 3.141593 +0.007%
3 1 67108864 35145071 4.189619 4.188790 +0.020%
4 1 67108864 20699876 4.935235 4.934802 +0.009%
5 1 67108864 11033343 5.261108 5.263789 -0.051%
6 1 67108864 5422119 5.170936 5.167713 +0.062%
7 1 67108864 2476368 4.723297 4.724766 -0.031%
8 1 67108864 1063928 4.058563 4.058712 -0.004%
9 3 201326592 1295917 3.295687 3.298509 -0.086%
10 6 402653184 1003562 2.552190 2.550164 +0.079%
11 17 1140850688 1050164 1.885204 1.884104 +0.058%
12 46 3087007744 1005588 1.334266 1.335263 -0.075%
The same, byte for byte, from all three engines, and from Snakemake on 1 core or on 8: every batch is seeded by its (d, k), and the reduce adds integers, as π does, so this pipeline follows the strong principle of the page on determinism, and the table meets the strictest equivalence, bit-identical. Matplotlib, however, writes the date into an SVG, and gives the elements inside it random ids, so two runs of the plot give two different files. plot fixes both, with svg.hashsalt and metadata={"Date": None}, and then two runs match as well, as long as they use the same version of matplotlib, which it also writes into the file.
The files are all in ball-workflow/, under examples/ in the guide’s repository, and each page runs its engine in a job of 8 cores. The next page starts with Snakemake.
Footnotes
The tab-separated columns are lined up here to be read. Measured on 8 cores of an x86 workstation, outside Slurm, by running the job scripts directly. The numbers depend on the build of NumPy, as π’s do.↩︎