| 1 |
Dask Best Practices |
| 2 |
=================== |
| 3 |
|
| 4 |
.. meta:: |
| 5 |
:description: This is a short overview of Dask best practices. This document specifically focuses on best practices that are shared among all of the Dask APIs. Readers may first want to investigate one of the API-specific Best Practices documents first. |
| 6 |
|
| 7 |
It is easy to get started with Dask's APIs, but using them *well* requires some |
| 8 |
experience. This page contains suggestions for Dask best practices and |
| 9 |
includes solutions to common Dask problems. |
| 10 |
|
| 11 |
This document specifically focuses on best practices that are shared among all |
| 12 |
of the Dask APIs. Readers may first want to investigate one of the |
| 13 |
API-specific Best Practices documents first. |
| 14 |
|
| 15 |
- :doc:`Arrays <array-best-practices>` |
| 16 |
- :doc:`DataFrames <dataframe-best-practices>` |
| 17 |
- :doc:`Delayed <delayed-best-practices>` |
| 18 |
|
| 19 |
.. raw:: html |
| 20 |
|
| •21 |
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/Gvuf6gSGA9M" title="YouTube video player" frameborder="0" style="margin: 0 auto 20px auto; display: block;" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> |
| 22 |
|
| 23 |
|
| 24 |
Start Small |
| 25 |
----------- |
| 26 |
|
| 27 |
Parallelism brings extra complexity and overhead. |
| 28 |
Sometimes it's necessary for larger problems, but often it's not. |
| 29 |
Before adding a parallel computing system like Dask to your workload you may |
| 30 |
want to first try some alternatives: |
| 31 |
|
| 32 |
- **Use better algorithms or data structures**: NumPy, pandas, Scikit-learn |
| 33 |
may have faster functions for what you're trying to do. It may be worth |
| 34 |
consulting with an expert or reading through their docs again to find a |
| 35 |
better pre-built algorithm. |
| 36 |
|
| 37 |
- **Better file formats**: Efficient binary formats that support random |
| 38 |
access can often help you manage larger-than-memory datasets efficiently and |
| 39 |
simply. See the `Store Data Efficiently`_ section below. |
| 40 |
|
| 41 |
- **Compiled code**: Compiling your Python code with Numba or Cython might |
| 42 |
make parallelism unnecessary. Or you might use the multi-core parallelism |
| 43 |
available within those libraries. |
| 44 |
|
| 45 |
- **Sampling**: Even if you have a lot of data, there might not be much |
| 46 |
advantage from using all of it. By sampling intelligently you might be able |
| 47 |
to derive the same insight from a much more manageable subset. |
| 48 |
|
| 49 |
- **Profile**: If you're trying to speed up slow code it's important that |
| 50 |
you first understand why it is slow. Modest time investments in profiling |
| 51 |
your code can help you to identify what is slowing you down. This |
| 52 |
information can help you make better decisions about if parallelism is likely |
| 53 |
to help, or if other approaches are likely to be more effective. |
| 54 |
|
| 55 |
|
| 56 |
Use The Dashboard |
| 57 |
----------------- |
| 58 |
|
| 59 |
Dask's dashboard helps you to understand the state of your workers. |
| 60 |
This information can help to guide you to efficient solutions. |
| 61 |
In parallel and distributed computing there are new costs to be aware of and so |
| 62 |
your old intuition may no longer be true. Working with the dashboard can help |
| 63 |
you relearn about what is fast and slow and how to deal with it. |
| 64 |
|
| 65 |
See :doc:`Documentation on Dask's dashboard <dashboard>` for more |
| 66 |
information. |
| 67 |
|
| 68 |
|
| 69 |
Avoid Very Large Partitions |
| 70 |
--------------------------- |
| 71 |
|
| 72 |
Your chunks of data should be small enough so that many of them fit in a |
| 73 |
worker's available memory at once. You often control this when you select |
| 74 |
partition size in Dask DataFrame (see :ref:`DataFrame Partitions <dataframe-design-partitions>`) |
| 75 |
or chunk size in Dask Array (see :doc:`Array Chunks <array-chunks>`). |
| 76 |
|
| 77 |
Dask will likely manipulate as many chunks in parallel on one machine as you |
| 78 |
have cores on that machine. So if you have 1 GB chunks and ten |
| 79 |
cores, then Dask is likely to use *at least* 10 GB of memory. Additionally, |
| 80 |
it's common for Dask to have 2-3 times as many chunks available to work on so |
| 81 |
that it always has something to work on. |
| 82 |
|
| 83 |
If you have a machine with 100 GB and 10 cores, then you might want to choose |
| 84 |
chunks in the 1GB range. You have space for ten chunks per core which gives |
| 85 |
Dask a healthy margin, without having tasks that are too small. |
| 86 |
|
| 87 |
Note that you also want to avoid chunk sizes that are too small. See the next |
| 88 |
section for details. For a more detailed guide to choosing chunk sizes for |
| 89 |
Dask Arrays, see this blog post on `Choosing good chunk sizes <https://blog.dask.org/2021/11/02/choosing-dask-chunk-sizes>`_. |
| 90 |
|
| 91 |
|
| 92 |
Avoid Very Large Graphs |
| 93 |
----------------------- |
| 94 |
|
| 95 |
Dask workloads are composed of *tasks*. |
| 96 |
A task is a Python function, like ``np.sum`` applied onto a Python object, |
| 97 |
like a pandas DataFrame or NumPy array. If you are working with Dask |
| 98 |
collections with many partitions, then every operation you do, like ``x + 1`` |
| 99 |
likely generates many tasks, at least as many as partitions in your collection. |
| 100 |
|
| 101 |
Every task comes with some overhead. This is somewhere between 200us and 1ms. |
| 102 |
If you have a computation with thousands of tasks this is fine, there will be |
| 103 |
about a second of overhead, and that may not trouble you. |
| 104 |
|
| 105 |
However when you have very large graphs with millions of tasks then this may |
| 106 |
become troublesome, both because overhead is now in the 10 minutes to hours |
| 107 |
range, and also because the overhead of dealing with such a large graph can |
| 108 |
start to overwhelm the scheduler. |
| 109 |
|
| 110 |
You can build smaller graphs by: |
| 111 |
|
| 112 |
- **Increasing your chunk size:** If you have a 1,000 GB of data and are using |
| 113 |
10 MB chunks, then you have 100,000 partitions. Every operation on such |
| 114 |
a collection will generate at least 100,000 tasks. |
| 115 |
|
| 116 |
However if you increase your chunksize to 1 GB or even a few GB then you |
| 117 |
reduce the overhead by orders of magnitude. This requires that your |
| 118 |
workers have much more than 1 GB of memory, but that's typical for larger |
| 119 |
workloads. |
| 120 |
|
| 121 |
- **Fusing operations together:** Dask will do a bit of this on its own, but you |
| 122 |
can help it. If you have a very complex operation with dozens of |
| 123 |
sub-operations, maybe you can pack that into a single Python function |
| 124 |
and use a function like ``da.map_blocks`` or ``dd.map_partitions``. |
| 125 |
|
| 126 |
In general, the more administrative work you can move into your functions |
| 127 |
the better. That way the Dask scheduler doesn't need to think about all |
| 128 |
of the fine-grained operations. |
| 129 |
|
| 130 |
- **Breaking up your computation:** For very large workloads you may also want to |
| 131 |
try sending smaller chunks to Dask at a time. For example if you're |
| 132 |
processing a petabyte of data but find that Dask is only happy with 100 |
| 133 |
TB, maybe you can break up your computation into ten pieces and submit |
| 134 |
them one after the other. |
| 135 |
|
| 136 |
Learn Techniques For Customization |
| 137 |
---------------------------------- |
| 138 |
|
| 139 |
The high level Dask collections (array, DataFrame, bag) include common |
| 140 |
operations that follow standard Python APIs from NumPy and pandas. |
| 141 |
However, many Python workloads are complex and may require operations that are |
| 142 |
not included in these high level APIs. |
| 143 |
|
| 144 |
Fortunately, there are many options to support custom workloads: |
| 145 |
|
| 146 |
- All collections have a ``map_partitions`` or ``map_blocks`` function, that |
| 147 |
applies a user provided function across every pandas DataFrame or NumPy array |
| 148 |
in the collection. Because Dask collections are made up of normal Python |
| 149 |
objects, it's often quite easy to map custom functions across partitions of a |
| 150 |
dataset without much modification. |
| 151 |
|
| 152 |
.. code-block:: python |
| 153 |
|
| 154 |
df.map_partitions(my_custom_func) |
| 155 |
|
| 156 |
- More complex ``map_*`` functions. Sometimes your custom behavior isn't |
| 157 |
embarrassingly parallel, but requires more advanced communication. For |
| 158 |
example maybe you need to communicate a little bit of information from one |
| 159 |
partition to the next, or maybe you want to build a custom aggregation. |
| 160 |
|
| 161 |
Dask collections include methods for these as well. |
| 162 |
|
| 163 |
- For even more complex workloads you can convert your collections into |
| 164 |
individual blocks, and arrange those blocks as you like using Dask Delayed. |
| 165 |
There is usually a ``to_delayed`` method on every collection. |
| 166 |
|
| 167 |
.. currentmodule:: dask.dataframe |
| 168 |
|
| 169 |
.. autosummary:: |
| 170 |
|
| 171 |
map_partitions |
| 172 |
map_overlap |
| 173 |
groupby.Aggregation |
| 174 |
|
| 175 |
.. currentmodule:: dask.array |
| 176 |
|
| 177 |
.. autosummary:: |
| 178 |
|
| 179 |
blockwise |
| 180 |
map_blocks |
| 181 |
map_overlap |
| 182 |
reduction |
| 183 |
|
| 184 |
Store Data Efficiently |
| 185 |
---------------------- |
| 186 |
|
| 187 |
As your ability to compute increases you will likely find that data access and |
| 188 |
I/O take up a larger portion of your total time. Additionally, parallel |
| 189 |
computing will often add new constraints to how your store your data, |
| 190 |
particularly around providing random access to blocks of your data that are in |
| 191 |
line with how you plan to compute on it. |
| 192 |
|
| 193 |
For example: |
| 194 |
|
| 195 |
- For compression you'll probably find that you drop gzip and bz2, and embrace |
| 196 |
newer systems like lz4, snappy, and Z-Standard that provide better |
| 197 |
performance and random access. |
| 198 |
- For storage formats you may find that you want self-describing formats that |
| 199 |
are optimized for random access, metadata storage, and binary encoding like |
| 200 |
`Parquet <https://parquet.apache.org/>`_, `ORC <https://orc.apache.org/>`_, |
| 201 |
`Zarr <https://zarr.readthedocs.io/en/stable/>`_, |
| 202 |
`HDF5 <https://portal.hdfgroup.org/display/HDF5/HDF5>`_, and |
| 203 |
`GeoTIFF <https://en.wikipedia.org/wiki/GeoTIFF>`_. |
| 204 |
- When working on the cloud you may find that some older formats like HDF5 may |
| 205 |
not work as well. |
| 206 |
- You may want to partition or chunk your data in ways that align well to |
| 207 |
common queries. In Dask DataFrame this might mean choosing a column to |
| 208 |
sort by for fast selection and joins. For Dask Array this might mean |
| 209 |
choosing chunk sizes that are aligned with your access patterns and |
| 210 |
algorithms. |
| 211 |
|
| 212 |
Processes and Threads |
| 213 |
--------------------- |
| 214 |
|
| 215 |
If you're doing mostly numeric work with Numpy, pandas, Scikit-learn, Numba, |
| 216 |
and other libraries that release the `GIL <https://docs.python.org/3/glossary.html#term-global-interpreter-lock>`_, then use mostly threads. If you're |
| 217 |
doing work on text data or Python collections like lists and dicts then use |
| 218 |
mostly processes. |
| 219 |
|
| 220 |
If you're on larger machines with a high thread count (greater than 10), then |
| 221 |
you should probably split things up into at least a few processes regardless. |
| 222 |
Python can be highly productive with 10 threads per process with numeric work, |
| 223 |
but not 50 threads. |
| 224 |
|
| 225 |
For more information on threads, processes, and how to configure them in Dask, see |
| 226 |
:doc:`the scheduler documentation <scheduling>`. |
| 227 |
|
| 228 |
|
| 229 |
Load Data with Dask |
| 230 |
------------------- |
| 231 |
|
| 232 |
A common anti-pattern we se is people creating large Python objects like a DataFrame |
| 233 |
or an Array on the client (i.e. their local machine) outside of Dask and then embedding |
| 234 |
them into the computation. This means that Dask has to send these objects over the network |
| 235 |
multiple times instead of just passing pointers to the data. |
| 236 |
|
| 237 |
This incurs a lot of overhead and slows down a computation quite significantly, especially |
| 238 |
so if the network connection between the client and the scheduler is slow. It can |
| 239 |
also overload the scheduler so that it errors with out of memory errors. Instead, you |
| 240 |
should use Dask methods to load the data and use Dask to control the results. |
| 241 |
|
| 242 |
Here are some common patterns to avoid and nicer alternatives: |
| 243 |
|
| 244 |
|
| 245 |
.. tab-set:: |
| 246 |
|
| 247 |
.. tab-item:: DataFrames |
| 248 |
:sync: dataframe |
| 249 |
|
| 250 |
We are using Dask to read a parquet dataset before appending a set of pandas |
| 251 |
DataFrames to it. We are loading the csv files into memory before sending the |
| 252 |
data to Dask. |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
ddf = dd.read_parquet(...) |
| 257 |
|
| 258 |
pandas_dfs = [] |
| 259 |
for fn in filenames: |
| 260 |
pandas_dfs(pandas.read_csv(fn)) # Read locally with pandas |
| 261 |
ddf = dd.concat([ddf] + pandas_dfs) # Give to Dask |
| 262 |
|
| 263 |
Instead, we can use Dask to read the csv files directly, keeping all data |
| 264 |
on the cluster. |
| 265 |
|
| 266 |
.. code-block:: python |
| 267 |
|
| 268 |
ddf = dd.read_parquet(...) |
| 269 |
ddf2 = dd.read_csv(filenames) |
| 270 |
ddf = dd.concat([ddf, ddf2]) |
| 271 |
|
| 272 |
|
| 273 |
.. tab-item:: Arrays |
| 274 |
:sync: array |
| 275 |
|
| 276 |
We are using NumPy to create an in-memory array before handing it over to |
| 277 |
Dask, forcing Dask to embed the array into the task graph instead of handling |
| 278 |
pointers to the data. |
| 279 |
|
| 280 |
.. code-block:: python |
| 281 |
|
| 282 |
f = h5py.File(...) |
| 283 |
|
| 284 |
x = np.asarray(f["x"]) # Get data as a NumPy array locally |
| 285 |
x = da.from_array(x) # Hand NumPy array to Dask |
| 286 |
|
| 287 |
Instead, we can use Dask to read the file directly, keeping all data |
| 288 |
on the cluster. |
| 289 |
|
| 290 |
.. code-block:: python |
| 291 |
|
| 292 |
f = h5py.File(...) |
| 293 |
x = da.from_array(f["x"]) # Let Dask do the reading |
| 294 |
|
| 295 |
.. tab-item:: Delayed |
| 296 |
:sync: delayed |
| 297 |
|
| 298 |
We are using pandas to read a large CSV file before building a Graph |
| 299 |
with delayed to parallelize a computation on the data. |
| 300 |
|
| 301 |
.. code-block:: python |
| 302 |
|
| 303 |
@dask.delayed |
| 304 |
def process(a, b): |
| 305 |
... |
| 306 |
|
| 307 |
df = pandas.read_csv("some-large-file.csv") # Create large object locally |
| 308 |
results = [] |
| 309 |
for item in L: |
| 310 |
result = process(item, df) # include df in every delayed call |
| 311 |
results.append(result) |
| 312 |
|
| 313 |
Instead, we can use delayed to read the data as well. This avoid embedding the |
| 314 |
large file into the graph, Dask can just pass a reference to the delayed |
| 315 |
object around. |
| 316 |
|
| 317 |
.. code-block:: python |
| 318 |
|
| 319 |
@dask.delayed |
| 320 |
def process(a, b): |
| 321 |
... |
| 322 |
|
| 323 |
df = dask.delayed(pandas.read_csv)("some-large-file.csv") # Let Dask build object |
| 324 |
results = [] |
| 325 |
for item in L: |
| 326 |
result = process(item, df) # include pointer to df in every delayed call |
| 327 |
results.append(result) |
| 328 |
|
| 329 |
Embedding large objects like pandas DataFrames or Arrays into the computation is a |
| 330 |
frequent pain point for Dask users. It adds a significant delay until the scheduler |
| 331 |
has received and is able to start the computation and stresses the scheduler during |
| 332 |
the computation. |
| 333 |
|
| 334 |
Using Dask to load these objects instead avoids these issues and improves the performance |
| 335 |
of a computation significantly. |
| 336 |
|
| 337 |
Avoid calling compute repeatedly |
| 338 |
-------------------------------- |
| 339 |
|
| 340 |
Calling ``compute`` will block the execution on the client until the Dask computation |
| 341 |
completes. A pattern we regularly see is users calling ``compute`` in a loop or sequentially |
| 342 |
on slightly different queries. |
| 343 |
|
| 344 |
This prohibits Dask from parallelizing different computations on the cluster and from |
| 345 |
sharing intermediate results between different queries. |
| 346 |
|
| 347 |
.. code-block:: python |
| 348 |
|
| 349 |
foo = ... |
| 350 |
results = [] |
| 351 |
for i in range(...): |
| 352 |
results.append(foo.select(...).compute()) |
| 353 |
|
| 354 |
This holds execution every time that the iteration arrives at the compute call computing |
| 355 |
one query at a time. |
| 356 |
|
| 357 |
.. code-block:: python |
| 358 |
|
| 359 |
foo = ... |
| 360 |
results = [] |
| 361 |
for i in range(...): |
| 362 |
results.append(foo.select(...)) # no compute here |
| 363 |
results = dask.compute(*results) |
| 364 |
|
| 365 |
This allows Dask to compute the shared parts of the computation (like the |
| 366 |
``foo`` object above) only once, rather than once per ``compute`` call and allows |
| 367 |
Dask to parallelize across the different selects as well instead of running |
| 368 |
them sequentially. |