Debian Codegraph @

docs/source/10-minutes-to-dask.rst

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 10 Minutes to Dask
2 ==================
3
4 .. meta::
5 :description: This is a short overview of Dask geared towards new users. Additional Dask information can be found in the rest of the Dask documentation.
6
7 This is a short overview of Dask geared towards new users.
8 There is much more information contained in the rest of the documentation.
9
10 .. figure:: images/dask-overview.svg
11 :alt: Dask overview. Dask is composed of three parts: collections, task graphs, and schedulers.
12 :align: center
13
14 High level collections are used to generate task graphs which can be executed by schedulers on a single machine or a cluster.
15
16 We normally import Dask as follows:
17
18 .. code-block:: python
19
20 >>> import numpy as np
21 >>> import pandas as pd
22
23 >>> import dask.dataframe as dd
24 >>> import dask.array as da
25 >>> import dask.bag as db
26
27 Based on the type of data you are working with, you might not need all of these.
28
29 Creating a Dask Object
30 ----------------------
31
32 You can create a Dask object from scratch by supplying existing data and optionally
33 including information about how the chunks should be structured.
34
35
36 .. tab-set::
37
38 .. tab-item:: DataFrame
39 :sync: dataframe
40
41 See :doc:`dataframe`.
42
43 .. code-block:: python
44
45 >>> index = pd.date_range("2021-09-01", periods=2400, freq="1h")
46 ... df = pd.DataFrame({"a": np.arange(2400), "b": list("abcaddbe" * 300)}, index=index)
47 ... ddf = dd.from_pandas(df, npartitions=10)
48 ... ddf
49 Dask DataFrame Structure:
50 a b
51 npartitions=10
52 2021-09-01 00:00:00 int64 object
53 2021-09-11 00:00:00 ... ...
54 ... ... ...
55 2021-11-30 00:00:00 ... ...
56 2021-12-09 23:00:00 ... ...
57 Dask Name: from_pandas, 10 tasks
58
59 Now we have a Dask DataFrame with 2 columns and 2400 rows composed of 10 partitions where
60 each partition has 240 rows. Each partition represents a piece of the data.
61
62 Here are some key properties of a DataFrame:
63
64 .. code-block:: python
65
66 >>> # check the index values covered by each partition
67 ... ddf.divisions
68 (Timestamp('2021-09-01 00:00:00', freq='H'),
69 Timestamp('2021-09-11 00:00:00', freq='H'),
70 Timestamp('2021-09-21 00:00:00', freq='H'),
71 Timestamp('2021-10-01 00:00:00', freq='H'),
72 Timestamp('2021-10-11 00:00:00', freq='H'),
73 Timestamp('2021-10-21 00:00:00', freq='H'),
74 Timestamp('2021-10-31 00:00:00', freq='H'),
75 Timestamp('2021-11-10 00:00:00', freq='H'),
76 Timestamp('2021-11-20 00:00:00', freq='H'),
77 Timestamp('2021-11-30 00:00:00', freq='H'),
78 Timestamp('2021-12-09 23:00:00', freq='H'))
79
80 >>> # access a particular partition
81 ... ddf.partitions[1]
82 Dask DataFrame Structure:
83 a b
84 npartitions=1
85 2021-09-11 int64 object
86 2021-09-21 ... ...
87 Dask Name: blocks, 11 tasks
88
89 .. tab-item:: Array
90 :sync: array
91
92 See :doc:`array`.
93
94 .. jupyter-execute::
95
96 import numpy as np
97 import dask.array as da
98
99 data = np.arange(100_000).reshape(200, 500)
100 a = da.from_array(data, chunks=(100, 100))
101 a
102
103 Now we have a 2D array with the shape (200, 500) composed of 10 chunks where
104 each chunk has the shape (100, 100). Each chunk represents a piece of the data.
105
106 Here are some key properties of a Dask Array:
107
108 .. jupyter-execute::
109
110 # inspect the chunks
111 a.chunks
112
113 .. jupyter-execute::
114
115 # access a particular block of data
116 a.blocks[1, 3]
117
118 .. tab-item:: Bag
119 :sync: bag
120
121 See :doc:`bag`.
122
123 .. code-block:: python
124
125 >>> b = db.from_sequence([1, 2, 3, 4, 5, 6, 2, 1], npartitions=2)
126 ... b
127 dask.bag<from_sequence, npartitions=2>
128
129 Now we have a sequence with 8 items composed of 2 partitions where each partition
130 has 4 items in it. Each partition represents a piece of the data.
131
132
133 Indexing
134 --------
135
136 Indexing Dask collections feels just like slicing NumPy arrays or pandas DataFrame.
137
138 .. tab-set::
139
140 .. tab-item:: DataFrame
141 :sync: dataframe
142
143 .. code-block:: python
144
145 >>> ddf.b
146 Dask Series Structure:
147 npartitions=10
148 2021-09-01 00:00:00 object
149 2021-09-11 00:00:00 ...
150 ...
151 2021-11-30 00:00:00 ...
152 2021-12-09 23:00:00 ...
153 Name: b, dtype: object
154 Dask Name: getitem, 20 tasks
155
156 >>> ddf["2021-10-01": "2021-10-09 5:00"]
157 Dask DataFrame Structure:
158 a b
159 npartitions=1
160 2021-10-01 00:00:00.000000000 int64 object
161 2021-10-09 05:00:59.999999999 ... ...
162 Dask Name: loc, 11 tasks
163
164 .. tab-item:: Array
165 :sync: array
166
167 .. jupyter-execute::
168
169 a[:50, 200]
170
171 .. tab-item:: Bag
172 :sync: bag
173
174 A Bag is an unordered collection allowing repeats. So it is like a list, but it doesn’t
175 guarantee an ordering among elements. There is no way to index Bags since they are
176 not ordered.
177
178
179 Computation
180 -----------
181
182 Dask is lazily evaluated. The result from a computation isn't computed until
183 you ask for it. Instead, a Dask task graph for the computation is produced.
184
185 Anytime you have a Dask object and you want to get the result, call ``compute``:
186
187 .. tab-set::
188
189 .. tab-item:: DataFrame
190 :sync: dataframe
191
192 .. code-block:: python
193
194 >>> ddf["2021-10-01": "2021-10-09 5:00"].compute()
195 a b
196 2021-10-01 00:00:00 720 a
197 2021-10-01 01:00:00 721 b
198 2021-10-01 02:00:00 722 c
199 2021-10-01 03:00:00 723 a
200 2021-10-01 04:00:00 724 d
201 ... ... ..
202 2021-10-09 01:00:00 913 b
203 2021-10-09 02:00:00 914 c
204 2021-10-09 03:00:00 915 a
205 2021-10-09 04:00:00 916 d
206 2021-10-09 05:00:00 917 d
207
208 [198 rows x 2 columns]
209
210 .. tab-item:: Array
211 :sync: array
212
213 .. code-block:: python
214
215 >>> a[:50, 200].compute()
216 array([ 200, 700, 1200, 1700, 2200, 2700, 3200, 3700, 4200,
217 4700, 5200, 5700, 6200, 6700, 7200, 7700, 8200, 8700,
218 9200, 9700, 10200, 10700, 11200, 11700, 12200, 12700, 13200,
219 13700, 14200, 14700, 15200, 15700, 16200, 16700, 17200, 17700,
220 18200, 18700, 19200, 19700, 20200, 20700, 21200, 21700, 22200,
221 22700, 23200, 23700, 24200, 24700])
222
223 .. tab-item:: Bag
224 :sync: bag
225
226 .. code-block:: python
227
228 >>> b.compute()
229 [1, 2, 3, 4, 5, 6, 2, 1]
230
231
232 Methods
233 -------
234
235 Dask collections match existing numpy and pandas methods, so they should feel familiar.
236 Call the method to set up the task graph, and then call ``compute`` to get the result.
237
238 .. tab-set::
239
240 .. tab-item:: DataFrame
241 :sync: dataframe
242
243 .. code-block:: python
244
245 >>> ddf.a.mean()
246 dd.Scalar<series-..., dtype=float64>
247
248 >>> ddf.a.mean().compute()
249 1199.5
250
251 >>> ddf.b.unique()
252 Dask Series Structure:
253 npartitions=1
254 object
255 ...
256 Name: b, dtype: object
257 Dask Name: unique-agg, 33 tasks
258
259 >>> ddf.b.unique().compute()
260 0 a
261 1 b
262 2 c
263 3 d
264 4 e
265 Name: b, dtype: object
266
267 Methods can be chained together just like in pandas
268
269 .. code-block:: python
270
271 >>> result = ddf["2021-10-01": "2021-10-09 5:00"].a.cumsum() - 100
272 ... result
273 Dask Series Structure:
274 npartitions=1
275 2021-10-01 00:00:00.000000000 int64
276 2021-10-09 05:00:59.999999999 ...
277 Name: a, dtype: int64
278 Dask Name: sub, 16 tasks
279
280 >>> result.compute()
281 2021-10-01 00:00:00 620
282 2021-10-01 01:00:00 1341
283 2021-10-01 02:00:00 2063
284 2021-10-01 03:00:00 2786
285 2021-10-01 04:00:00 3510
286 ...
287 2021-10-09 01:00:00 158301
288 2021-10-09 02:00:00 159215
289 2021-10-09 03:00:00 160130
290 2021-10-09 04:00:00 161046
291 2021-10-09 05:00:00 161963
292 Freq: H, Name: a, Length: 198, dtype: int64
293
294 .. tab-item:: Array
295 :sync: array
296
297 .. code-block:: python
298
299 >>> a.mean()
300 dask.array<mean_agg-aggregate, shape=(), dtype=float64, chunksize=(), chunktype=numpy.ndarray>
301
302 >>> a.mean().compute()
303 49999.5
304
305 >>> np.sin(a)
306 dask.array<sin, shape=(200, 500), dtype=float64, chunksize=(100, 100), chunktype=numpy.ndarray>
307
308 >>> np.sin(a).compute()
309 array([[ 0. , 0.84147098, 0.90929743, ..., 0.58781939,
310 0.99834363, 0.49099533],
311 [-0.46777181, -0.9964717 , -0.60902011, ..., -0.89796748,
312 -0.85547315, -0.02646075],
313 [ 0.82687954, 0.9199906 , 0.16726654, ..., 0.99951642,
314 0.51387502, -0.4442207 ],
315 ...,
316 [-0.99720859, -0.47596473, 0.48287891, ..., -0.76284376,
317 0.13191447, 0.90539115],
318 [ 0.84645538, 0.00929244, -0.83641393, ..., 0.37178568,
319 -0.5802765 , -0.99883514],
320 [-0.49906936, 0.45953849, 0.99564877, ..., 0.10563876,
321 0.89383946, 0.86024828]])
322
323 >>> a.T
324 dask.array<transpose, shape=(500, 200), dtype=int64, chunksize=(100, 100), chunktype=numpy.ndarray>
325
326 >>> a.T.compute()
327 array([[ 0, 500, 1000, ..., 98500, 99000, 99500],
328 [ 1, 501, 1001, ..., 98501, 99001, 99501],
329 [ 2, 502, 1002, ..., 98502, 99002, 99502],
330 ...,
331 [ 497, 997, 1497, ..., 98997, 99497, 99997],
332 [ 498, 998, 1498, ..., 98998, 99498, 99998],
333 [ 499, 999, 1499, ..., 98999, 99499, 99999]])
334
335 Methods can be chained together just like in NumPy
336
337 .. code-block:: python
338
339 >>> b = a.max(axis=1)[::-1] + 10
340 ... b
341 dask.array<add, shape=(200,), dtype=int64, chunksize=(100,), chunktype=numpy.ndarray>
342
343 >>> b[:10].compute()
344 array([100009, 99509, 99009, 98509, 98009, 97509, 97009, 96509,
345 96009, 95509])
346
347 .. tab-item:: Bag
348 :sync: bag
349
350 Dask Bag implements operations like ``map``, ``filter``, ``fold``, and
351 ``groupby`` on collections of generic Python objects.
352
353 .. code-block:: python
354
355 >>> b.filter(lambda x: x % 2)
356 dask.bag<filter-lambda, npartitions=2>
357
358 >>> b.filter(lambda x: x % 2).compute()
359 [1, 3, 5, 1]
360
361 >>> b.distinct()
362 dask.bag<distinct-aggregate, npartitions=1>
363
364 >>> b.distinct().compute()
365 [1, 2, 3, 4, 5, 6]
366
367 Methods can be chained together.
368
369 .. code-block:: python
370
371 >>> c = db.zip(b, b.map(lambda x: x * 10))
372 ... c
373 dask.bag<zip, npartitions=2>
374
375 >>> c.compute()
376 [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60), (2, 20), (1, 10)]
377
378
379 Visualize the Task Graph
380 ------------------------
381
382 So far we've been setting up computations and calling ``compute``. In addition to
383 triggering computation, we can inspect the task graph to figure out what's going on.
384
385 .. tab-set::
386
387 .. tab-item:: DataFrame
388 :sync: dataframe
389
390 .. code-block:: python
391
392 >>> result.dask
393 HighLevelGraph with 7 layers.
394 <dask.highlevelgraph.HighLevelGraph object at 0x7f129df7a9d0>
395 1. from_pandas-0b850a81e4dfe2d272df4dc718065116
396 2. loc-fb7ada1e5ba8f343678fdc54a36e9b3e
397 3. getitem-55d10498f88fc709e600e2c6054a0625
398 4. series-cumsum-map-131dc242aeba09a82fea94e5442f3da9
399 5. series-cumsum-take-last-9ebf1cce482a441d819d8199eac0f721
400 6. series-cumsum-d51d7003e20bd5d2f767cd554bdd5299
401 7. sub-fed3e4af52ad0bd9c3cc3bf800544f57
402
403 >>> result.visualize()
404
405 .. image:: images/10_minutes_dataframe_graph.png
406 :alt: Dask task graph for the Dask dataframe computation. The task graph shows a "loc" and "getitem" operations selecting a small section of the dataframe values, before applying a cumulative sum "cumsum" operation, then finally subtracting a value from the result.
407
408 .. tab-item:: Array
409 :sync: array
410
411 .. code-block:: python
412
413 >>> b.dask
414 HighLevelGraph with 6 layers.
415 <dask.highlevelgraph.HighLevelGraph object at 0x7fd33a4aa400>
416 1. array-ef3148ecc2e8957c6abe629e08306680
417 2. amax-b9b637c165d9bf139f7b93458cd68ec3
418 3. amax-partial-aaf8028d4a4785f579b8d03ffc1ec615
419 4. amax-aggregate-07b2f92aee59691afaf1680569ee4a63
420 5. getitem-f9e225a2fd32b3d2f5681070d2c3d767
421 6. add-f54f3a929c7efca76a23d6c42cdbbe84
422
423 >>> b.visualize()
424
425 .. image:: images/10_minutes_array_graph.png
426 :alt: Dask task graph for the Dask array computation. The task graph shows many "amax" operations on each chunk of the Dask array, that are then aggregated to find "amax" along the first array axis, then reversing the order of the array values with a "getitem" slicing operation, before an "add" operation to get the final result.
427
428 .. tab-item:: Bag
429 :sync: bag
430
431 .. code-block:: python
432
433 >>> c.dask
434 HighLevelGraph with 3 layers.
435 <dask.highlevelgraph.HighLevelGraph object at 0x7f96d0814fd0>
436 1. from_sequence-cca2a33ba6e12645a0c9bc0fd3fe6c88
437 2. lambda-93a7a982c4231fea874e07f71b4bcd7d
438 3. zip-474300792cc4f502f1c1f632d50e0272
439
440 >>> c.visualize()
441
442 .. image:: images/10_minutes_bag_graph.png
443 :alt: Dask task graph for the Dask bag computation. The task graph shows a "lambda" operation, and then a "zip" operation is applied to the partitions of the Dask bag. There is no communication needed between the bag partitions, this is an embarrassingly parallel computation.
444
445 Low-Level Interfaces
446 --------------------
447 Often when parallelizing existing code bases or building custom algorithms, you
448 run into code that is parallelizable, but isn't just a big DataFrame or array.
449
450 .. tab-set::
451
452 .. tab-item:: Delayed: Lazy
453
454 :doc:`delayed` lets you to wrap individual function calls into a lazily constructed task graph:
455
456 .. code-block:: python
457
458 import dask
459
460 @dask.delayed
461 def inc(x):
462 return x + 1
463
464 @dask.delayed
465 def add(x, y):
466 return x + y
467
468 a = inc(1) # no work has happened yet
469 b = inc(2) # no work has happened yet
470 c = add(a, b) # no work has happened yet
471
472 c = c.compute() # This triggers all of the above computations
473
474 .. tab-item:: Futures: Immediate
475
476 Unlike the interfaces described so far, Futures are eager. Computation starts as soon
477 as the function is submitted (see :doc:`futures`).
478
479 .. code-block:: python
480
481 from dask.distributed import Client
482
483 client = Client()
484
485 def inc(x):
486 return x + 1
487
488 def add(x, y):
489 return x + y
490
491 a = client.submit(inc, 1) # work starts immediately
492 b = client.submit(inc, 2) # work starts immediately
493 c = client.submit(add, a, b) # work starts immediately
494
495 c = c.result() # block until work finishes, then gather result
496
497 .. note::
498
499 Futures can only be used with distributed cluster. See the section below for more
500 information.
501
502
503 Scheduling
504 ----------
505
506 After you have generated a task graph, it is the scheduler's job to execute it
507 (see :doc:`scheduling`).
508
509 By default, for the majority of Dask APIs, when you call ``compute`` on a Dask object,
510 Dask uses the thread pool on your computer (a.k.a threaded scheduler) to run computations in parallel.
511 This is true for :doc:`Dask Array <array>`, :doc:`Dask DataFrame <dataframe>`,
512 and :doc:`Dask Delayed <delayed>`. The exception being :doc:`Dask Bag <bag>`
513 which uses the multiprocessing scheduler by default.
514
515 If you want more control, use the distributed scheduler instead. Despite having
516 "distributed" in it's name, the distributed scheduler works well
517 on both single and multiple machines. Think of it as the "advanced scheduler".
518
519 .. tab-set::
520
521 .. tab-item:: Local
522
523 This is how you set up a cluster that uses only your own computer.
524
525 .. code-block:: python
526
527 >>> from dask.distributed import Client
528 ...
529 ... client = Client()
530 ... client
531 <Client: 'tcp://127.0.0.1:41703' processes=4 threads=12, memory=31.08 GiB>
532
533 .. tab-item:: Remote
534
535 This is how you connect to a cluster that is already running.
536
537 .. code-block:: python
538
539 >>> from dask.distributed import Client
540 ...
541 ... client = Client("<url-of-scheduler>")
542 ... client
543 <Client: 'tcp://127.0.0.1:41703' processes=4 threads=12, memory=31.08 GiB>
544
545 There are a variety of ways to set up a remote cluster. Refer to
546 :doc:`how to deploy dask clusters <deploying>` for more
547 information.
548
549 Once you create a client, any computation will run on the cluster that it points to.
550
551
552 Diagnostics
553 -----------
554
555 When using a distributed cluster, Dask provides a diagnostics dashboard where you can
556 see your tasks as they are processed.
557
558 .. code-block:: python
559
560 >>> client.dashboard_link
561 'http://127.0.0.1:8787/status'
562
563 To learn more about those graphs take a look at :doc:`dashboard`.