Debian Codegraph @

docs/source/custom-collections.rst

raw
1 Custom Collections
2 ==================
3
4 For many problems, the built-in Dask collections (``dask.array``,
5 ``dask.dataframe``, ``dask.bag``, and ``dask.delayed``) are sufficient. For
6 cases where they aren't, it's possible to create your own Dask collections. Here
7 we describe the required methods to fulfill the Dask collection interface.
8
9 .. note:: This is considered an advanced feature. For most cases the built-in
10 collections are probably sufficient.
11
12 Before reading this you should read and understand:
13
14 - :doc:`overview <graphs>`
15 - :doc:`graph specification <spec>`
16 - :doc:`custom graphs <custom-graphs>`
17
18 **Contents**
19
20 - :ref:`Description of the Dask collection interface <collection-interface>`
21 - :ref:`How this interface is used to implement the core Dask
22 methods <core-method-internals>`
23 - :ref:`How to add the core methods to your class <adding-methods-to-class>`
24 - :ref:`example-dask-collection`
25 - :ref:`How to check if something is a Dask collection <is-dask-collection>`
26 - :ref:`How to make tokenize work with your collection <deterministic-hashing>`
27
28
29 .. _collection-interface:
30
31 The Dask Collection Interface
32 -----------------------------
33
34 To create your own Dask collection, you need to fulfill the interface
35 defined by the :py:class:`dask.typing.DaskCollection` protocol. Note
36 that there is no required base class.
37
38 It is recommended to also read :ref:`core-method-internals` to see how this
39 interface is used inside Dask.
40
41 Collection Protocol
42 ~~~~~~~~~~~~~~~~~~~~
43
44 .. autoclass:: dask.typing.DaskCollection
45 :members: __dask_graph__, __dask_keys__, __dask_postcompute__,
46 __dask_postpersist__, __dask_tokenize__,
47 __dask_optimize__, __dask_scheduler__, compute, persist,
48 visualize
49
50 HLG Collection Protocol
51 ~~~~~~~~~~~~~~~~~~~~~~~
52
53 Collections backed by Dask's :ref:`high-level-graphs` must implement
54 an additional method, defined by this protocol:
55
56 .. autoclass:: dask.typing.HLGDaskCollection
57 :members: __dask_layers__
58
59 Scheduler ``get`` Protocol
60 ~~~~~~~~~~~~~~~~~~~~~~~~~~
61
62 The ``SchedulerGetProtocol`` defines the signature that a Dask
63 collection's ``__dask_scheduler__`` definition must adhere to.
64
65 .. autoclass:: dask.typing.SchedulerGetCallable
66 :members: __call__
67
68 Post-persist Callable Protocol
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71 Collections must define a ``__dask_postpersist__`` method which
72 returns a callable that adheres to the ``PostPersistCallable``
73 interface.
74
75 .. autoclass:: dask.typing.PostPersistCallable
76 :members: __call__
77
78 .. _core-method-internals:
79
80 Internals of the Core Dask Methods
81 ----------------------------------
82
83 Dask has a few *core* functions (and corresponding methods) that implement
84 common operations:
85
86 - ``compute``: Convert one or more Dask collections into their in-memory
87 counterparts
88 - ``persist``: Convert one or more Dask collections into equivalent Dask
89 collections with their results already computed and cached in memory
90 - ``optimize``: Convert one or more Dask collections into equivalent Dask
91 collections sharing one large optimized graph
92 - ``visualize``: Given one or more Dask collections, draw out the graph that
93 would be passed to the scheduler during a call to ``compute`` or ``persist``
94
95 Here we briefly describe the internals of these functions to illustrate how
96 they relate to the above interface.
97
98 Compute
99 ~~~~~~~
100
101 The operation of ``compute`` can be broken into three stages:
102
103 1. **Graph Merging & Optimization**
104
105 First, the individual collections are converted to a single large graph and
106 nested list of keys. How this happens depends on the value of the
107 ``optimize_graph`` keyword, which each function takes:
108
109 - If ``optimize_graph`` is ``True`` (default), then the collections are first
110 grouped by their ``__dask_optimize__`` methods. All collections with the
111 same ``__dask_optimize__`` method have their graphs merged and keys
112 concatenated, and then a single call to each respective
113 ``__dask_optimize__`` is made with the merged graphs and keys. The
114 resulting graphs are then merged.
115
116 - If ``optimize_graph`` is ``False``, then all the graphs are merged and all
117 the keys concatenated.
118
119 After this stage there is a single large graph and nested list of keys which
120 represents all the collections.
121
122 2. **Computation**
123
124 After the graphs are merged and any optimizations performed, the resulting
125 large graph and nested list of keys are passed on to the scheduler. The
126 scheduler to use is chosen as follows:
127
128 - If a ``get`` function is specified directly as a keyword, use that
129 - Otherwise, if a global scheduler is set, use that
130 - Otherwise fall back to the default scheduler for the given collections.
131 Note that if all collections don't share the same ``__dask_scheduler__``
132 then an error will be raised.
133
134 Once the appropriate scheduler ``get`` function is determined, it is called
135 with the merged graph, keys, and extra keyword arguments. After this stage,
136 ``results`` is a nested list of values. The structure of this list mirrors
137 that of ``keys``, with each key substituted with its corresponding result.
138
139 3. **Postcompute**
140
141 After the results are generated, the output values of ``compute`` need to be
142 built. This is what the ``__dask_postcompute__`` method is for.
143 ``__dask_postcompute__`` returns two things:
144
145 - A ``finalize`` function, which takes in the results for the corresponding
146 keys
147 - A tuple of extra arguments to pass to ``finalize`` after the results
148
149 To build the outputs, the list of collections and results is iterated over,
150 and the finalizer for each collection is called on its respective results.
151
152 In pseudocode, this process looks like the following:
153
154 .. code:: python
155
156 def compute(*collections, **kwargs):
157 # 1. Graph Merging & Optimization
158 # -------------------------------
159 if kwargs.pop('optimize_graph', True):
160 # If optimization is turned on, group the collections by
161 # optimization method, and apply each method only once to the merged
162 # sub-graphs.
163 optimization_groups = groupby_optimization_methods(collections)
164 graphs = []
165 for optimize_method, cols in optimization_groups:
166 # Merge the graphs and keys for the subset of collections that
167 # share this optimization method
168 sub_graph = merge_graphs([x.__dask_graph__() for x in cols])
169 sub_keys = [x.__dask_keys__() for x in cols]
170 # kwargs are forwarded to ``__dask_optimize__`` from compute
171 optimized_graph = optimize_method(sub_graph, sub_keys, **kwargs)
172 graphs.append(optimized_graph)
173 graph = merge_graphs(graphs)
174 else:
175 graph = merge_graphs([x.__dask_graph__() for x in collections])
176 # Keys are always the same
177 keys = [x.__dask_keys__() for x in collections]
178
179 # 2. Computation
180 # --------------
181 # Determine appropriate get function based on collections, global
182 # settings, and keyword arguments
183 get = determine_get_function(collections, **kwargs)
184 # Pass the merged graph, keys, and kwargs to ``get``
185 results = get(graph, keys, **kwargs)
186
187 # 3. Postcompute
188 # --------------
189 output = []
190 # Iterate over the results and collections
191 for res, collection in zip(results, collections):
192 finalize, extra_args = collection.__dask_postcompute__()
193 out = finalize(res, **extra_args)
194 output.append(out)
195
196 # `dask.compute` always returns tuples
197 return tuple(output)
198
199
200 Persist
201 ~~~~~~~
202
203 Persist is very similar to ``compute``, except for how the return values are
204 created. It too has three stages:
205
206 1. **Graph Merging & Optimization**
207
208 Same as in ``compute``.
209
210 2. **Computation**
211
212 Same as in ``compute``, except in the case of the distributed scheduler,
213 where the values in ``results`` are futures instead of values.
214
215 3. **Postpersist**
216
217 Similar to ``__dask_postcompute__``, ``__dask_postpersist__`` is used to
218 rebuild values in a call to ``persist``. ``__dask_postpersist__`` returns
219 two things:
220
221 - A ``rebuild`` function, which takes in a persisted graph. The keys of
222 this graph are the same as ``__dask_keys__`` for the corresponding
223 collection, and the values are computed results (for the single-machine
224 scheduler) or futures (for the distributed scheduler).
225 - A tuple of extra arguments to pass to ``rebuild`` after the graph
226
227 To build the outputs of ``persist``, the list of collections and results is
228 iterated over, and the rebuilder for each collection is called on the graph
229 for its respective results.
230
231 In pseudocode, this looks like the following:
232
233 .. code:: python
234
235 def persist(*collections, **kwargs):
236 # 1. Graph Merging & Optimization
237 # -------------------------------
238 # **Same as in compute**
239 graph = ...
240 keys = ...
241
242 # 2. Computation
243 # --------------
244 # **Same as in compute**
245 results = ...
246
247 # 3. Postpersist
248 # --------------
249 output = []
250 # Iterate over the results and collections
251 for res, collection in zip(results, collections):
252 # res has the same structure as keys
253 keys = collection.__dask_keys__()
254 # Get the computed graph for this collection.
255 # Here flatten converts a nested list into a single list
256 subgraph = {k: r for (k, r) in zip(flatten(keys), flatten(res))}
257
258 # Rebuild the output dask collection with the computed graph
259 rebuild, extra_args = collection.__dask_postpersist__()
260 out = rebuild(subgraph, *extra_args)
261
262 output.append(out)
263
264 # dask.persist always returns tuples
265 return tuple(output)
266
267
268 Optimize
269 ~~~~~~~~
270
271 The operation of ``optimize`` can be broken into two stages:
272
273 1. **Graph Merging & Optimization**
274
275 Same as in ``compute``.
276
277 2. **Rebuilding**
278
279 Similar to ``persist``, the ``rebuild`` function and arguments from
280 ``__dask_postpersist__`` are used to reconstruct equivalent collections from
281 the optimized graph.
282
283 In pseudocode, this looks like the following:
284
285 .. code:: python
286
287 def optimize(*collections, **kwargs):
288 # 1. Graph Merging & Optimization
289 # -------------------------------
290 # **Same as in compute**
291 graph = ...
292
293 # 2. Rebuilding
294 # -------------
295 # Rebuild each dask collection using the same large optimized graph
296 output = []
297 for collection in collections:
298 rebuild, extra_args = collection.__dask_postpersist__()
299 out = rebuild(graph, *extra_args)
300 output.append(out)
301
302 # dask.optimize always returns tuples
303 return tuple(output)
304
305
306 Visualize
307 ~~~~~~~~~
308
309 Visualize is the simplest of the 4 core functions. It only has two stages:
310
311 1. **Graph Merging & Optimization**
312
313 Same as in ``compute``.
314
315 2. **Graph Drawing**
316
317 The resulting merged graph is drawn using ``graphviz`` and outputs to the
318 specified file.
319
320 In pseudocode, this looks like the following:
321
322 .. code:: python
323
324 def visualize(*collections, **kwargs):
325 # 1. Graph Merging & Optimization
326 # -------------------------------
327 # **Same as in compute**
328 graph = ...
329
330 # 2. Graph Drawing
331 # ----------------
332 # Draw the graph with graphviz's `dot` tool and return the result.
333 return dot_graph(graph, **kwargs)
334
335
336 .. _adding-methods-to-class:
337
338 Adding the Core Dask Methods to Your Class
339 ------------------------------------------
340
341 Defining the above interface will allow your object to used by the core Dask
342 functions (``dask.compute``, ``dask.persist``, ``dask.visualize``, etc.). To
343 add corresponding method versions of these, you can subclass from
344 ``dask.base.DaskMethodsMixin`` which adds implementations of ``compute``,
345 ``persist``, and ``visualize`` based on the interface above.
346
347 .. _example-dask-collection:
348
349 Example Dask Collection
350 -----------------------
351
352 Here we create a Dask collection representing a tuple. Every element in the
353 tuple is represented as a task in the graph. Note that this is for illustration
354 purposes only - the same user experience could be done using normal tuples with
355 elements of ``dask.delayed``:
356
357 .. code:: python
358
359 # Saved as dask_tuple.py
360 import dask
361 from dask.base import DaskMethodsMixin, replace_name_in_key
362 from dask.optimization import cull
363
364 def tuple_optimize(dsk, keys, **kwargs):
365 # We cull unnecessary tasks here. See
366 # https://docs.dask.org/en/stable/optimize.html for more
367 # information on optimizations in Dask.
368 dsk2, _ = cull(dsk, keys)
369 return dsk2
370
371 # We subclass from DaskMethodsMixin to add common dask methods to
372 # our class (compute, persist, and visualize). This is nice but not
373 # necessary for creating a Dask collection (you can define them
374 # yourself).
375 class Tuple(DaskMethodsMixin):
376 def __init__(self, dsk, keys):
377 # The init method takes in a dask graph and a set of keys to use
378 # as outputs.
379 self._dsk = dsk
380 self._keys = keys
381
382 def __dask_graph__(self):
383 return self._dsk
384
385 def __dask_keys__(self):
386 return self._keys
387
388 # use the `tuple_optimize` function defined above
389 __dask_optimize__ = staticmethod(tuple_optimize)
390
391 # Use the threaded scheduler by default.
392 __dask_scheduler__ = staticmethod(dask.threaded.get)
393
394 def __dask_postcompute__(self):
395 # We want to return the results as a tuple, so our finalize
396 # function is `tuple`. There are no extra arguments, so we also
397 # return an empty tuple.
398 return tuple, ()
399
400 def __dask_postpersist__(self):
401 # We need to return a callable with the signature
402 # rebuild(dsk, *extra_args, rename: Mapping[str, str] = None)
403 return Tuple._rebuild, (self._keys,)
404
405 @staticmethod
406 def _rebuild(dsk, keys, *, rename=None):
407 if rename is not None:
408 keys = [replace_name_in_key(key, rename) for key in keys]
409 return Tuple(dsk, keys)
410
411 def __dask_tokenize__(self):
412 # For tokenize to work we want to return a value that fully
413 # represents this object. In this case it's the list of keys
414 # to be computed.
415 return self._keys
416
417 Demonstrating this class:
418
419 .. code:: python
420
421 >>> from dask_tuple import Tuple
422 >>> from operator import add, mul
423
424 # Define a dask graph
425 >>> dsk = {"k0": 1,
426 ... ("x", "k1"): 2,
427 ... ("x", 1): (add, "k0", ("x", "k1")),
428 ... ("x", 2): (mul, ("x", "k1"), 2),
429 ... ("x", 3): (add, ("x", "k1"), ("x", 1))}
430
431 # The output keys for this graph.
432 # The first element of each tuple must be the same across the whole collection;
433 # the remainder are arbitrary, unique str, bytes, int, or floats
434 >>> keys = [("x", "k1"), ("x", 1), ("x", 2), ("x", 3)]
435
436 >>> x = Tuple(dsk, keys)
437
438 # Compute turns Tuple into a tuple
439 >>> x.compute()
440 (2, 3, 4, 5)
441
442 # Persist turns Tuple into a Tuple, with each task already computed
443 >>> x2 = x.persist()
444 >>> isinstance(x2, Tuple)
445 True
446 >>> x2.__dask_graph__()
447 {('x', 'k1'): 2, ('x', 1): 3, ('x', 2): 4, ('x', 3): 5}
448 >>> x2.compute()
449 (2, 3, 4, 5)
450
451 # Run-time typechecking
452 >>> from dask.typing import DaskCollection
453 >>> isinstance(x, DaskCollection)
454 True
455
456
457 .. _is-dask-collection:
458
459 Checking if an object is a Dask collection
460 ------------------------------------------
461
462 To check if an object is a Dask collection, use
463 ``dask.base.is_dask_collection``:
464
465 .. code:: python
466
467 >>> from dask.base import is_dask_collection
468 >>> from dask import delayed
469
470 >>> x = delayed(sum)([1, 2, 3])
471 >>> is_dask_collection(x)
472 True
473 >>> is_dask_collection(1)
474 False
475
476
477 .. _deterministic-hashing:
478
479 Implementing Deterministic Hashing
480 ----------------------------------
481
482 Dask implements its own deterministic hash function to generate keys based on
483 the value of arguments. This function is available as ``dask.base.tokenize``.
484 Many common types already have implementations of ``tokenize``, which can be
485 found in ``dask/base.py``.
486
487 When creating your own custom classes, you may need to register a ``tokenize``
488 implementation. There are two ways to do this:
489
490 1. The ``__dask_tokenize__`` method
491
492 Where possible, it is recommended to define the ``__dask_tokenize__`` method.
493 This method takes no arguments and should return a value fully
494 representative of the object. It is a good idea to call ``dask.base.normalize_token``
495 from it before returning any non-trivial objects.
496
497 2. Register a function with ``dask.base.normalize_token``
498
499 If defining a method on the class isn't possible or you need to
500 customize the tokenize function for a class whose super-class is
501 already registered (for example if you need to sub-class built-ins),
502 you can register a tokenize function with the ``normalize_token``
503 dispatch. The function should have the same signature as described
504 above.
505
506 In both cases the implementation should be the same, where only the location of the
507 definition is different.
508
509 .. note:: Both Dask collections and normal Python objects can have
510 implementations of ``tokenize`` using either of the methods
511 described above.
512
513 Example
514 ~~~~~~~
515
516 .. code:: python
517
518 >>> from dask.base import tokenize, normalize_token
519
520 # Define a tokenize implementation using a method.
521 >>> class Point:
522 ... def __init__(self, x, y):
523 ... self.x = x
524 ... self.y = y
525 ...
526 ... def __dask_tokenize__(self):
527 ... # This tuple fully represents self
528 ... # Wrap non-trivial objects with normalize_token before returning them
529 ... return normalize_token(Point), self.x, self.y
530
531 >>> x = Point(1, 2)
532 >>> tokenize(x)
533 '5988362b6e07087db2bc8e7c1c8cc560'
534 >>> tokenize(x) == tokenize(x) # token is idempotent
535 True
536 >>> tokenize(Point(1, 2)) == tokenize(Point(1, 2)) # token is deterministic
537 True
538 >>> tokenize(Point(1, 2)) == tokenize(Point(2, 1)) # tokens are unique
539 False
540
541
542 # Register an implementation with normalize_token
543 >>> class Point3D:
544 ... def __init__(self, x, y, z):
545 ... self.x = x
546 ... self.y = y
547 ... self.z = z
548
549 >>> @normalize_token.register(Point3D)
550 ... def normalize_point3d(x):
551 ... return normalize_token(Point3D), x.x, x.y, x.z
552
553 >>> y = Point3D(1, 2, 3)
554 >>> tokenize(y)
555 '5a7e9c3645aa44cf13d021c14452152e'
556
557
558 For more examples, see ``dask/base.py`` or any of the built-in Dask collections.