Sub topic 8
Choosing a scheduler
This chapter assumes you can build a Dask DataFrame, know that operations are lazy, and can call compute() to run them. You should also know the difference between a thread and a process in Python, and have a rough idea of what the Global Interpreter Lock (GIL) is.
What a scheduler does
When you call compute(), Dask has a task graph: a set of small tasks, each of which depends on the results of other tasks. A scheduler is the component that decides which task runs next, where it runs, and how results move between tasks. The graph stays the same. Only the execution strategy changes.
The three local schedulers are in the dask package itself:
| Scheduler name | Workers | Shares memory | Typical use |
|---|---|---|---|
| `threads` | Threads in one process | Yes | Code that releases the GIL, such as most pandas and NumPy work |
| `processes` | Separate Python processes | No | Pure-Python code that holds the GIL |
| `synchronous` | The calling thread only | Yes | Debugging and profiling |
The distributed scheduler, covered in the next chapter, is a fourth option. It runs on one machine or on a cluster and also gives you a dashboard.
Setting up an example
The examples below use the small DataFrame from earlier chapters. On a tiny dataset the timing differences are meaningless, but the code is the same for large data.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()Picking a scheduler per call
The scheduler= argument to compute() selects a scheduler for that one call.
print(mean_fare.compute(scheduler="threads"))
print(mean_fare.compute(scheduler="processes"))
print(mean_fare.compute(scheduler="synchronous")) # single thread, easy to debugAll three calls return the same pandas Series. Which one is fastest depends on the work inside the tasks.
On a script run as a file, put process-based code under an if __name__ == "__main__": guard. On Windows and macOS, Python starts new processes by importing your main module again. Without the guard, each worker would re-run your top-level code.
The default scheduler
You do not have to name a scheduler. Dask picks a default based on the collection type:
- Dask DataFrames use the threaded scheduler. (Older documentation described a processes default for Bag, and a threaded default for Array and Delayed. Check your version's docs if you rely on this.)
- If a distributed
Clientexists, it becomes the default for everything, and the local schedulers are ignored unless you ask for them by name.
Since Dask DataFrame is made of pandas objects, threads are a reasonable default. Many pandas and NumPy operations release the GIL while they run in compiled code, so several threads can work at once.
Threads, and the GIL
A thread worker shares memory with the main process. This makes it cheap:
- No data is copied between tasks.
- Startup cost is nearly zero.
- Large partitions never need to be serialized.
The cost is the GIL. Python allows only one thread to execute Python bytecode at a time. Compiled code can release the lock, but code written in pure Python cannot. If your tasks are mostly pure-Python loops, string handling with Python objects, or apply with a Python function, threads will run them one after another, and you get little or no speedup.
Object-dtype columns are a common trap. A column of Python strings stored as object often falls back to Python-level work. Using the string[pyarrow] dtype generally improves this, since the work happens in compiled Arrow code.
Processes, and the cost of copying
The process scheduler starts separate Python interpreters, each with its own GIL. Pure-Python code can run in parallel across them. Processes have their own costs:
- Startup is slower, because each worker is a new interpreter.
- Inputs and outputs of each task must be serialized (pickled) and sent between processes.
- Functions you pass in must be picklable. Lambdas and locally defined functions can cause problems.
- Memory is not shared, so the same data may exist in more than one process.
Processes pay off when tasks are heavy, mostly pure Python, and move little data. They are a poor choice when tasks are small or when large intermediate results travel between workers.
You can control the number of workers:
import dask
with dask.config.set(scheduler="threads", num_workers=4):
print(mean_fare.compute())dask.config.set as a context manager changes the setting only inside the with block. You can also pass num_workers= directly to compute():
print(mean_fare.compute(scheduler="processes", num_workers=2))The synchronous scheduler
The synchronous scheduler runs every task one after another in the calling thread. It has no parallelism, which is the point. In this mode:
- Exceptions raise in your own thread with a normal traceback.
pdb, IDE breakpoints, andprintoutput behave as you expect.- Profilers such as
cProfilesee the real function calls.
Use it whenever a computation fails or behaves oddly, ideally on a small slice of the data first. If the error disappears under synchronous, suspect a thread-safety problem or a pickling problem. If it stays, the bug is in your logic.
# Reproduce a failure on one small piece of data, with a debugger available
sample = ddf.partitions[0]
result = sample["fare"].sum().compute(scheduler="synchronous")
print(result)ddf.partitions[0] selects the first partition, so the debug run touches only a small part of the data.
Setting a scheduler globally
You can set a default for a whole session or script:
import dask
dask.config.set(scheduler="synchronous") # for the rest of the session
print(mean_fare.compute()) # now runs synchronously
dask.config.set(scheduler="threads") # switch backThe context-manager form is safer for temporary changes, because it restores the previous value when the block ends. A global setting that you forget about is a common cause of "why is this slow" questions.
When settings conflict, the more specific one wins. The order of precedence, highest first, is:
- The
scheduler=argument tocompute(). - A
dask.config.setsetting, whether global or in awithblock. - A distributed
Clientthat has been created. - The default for the collection type.
Decision guide
Use these questions in order:
- Are you debugging, or is the traceback confusing? Use
synchronous. - Do you need the dashboard, more than one machine, or better memory management? Use the distributed
Client. - Is the work mostly pandas, NumPy, or Arrow operations? Use
threads, which is already the default. - Is the work mostly pure-Python code on moderate amounts of data? Try
processes, and measure.
Measure rather than guess. Run the same computation under each choice on a realistic subset and compare wall-clock time:
import time
for name in ["synchronous", "threads", "processes"]:
start = time.perf_counter()
mean_fare.compute(scheduler=name)
print(name, round(time.perf_counter() - start, 3), "seconds")On the four-row example, synchronous will usually win, because there is nothing to parallelize and the other schedulers add overhead. That is a real effect: parallel schedulers have a fixed cost per task, so they only help when each task does enough work to cover it.
Common mistakes
- Expecting threads to speed up
applywith a Python function. The GIL serializes that work. Vectorize with pandas operations, or move to processes. - Using processes with huge partitions. Every partition is pickled to cross the process boundary, which can cost more than the computation.
- Creating a
Clientand forgetting it. After that,compute()uses the distributed scheduler, and ascheduler="threads"setting elsewhere may not apply the way you think. Close the client withclient.close()when you are done. - Missing the
__main__guard in scripts that use processes. The result is repeated startup or an error about starting new processes. - Benchmarking tiny data. Overhead dominates, and the result does not predict how large data behaves.
- Leaving
synchronousset globally after a debugging session, then wondering why nothing runs in parallel.
Summary of trade-offs
| Concern | threads | processes | synchronous |
|---|---|---|---|
| Startup cost | Very low | Higher | None |
| Data transfer | None, shared memory | Pickling required | None |
| Pure-Python speedup | Little or none | Yes | None |
| Pandas and NumPy speedup | Yes | Yes, with overhead | None |
| Debugging | Harder | Hardest | Easiest |
Exercise
A Dask DataFrame computation uses ddf.map_partitions with a function that loops over rows in pure Python. On a 4-core machine, scheduler="threads" uses about one core. Why, and what two changes could you try?
Show answer
The pure-Python loop holds the GIL, so only one thread can run it at a time, and the other cores stay idle. You could try scheduler="processes", so each worker has its own GIL, but check that the function is picklable and that the partitions are not so large that pickling dominates. Or you could rewrite the loop with vectorized pandas or NumPy operations, which release the GIL and run in compiled code.
Exercise
A computation raises a confusing error from inside a worker. What is the first scheduler change you should make, and what should you also do to the data?
Show answer
Rerun with scheduler="synchronous" so the exception is raised in your own thread with a normal traceback and breakpoints work. Also shrink the input, for example with ddf.partitions[0], so the debug run is quick.
Exercise
You created a distributed Client earlier in the session. You call mean_fare.compute() with no arguments. Which scheduler runs it, and how can you run that one call on threads instead?
Show answer
The distributed scheduler runs it, because an existing Client becomes the default. Pass scheduler="threads" to that call, since the scheduler= argument has the highest precedence.