| 1 |
User Interfaces |
| 2 |
=============== |
| 3 |
|
| 4 |
Dask supports several user interfaces: |
| 5 |
|
| 6 |
- High-Level |
| 7 |
- :doc:`Arrays <array>`: Parallel NumPy |
| 8 |
- :doc:`Bags <bag>`: Parallel lists |
| 9 |
- :doc:`DataFrames <dataframe>`: Parallel Pandas |
| 10 |
- `Machine Learning <https://ml.dask.org>`_ : Parallel Scikit-Learn |
| 11 |
- Others from external projects, like `XArray <https://xarray.pydata.org>`_ |
| 12 |
- Low-Level |
| 13 |
- :doc:`Delayed <delayed>`: Parallel function evaluation |
| 14 |
- :doc:`Futures <futures>`: Real-time parallel function evaluation |
| 15 |
|
| 16 |
Each of these user interfaces employs the same underlying parallel computing |
| 17 |
machinery, and so has the same scaling, diagnostics, resilience, and so on, but |
| 18 |
each provides a different set of parallel algorithms and programming style. |
| 19 |
|
| 20 |
This document helps you to decide which user interface best suits your needs, |
| 21 |
and gives some general information that applies to all interfaces. |
| 22 |
The pages linked above give more information about each interface in greater |
| 23 |
depth. |
| 24 |
|
| 25 |
High-Level Collections |
| 26 |
---------------------- |
| 27 |
|
| 28 |
Many people who start using Dask are explicitly looking for a scalable version of |
| 29 |
NumPy, Pandas, or Scikit-Learn. For these situations, the starting point within |
| 30 |
Dask is usually fairly clear. If you want scalable NumPy arrays, then start with Dask |
| 31 |
array; if you want scalable Pandas DataFrames, then start with Dask DataFrame, and so on. |
| 32 |
|
| 33 |
These high-level interfaces copy the standard interface with slight variations. |
| 34 |
These interfaces automatically parallelize over larger datasets for you for a |
| 35 |
large subset of the API from the original project. |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
|
| 39 |
# Arrays |
| 40 |
import dask.array as da |
| 41 |
rng = da.random.default_rng() |
| 42 |
x = rng.uniform(low=0, high=10, size=(10000, 10000), # normal numpy code |
| 43 |
chunks=(1000, 1000)) # break into chunks of size 1000x1000 |
| 44 |
|
| 45 |
y = x + x.T - x.mean(axis=0) # Use normal syntax for high level algorithms |
| 46 |
|
| 47 |
# DataFrames |
| 48 |
import dask.dataframe as dd |
| 49 |
df = dd.read_csv('2018-*-*.csv', parse_dates='timestamp', # normal Pandas code |
| 50 |
blocksize=64000000) # break text into 64MB chunks |
| 51 |
|
| 52 |
s = df.groupby('name').balance.mean() # Use normal syntax for high level algorithms |
| 53 |
|
| 54 |
# Bags / lists |
| 55 |
import dask.bag as db |
| 56 |
b = db.read_text('*.json').map(json.loads) |
| 57 |
total = (b.filter(lambda d: d['name'] == 'Alice') |
| 58 |
.map(lambda d: d['balance']) |
| 59 |
.sum()) |
| 60 |
|
| 61 |
It is important to remember that, while APIs may be similar, some differences do |
| 62 |
exist. Additionally, the performance of some algorithms may differ from their |
| 63 |
in-memory counterparts due to the advantages and disadvantages of parallel |
| 64 |
programming. Some thought and attention is still required when using Dask. |
| 65 |
|
| 66 |
|
| 67 |
Low-Level Interfaces |
| 68 |
-------------------- |
| 69 |
|
| 70 |
Often when parallelizing existing code bases or building custom algorithms, you |
| 71 |
run into code that is parallelizable, but isn't just a big DataFrame or array. |
| 72 |
Consider the for-loopy code below: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
results = [] |
| 77 |
for a in A: |
| 78 |
for b in B: |
| 79 |
if a < b: |
| 80 |
c = f(a, b) |
| 81 |
else: |
| 82 |
c = g(a, b) |
| 83 |
results.append(c) |
| 84 |
|
| 85 |
There is potential parallelism in this code (the many calls to ``f`` and ``g`` |
| 86 |
can be done in parallel), but it's not clear how to rewrite it into a big |
| 87 |
array or DataFrame so that it can use a higher-level API. Even if you could |
| 88 |
rewrite it into one of these paradigms, it's not clear that this would be a |
| 89 |
good idea. Much of the meaning would likely be lost in translation, and this |
| 90 |
process would become much more difficult for more complex systems. |
| 91 |
|
| 92 |
Instead, Dask's lower-level APIs let you write parallel code one function call |
| 93 |
at a time within the context of your existing for loops. A common solution |
| 94 |
here is to use :doc:`Dask delayed <delayed>` to wrap individual function calls |
| 95 |
into a lazily constructed task graph: |
| 96 |
|
| 97 |
.. code-block:: python |
| 98 |
|
| 99 |
import dask |
| 100 |
|
| 101 |
lazy_results = [] |
| 102 |
for a in A: |
| 103 |
for b in B: |
| 104 |
if a < b: |
| 105 |
c = dask.delayed(f)(a, b) # add lazy task |
| 106 |
else: |
| 107 |
c = dask.delayed(g)(a, b) # add lazy task |
| 108 |
lazy_results.append(c) |
| 109 |
|
| 110 |
results = dask.compute(*lazy_results) # compute all in parallel |
| 111 |
|
| 112 |
|
| 113 |
Combining High- and Low-Level Interfaces |
| 114 |
---------------------------------------- |
| 115 |
|
| 116 |
It is common to combine high- and low-level interfaces. |
| 117 |
For example, you might use Dask array/bag/dataframe to load in data and do |
| 118 |
initial pre-processing, then switch to Dask delayed for a custom algorithm that |
| 119 |
is specific to your domain, then switch back to Dask array/dataframe to clean |
| 120 |
up and store results. Understanding both sets of user interfaces, and how |
| 121 |
to switch between them, can be a productive combination. |
| 122 |
|
| 123 |
.. code-block:: python |
| 124 |
|
| 125 |
# Convert to a list of delayed Pandas dataframes |
| 126 |
delayed_values = df.to_delayed() |
| 127 |
|
| 128 |
# Manipulate delayed values arbitrarily as you like |
| 129 |
|
| 130 |
# Convert many delayed Pandas DataFrames back to a single Dask DataFrame |
| 131 |
df = dd.from_delayed(delayed_values) |
| 132 |
|
| 133 |
|
| 134 |
Laziness and Computing |
| 135 |
---------------------- |
| 136 |
|
| 137 |
Most Dask user interfaces are *lazy*, meaning that they do not evaluate until |
| 138 |
you explicitly ask for a result using the ``compute`` method: |
| 139 |
|
| 140 |
.. code-block:: python |
| 141 |
|
| 142 |
# This array syntax doesn't cause computation |
| 143 |
y = x + x.T - x.mean(axis=0) |
| 144 |
|
| 145 |
# Trigger computation by explicitly calling the compute method |
| 146 |
y = y.compute() |
| 147 |
|
| 148 |
If you have multiple results that you want to compute at the same time, use the |
| 149 |
``dask.compute`` function. This can share intermediate results and so be more |
| 150 |
efficient: |
| 151 |
|
| 152 |
.. code-block:: python |
| 153 |
|
| 154 |
# compute multiple results at the same time with the compute function |
| 155 |
min, max = dask.compute(y.min(), y.max()) |
| 156 |
|
| 157 |
Note that the ``compute()`` function returns in-memory results. It converts |
| 158 |
Dask DataFrames to Pandas DataFrames, Dask arrays to NumPy arrays, and Dask |
| 159 |
bags to lists. *You should only call compute on results that will fit |
| 160 |
comfortably in memory*. If your result does not fit in memory, then you might |
| 161 |
consider writing it to disk instead. |
| 162 |
|
| 163 |
.. code-block:: python |
| 164 |
|
| 165 |
# Write larger results out to disk rather than store them in memory |
| 166 |
my_dask_dataframe.to_parquet('myfile.parquet') |
| 167 |
my_dask_array.to_hdf5('myfile.hdf5') |
| 168 |
my_dask_bag.to_textfiles('myfile.*.txt') |
| 169 |
|
| 170 |
|
| 171 |
Persist into Distributed Memory |
| 172 |
------------------------------- |
| 173 |
|
| 174 |
.. warning:: |
| 175 |
|
| 176 |
persist will store the full dataset in memory. This has the disadvantage that |
| 177 |
the available memory must actually exceed the size of the dataset. Use persist |
| 178 |
only when interactively iterating on the same dataset over and over again and |
| 179 |
avoid it in productive use-cases as much as possible. |
| 180 |
|
| 181 |
Alternatively, if you are on a cluster, then you may want to trigger a |
| 182 |
computation and store the results in distributed memory. In this case you do |
| 183 |
not want to call ``compute``, which would create a single Pandas, NumPy, or |
| 184 |
list result. Instead, you want to call ``persist``, which returns a new Dask |
| 185 |
object that points to actively computing, or already computed results spread |
| 186 |
around your cluster's memory. |
| 187 |
|
| 188 |
.. code-block:: python |
| 189 |
|
| 190 |
# Compute returns an in-memory non-Dask object |
| 191 |
y = y.compute() |
| 192 |
|
| 193 |
# Persist returns an in-memory Dask object that uses distributed storage if available |
| 194 |
y = y.persist() |
| 195 |
|
| 196 |
This is common to see after data loading an preprocessing steps, but before |
| 197 |
rapid iteration, exploration, or complex algorithms. For example, we might read |
| 198 |
in a lot of data, filter down to a more manageable subset, and then persist |
| 199 |
data into memory so that we can iterate quickly. |
| 200 |
|
| 201 |
.. code-block:: python |
| 202 |
|
| 203 |
import dask.dataframe as dd |
| 204 |
df = dd.read_parquet('...') |
| 205 |
df = df[df.name == 'Alice'] # select important subset of data |
| 206 |
df = df.persist() # trigger computation in the background |
| 207 |
|
| 208 |
# These are all relatively fast now that the relevant data is in memory |
| 209 |
df.groupby(df.id).balance.sum().compute() # explore data quickly |
| 210 |
df.groupby(df.id).balance.mean().compute() # explore data quickly |
| 211 |
df.id.nunique() # explore data quickly |
| 212 |
|
| 213 |
|
| 214 |
Lazy vs Immediate |
| 215 |
----------------- |
| 216 |
|
| 217 |
As mentioned above, most Dask workloads are lazy, that is, they don't start any |
| 218 |
work until you explicitly trigger them with a call to ``compute()``. |
| 219 |
However, sometimes you *do* want to submit work as quickly as possible, track it |
| 220 |
over time, submit new work or cancel work depending on partial results, and so |
| 221 |
on. This can be useful when tracking or responding to real-time events, |
| 222 |
handling streaming data, or when building complex and adaptive algorithms. |
| 223 |
|
| 224 |
For these situations, people typically turn to the :doc:`futures interface |
| 225 |
<futures>` which is a low-level interface like Dask delayed, but operates |
| 226 |
immediately rather than lazily. |
| 227 |
|
| 228 |
Here is the same example with Dask delayed and Dask futures to illustrate the |
| 229 |
difference. |
| 230 |
|
| 231 |
Delayed: Lazy |
| 232 |
~~~~~~~~~~~~~ |
| 233 |
|
| 234 |
.. code-block:: python |
| 235 |
|
| 236 |
@dask.delayed |
| 237 |
def inc(x): |
| 238 |
return x + 1 |
| 239 |
|
| 240 |
@dask.delayed |
| 241 |
def add(x, y): |
| 242 |
return x + y |
| 243 |
|
| 244 |
a = inc(1) # no work has happened yet |
| 245 |
b = inc(2) # no work has happened yet |
| 246 |
c = add(a, b) # no work has happened yet |
| 247 |
|
| 248 |
c = c.compute() # This triggers all of the above computations |
| 249 |
|
| 250 |
|
| 251 |
Futures: Immediate |
| 252 |
~~~~~~~~~~~~~~~~~~ |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
from dask.distributed import Client |
| 257 |
client = Client() |
| 258 |
|
| 259 |
def inc(x): |
| 260 |
return x + 1 |
| 261 |
|
| 262 |
def add(x, y): |
| 263 |
return x + y |
| 264 |
|
| 265 |
a = client.submit(inc, 1) # work starts immediately |
| 266 |
b = client.submit(inc, 2) # work starts immediately |
| 267 |
c = client.submit(add, a, b) # work starts immediately |
| 268 |
|
| 269 |
c = c.result() # block until work finishes, then gather result |
| 270 |
|
| 271 |
You can also trigger work with the high-level collections using the |
| 272 |
``persist`` function. This will cause work to happen in the background when |
| 273 |
using the distributed scheduler. |
| 274 |
|
| 275 |
|
| 276 |
Combining Interfaces |
| 277 |
-------------------- |
| 278 |
|
| 279 |
There are established ways to combine the interfaces above: |
| 280 |
|
| 281 |
1. The high-level interfaces (array, bag, dataframe) have a ``to_delayed`` |
| 282 |
method that can convert to a sequence (or grid) of Dask delayed objects |
| 283 |
|
| 284 |
.. code-block:: python |
| 285 |
|
| 286 |
delayeds = df.to_delayed() |
| 287 |
|
| 288 |
2. The high-level interfaces (array, bag, dataframe) have a ``from_delayed`` |
| 289 |
method that can convert from either Delayed *or* Future objects |
| 290 |
|
| 291 |
.. code-block:: python |
| 292 |
|
| 293 |
df = dd.from_delayed(delayeds) |
| 294 |
df = dd.from_delayed(futures) |
| 295 |
|
| 296 |
3. The ``Client.compute`` method converts Delayed objects into Futures |
| 297 |
|
| 298 |
.. code-block:: python |
| 299 |
|
| 300 |
futures = client.compute(delayeds) |
| 301 |
|
| 302 |
4. The ``dask.distributed.futures_of`` function gathers futures from |
| 303 |
persisted collections |
| 304 |
|
| 305 |
.. code-block:: python |
| 306 |
|
| 307 |
from dask.distributed import futures_of |
| 308 |
|
| 309 |
df = df.persist() # start computation in the background |
| 310 |
futures = futures_of(df) |
| 311 |
|
| 312 |
5. The Dask.delayed object converts Futures into delayed objects |
| 313 |
|
| 314 |
.. code-block:: python |
| 315 |
|
| 316 |
delayed_value = dask.delayed(future) |
| 317 |
|
| 318 |
The approaches above should suffice to convert any interface into any other. |
| 319 |
We often see some anti-patterns that do not work as well: |
| 320 |
|
| 321 |
1. Calling low-level APIs (delayed or futures) on high-level objects (like |
| 322 |
Dask arrays or DataFrames). This downgrades those objects to their NumPy or |
| 323 |
Pandas equivalents, which may not be desired. |
| 324 |
Often people are looking for APIs like ``dask.array.map_blocks`` or |
| 325 |
``dask.dataframe.map_partitions`` instead. |
| 326 |
2. Calling ``compute()`` on Future objects. |
| 327 |
Often people want the ``.result()`` method instead. |
| 328 |
3. Calling NumPy/Pandas functions on high-level Dask objects or |
| 329 |
high-level Dask functions on NumPy/Pandas objects |
| 330 |
|
| 331 |
Conclusion |
| 332 |
---------- |
| 333 |
|
| 334 |
Most people who use Dask start with only one of the interfaces above but |
| 335 |
eventually learn how to use a few interfaces together. This helps them |
| 336 |
leverage the sophisticated algorithms in the high-level interfaces while also |
| 337 |
working around tricky problems with the low-level interfaces. |
| 338 |
|
| 339 |
For more information, see the documentation for the particular user interfaces |
| 340 |
below: |
| 341 |
|
| 342 |
- High Level |
| 343 |
- :doc:`Arrays <array>`: Parallel NumPy |
| 344 |
- :doc:`Bags <bag>`: Parallel lists |
| 345 |
- :doc:`DataFrames <dataframe>`: Parallel Pandas |
| 346 |
- `Machine Learning <https://ml.dask.org>`_ : Parallel Scikit-Learn |
| 347 |
- Others from external projects, like `XArray <https://xarray.pydata.org>`_ |
| 348 |
- Low Level |
| 349 |
- :doc:`Delayed <delayed>`: Parallel function evaluation |
| 350 |
- :doc:`Futures <futures>`: Real-time parallel function evaluation |