Sub topic 15
Beyond DataFrames: a first look at dask.delayed
This chapter assumes you know how Dask DataFrames build lazy task graphs and how compute() runs them. It also assumes you have met the schedulers (threads, processes, synchronous). Here you apply the same ideas to ordinary Python functions that do not fit the DataFrame model.
Why a second tool
A Dask DataFrame fits work that looks like pandas: filters, column math and groupby aggregations. Some jobs do not look like that:
- Reading a few hundred files that each need a different parser.
- Calling an API or a model for each of many items.
- A pipeline of custom steps where the output of one function feeds the next.
- A loop whose iterations are independent but that you wrote as a plain
forloop.
dask.delayed wraps any Python function so that calling it does not run it. The call records a node in a task graph and returns a placeholder. Nothing runs until you call compute(). This is the same lazy model you already know, applied to arbitrary code.
The basic pattern
Decorate a function with @delayed, or wrap it with delayed(func). Then call it as usual.
import time
from dask import delayed
@delayed
def load(n):
time.sleep(1) # stands in for slow I/O
return list(range(n))
@delayed
def total(values):
return sum(values)
a = load(3)
b = load(4)
c = total(a)
print(type(c)) # a Delayed object, not a number
print(c.compute()) # 3Calling load(3) returns a Delayed object. Passing a into total does not force it. Dask records that total depends on a. When you call c.compute(), Dask runs only what c needs. The call load(4) that produced b is never executed, because nothing depends on it.
You can look at the graph before running it. Install the optional graphviz package and call c.visualize() to draw it, or inspect the raw dictionary.
print(dict(c.__dask_graph__()))Parallelising a loop
The most common use is turning a slow loop into parallel work. Build a list of delayed results, then compute them together.
import time
from dask import compute, delayed
@delayed
def slow_square(x):
time.sleep(1)
return x * x
@delayed
def add(a, b):
return a + b
parts = [slow_square(i) for i in range(8)]
combined = delayed(sum)(parts)
start = time.time()
print(combined.compute()) # 140
print(round(time.time() - start)) # about 1 second with enough threadsEight one-second tasks finish in roughly one second, not eight, because the default threaded scheduler runs them side by side. time.sleep releases the GIL, so threads work well here.
Notice delayed(sum)(parts). A list of Delayed objects passed to a delayed function is unpacked for you, so sum receives the real values. This also works for lists, tuples, sets and dictionaries nested in the arguments.
To get several results from one pass over the graph, use dask.compute.
from dask import compute
x = slow_square(2)
y = slow_square(3)
print(compute(x, y)) # (4, 9)Calling x.compute() and then y.compute() runs two separate passes. If x and y share upstream tasks, compute(x, y) runs those shared tasks once.
Choosing the scheduler
The same scheduler rules apply as for DataFrames. The choice matters more here because your code is arbitrary Python.
| Work in your function | Better scheduler | Reason |
|---|---|---|
| Waiting on disk, network or `sleep` | `threads` | The GIL is released while waiting, and threads share memory. |
| Pure-Python CPU work | `processes` | Each process has its own GIL, so work runs truly in parallel. |
| NumPy, pandas or other code that releases the GIL | `threads` | Native code runs in parallel without copying data. |
| Debugging | `synchronous` | One thread, normal tracebacks, and `pdb` works. |
Pass the choice to compute.
print(combined.compute(scheduler="processes"))
print(combined.compute(scheduler="synchronous"))The processes scheduler pickles arguments and results to move them between processes. Functions defined interactively, or objects that cannot be pickled, can fail there. Dask serializes functions with cloudpickle, which handles most cases. Large arguments are slow to ship.
Delayed objects and normal Python control flow
A Delayed object is a placeholder, so you cannot use its value in the code that builds the graph. These fail or behave wrongly:
n = delayed(len)([1, 2, 3])
# if n > 2: # raises: truth value of a Delayed is not defined
# for i in range(n): # raises: a Delayed cannot be used as an intBranching on a result requires one of two approaches.
- Compute the value first, then decide. This breaks laziness at that point, but it is often the simplest choice.
- Move the condition inside a delayed function.
from dask import delayed
@delayed
def pick(n):
return "big" if n > 2 else "small"
print(pick(n).compute()) # bigThe second approach keeps the whole pipeline lazy. Loops over a known list of inputs are fine, because the loop runs while you build the graph and each iteration adds tasks. A loop whose length depends on a computed value is the case that needs approach 1.
Delayed and DataFrames together
You can mix the two. dd.from_delayed builds a Dask DataFrame from a list of delayed pandas DataFrames. This suits cases where each partition comes from custom loading code. Call dd.from_delayed with meta set, so Dask does not have to run a task to learn the columns.
import pandas as pd
import dask.dataframe as dd
from dask import delayed
@delayed
def make_part(i):
return pd.DataFrame({"zone": ["a", "b"], "fare": [10.0 * i, 20.0 * i]})
meta = pd.DataFrame({"zone": pd.Series(dtype="object"),
"fare": pd.Series(dtype="float64")})
ddf = dd.from_delayed([make_part(i) for i in range(1, 4)], meta=meta)
print(ddf.npartitions) # 3
print(ddf.groupby("zone")["fare"].sum().compute())The reverse also exists. ddf.to_delayed() returns one Delayed per partition, which you can pass to your own functions.
Common mistakes
- Computing inside a loop. Writing
results.append(f(x).compute())runs one task at a time and removes all parallelism. Collect delayed objects first, then compute once. - Tiny tasks. Each task adds scheduler overhead of roughly a millisecond or more. If a function runs in microseconds, group many items into one task, for example by processing a chunk of a list per call.
- Giant graphs. A million delayed calls creates a million graph nodes, which is slow to build and to schedule. Batch the work.
- Mutating inputs. Tasks may run in any order and on different threads. Do not rely on shared mutable state or side effects such as appending to a global list. Return values instead.
- Passing big data as arguments repeatedly. Each use embeds the argument in the graph. Wrap a large object once with
delayed(obj)and pass that single reference. - Forgetting
compute. Printing aDelayedshows its type and key, not the answer.
import numpy as np
from dask import delayed
big = delayed(np.arange(1_000_000)) # wrapped once
@delayed
def head(arr, k):
return arr[:k].sum()
print(delayed(sum)([head(big, k) for k in (10, 100, 1000)]).compute())When to use which
Reach for a Dask DataFrame when the operation has a pandas equivalent, because Dask then optimizes the graph and manages partitions for you. Reach for delayed when you control the structure: the parts differ, the function is custom, or you are parallelising existing code with few changes. Many real pipelines use both, with delayed for loading and DataFrames for the analysis.
Exercise
A colleague writes results = [process(f).compute() for f in files] where process is decorated with @delayed, and finds it runs no faster than a plain loop. Why, and how do you fix it?
Show answer
Each .compute() call runs one task and waits for it before the next iteration starts, so only one task is ever in the graph at a time. Build the list lazily with tasks = [process(f) for f in files] and then run them together with dask.compute(*tasks) (or delayed(list)(tasks).compute()). Dask can then run the independent tasks in parallel.
Exercise
You have a delayed value n that holds a row count. Why does if n > 1000: raise an error, and name two ways to branch on it?
Show answer
n is a Delayed placeholder with no value yet, so Python cannot evaluate the comparison as a truth value while the graph is being built. You can call n.compute() and branch on the real number, which ends laziness at that point. Or you can move the condition into a delayed function that takes n as an argument, which keeps the pipeline lazy.