Debian Codegraph @

dask/blockwise.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 from collections.abc import Hashable, Iterable, Mapping, Sequence
6 from dataclasses import fields, is_dataclass, replace
7 from itertools import product
8 from math import prod
9 from typing import Any
10
11 import tlz as toolz
12
13 import dask
14 from dask import base, utils
15 from dask._task_spec import Dict, GraphNode, List, Task, TaskRef, parse_input
16 from dask.base import clone_key, get_name_from_key, tokenize
17 from dask.core import flatten, ishashable, keys_in_tasks, reverse_dict
18 from dask.delayed import Delayed, finalize
19 from dask.highlevelgraph import HighLevelGraph, Layer
20 from dask.optimization import fuse
21 from dask.typing import Key
22 from dask.utils import _deprecated, ensure_dict, homogeneous_deepmap
23
24
25 class BlockwiseDep:
26 """Blockwise-IO argument
27
28 This is the base class for indexable Blockwise-IO arguments.
29 When constructing a ``Blockwise`` Layer, one or more of the
30 collection tuples passed in with ``indices`` may contain a
31 ``BlockwiseDep`` instance (in place of a "real" collection name).
32 This allows a new collection to be created (via IO) within a
33 ``Blockwise`` layer.
34
35 Parameters
36 ----------
37 numblocks: tuple[int, ...]
38 The number of blocks/partitions the object can support
39 along each dimension.
40 produces_tasks: bool
41 Whether any nested tasks will be passed to the Blockwise
42 function.
43
44 See Also
45 --------
46 dask.blockwise.Blockwise
47 dask.blockwise.BlockwiseDepDict
48 """
49
50 numblocks: tuple[int, ...]
51 produces_tasks: bool
52
53 def __getitem__(self, idx: tuple[int, ...]) -> Any:
54 """Return Blockwise-function arguments for a specific index"""
55 raise NotImplementedError(
56 "Must define `__getitem__` for `BlockwiseDep` subclass."
57 )
58
59 def get(self, idx: tuple[int, ...], default) -> Any:
60 """BlockwiseDep ``__getitem__`` Wrapper"""
61 try:
62 return self.__getitem__(idx)
63 except KeyError:
64 return default
65
66 @property
67 def produces_keys(self) -> bool:
68 """Whether this object will produce external key dependencies.
69
70 An external key corresponds to a task key or ``Delayed``-object
71 key that does not originate from within the ``Blockwise`` layer
72 that is including this ``BlockwiseDep`` object in its ``indices``.
73 A ``BlockwiseDep`` object should only return external-key
74 dependencies when those dependencies do not correspond to a
75 blockwise-compatible Dask collection (otherwise the collection
76 name should just be included in ``indices`` list instead).
77 """
78 return False
79
80 def __repr__(self) -> str:
81 return f"<{type(self).__name__} {self.numblocks}>"
82
83
84 class BlockwiseDepDict(BlockwiseDep):
85 """Dictionary-based Blockwise-IO argument
86
87 This is a dictionary-backed instance of ``BlockwiseDep``.
88 The purpose of this class is to simplify the construction
89 of IO-based Blockwise Layers with block/partition-dependent
90 function arguments that are difficult to calculate at
91 graph-materialization time.
92
93 Examples
94 --------
95
96 Specify an IO-based function for the Blockwise Layer. Note
97 that the function will be passed a single input object when
98 the task is executed (e.g. a single ``tuple`` or ``dict``):
99
100 >>> import pandas as pd
101 >>> func = lambda x: pd.read_csv(**x)
102
103 Use ``BlockwiseDepDict`` to define the input argument to
104 ``func`` for each block/partition:
105
106 >>> dep = BlockwiseDepDict(
107 ... mapping={
108 ... (0,) : {
109 ... "filepath_or_buffer": "data.csv",
110 ... "skiprows": 1,
111 ... "nrows": 2,
112 ... "names": ["a", "b"],
113 ... },
114 ... (1,) : {
115 ... "filepath_or_buffer": "data.csv",
116 ... "skiprows": 3,
117 ... "nrows": 2,
118 ... "names": ["a", "b"],
119 ... },
120 ... }
121 ... )
122
123 Construct a Blockwise Layer with ``dep`` specified
124 in the ``indices`` list:
125
126 >>> layer = Blockwise(
127 ... output="collection-name",
128 ... output_indices="i",
129 ... task=Task("collection-name", func, TaskRef("_0")),
130 ... indices=[(dep, "i")],
131 ... numblocks={},
132 ... )
133
134 See Also
135 --------
136 dask.blockwise.Blockwise
137 dask.blockwise.BlockwiseDep
138 """
139
140 def __init__(
141 self,
142 mapping: dict,
143 numblocks: tuple[int, ...] | None = None,
144 produces_tasks: bool = False,
145 produces_keys: bool = False,
146 ):
147 self.mapping = mapping
148 self.produces_tasks = produces_tasks
149
150 # By default, assume 1D shape
151 self.numblocks = numblocks or (len(mapping),)
152
153 # Whether `mapping` values are real task keys
154 # (e.g. Delayed objects)
155 self._produces_keys = produces_keys
156
157 @property
158 def produces_keys(self) -> bool:
159 return self._produces_keys
160
161 def __getitem__(self, idx: tuple[int, ...]) -> Any:
162 try:
163 return self.mapping[idx]
164 except KeyError as err:
165 # If a DataFrame collection was converted
166 # to an Array collection, the dimension of
167 # `idx` may not agree with the keys in
168 # `self.mapping`. In this case, we can
169 # use `self.numblocks` to check for a key
170 # match in the leading elements of `idx`
171 flat_idx = idx[: len(self.numblocks)]
172 if flat_idx in self.mapping:
173 return self.mapping[flat_idx]
174 raise err
175
176 def __len__(self) -> int:
177 return len(self.mapping)
178
179
180 class BlockIndex(BlockwiseDep):
181 """Index BlockwiseDep argument
182
183 The purpose of this class is to provide each
184 block of a ``Blockwise``-based operation with
185 the current block index.
186 """
187
188 produces_tasks: bool = False
189
190 def __init__(self, numblocks: tuple[int, ...]):
191 # NOTE: Unused - Just needs to be set to
192 # follow the `BlockwiseDep` interface
193 self.numblocks = numblocks
194
195 def __getitem__(self, idx: tuple[int, ...]) -> tuple[int, ...]:
196 return idx
197
198
199 def subs(task, substitution):
200 """Create a new task with the values substituted
201
202 This is like dask.core.subs, but takes a dict of many substitutions to
203 perform simultaneously. It is not as concerned with micro performance.
204 """
205 if isinstance(task, dict):
206 return {k: subs(v, substitution) for k, v in task.items()}
207 if type(task) in (tuple, list, set):
208 return type(task)([subs(x, substitution) for x in task])
209 try:
210 return substitution[task]
211 except (KeyError, TypeError):
212 return task
213
214
215 def index_subs(ind, substitution):
216 """A simple subs function that works both on tuples and strings"""
217 if ind is None:
218 return ind
219 else:
220 return tuple(substitution.get(c, c) for c in ind)
221
222
223 _BLOCKWISE_DEFAULT_PREFIX = "__dask_blockwise__"
224
225
226 def blockwise_token(i, prefix=_BLOCKWISE_DEFAULT_PREFIX):
227 return prefix + "%d" % i
228
229
230 def blockwise(
231 func,
232 output,
233 output_indices,
234 *arrind_pairs,
235 numblocks=None,
236 concatenate=None,
237 new_axes=None,
238 dependencies=(),
239 **kwargs,
240 ):
241 """Create a Blockwise symbolic mutable mapping
242
243 Applies a function, ``func``, across blocks from many different input
244 collections. We arrange the pattern with which those blocks interact with
245 sets of matching indices. E.g.::
246
247 blockwise(func, 'z', 'i', 'x', 'i', 'y', 'i')
248
249 yield an embarrassingly parallel communication pattern and is read as
250
251 $$ z_i = func(x_i, y_i) $$
252
253 More complex patterns may emerge, including multiple indices::
254
255 blockwise(func, 'z', 'ij', 'x', 'ij', 'y', 'ji')
256
257 $$ z_{ij} = func(x_{ij}, y_{ji}) $$
258
259 Indices missing in the output but present in the inputs results in many
260 inputs being sent to one function (see examples).
261
262 Examples
263 --------
264 Simple embarrassing map operation
265
266 >>> def inc(x):
267 ... return x + 1
268 >>> dict(
269 ... blockwise(
270 ... inc,
271 ... 'z', 'ij',
272 ... 'x', 'ij',
273 ... numblocks={'x': (2, 2)}
274 ... )
275 ... ) # doctest: +NORMALIZE_WHITESPACE
276 {('z', 0, 0): <Task ('z', 0, 0) inc(Alias(('x', 0, 0)))>,
277 ('z', 0, 1): <Task ('z', 0, 1) inc(Alias(('x', 0, 1)))>,
278 ('z', 1, 0): <Task ('z', 1, 0) inc(Alias(('x', 1, 0)))>,
279 ('z', 1, 1): <Task ('z', 1, 1) inc(Alias(('x', 1, 1)))>}
280
281 Simple operation on two datasets x and y
282
283 >>> def add(x, y):
284 ... return x + y
285 >>> dict(
286 ... blockwise(
287 ... add,
288 ... 'z', 'ij',
289 ... 'x', 'ij',
290 ... 'y', 'ij',
291 ... numblocks={'x': (2, 2), 'y': (2, 2)}
292 ... )
293 ... ) # doctest: +NORMALIZE_WHITESPACE
294 {('z', 0, 0): <Task ('z', 0, 0) add(Alias(('x', 0, 0)), Alias(('y', 0, 0)))>,
295 ('z', 0, 1): <Task ('z', 0, 1) add(Alias(('x', 0, 1)), Alias(('y', 0, 1)))>,
296 ('z', 1, 0): <Task ('z', 1, 0) add(Alias(('x', 1, 0)), Alias(('y', 1, 0)))>,
297 ('z', 1, 1): <Task ('z', 1, 1) add(Alias(('x', 1, 1)), Alias(('y', 1, 1)))>}
298
299 Operation that flips one of the datasets
300
301 >>> def addT(x, y):
302 ... return x + y.T
303 >>> dict(
304 ... blockwise(
305 ... addT,
306 ... 'z', 'ij',
307 ... 'x', 'ij',
308 ... 'y', 'ji',
309 ... numblocks={'x': (2, 2), 'y': (2, 2)}
310 ... )
311 ... ) # doctest: +NORMALIZE_WHITESPACE
312 {('z', 0, 0): <Task ('z', 0, 0) addT(Alias(('x', 0, 0)), Alias(('y', 0, 0)))>,
313 ('z', 0, 1): <Task ('z', 0, 1) addT(Alias(('x', 0, 1)), Alias(('y', 1, 0)))>,
314 ('z', 1, 0): <Task ('z', 1, 0) addT(Alias(('x', 1, 0)), Alias(('y', 0, 1)))>,
315 ('z', 1, 1): <Task ('z', 1, 1) addT(Alias(('x', 1, 1)), Alias(('y', 1, 1)))>}
316
317 Dot product with contraction over ``j`` index. Yields list arguments
318
319 >>> from dask.array.core import dotmany
320 >>> dict(
321 ... blockwise(
322 ... dotmany,
323 ... 'z', 'ik',
324 ... 'x', 'ij',
325 ... 'y', 'jk',
326 ... numblocks={'x': (2, 2), 'y': (2, 2)}
327 ... )
328 ... ) # doctest: +SKIP
329 {('z', 0, 0):
330 <Task ('z', 0, 0) dotmany(
331 List((Alias(('x', 0, 0)), Alias(('x', 0, 1)))),
332 List((Alias(('y', 0, 0)), Alias(('y', 1, 0)))))
333 >,
334 ('z', 0, 1):
335 <Task ('z', 0, 1) dotmany(
336 List((Alias(('x', 0, 0)), Alias(('x', 0, 1)))),
337 List((Alias(('y', 0, 1)), Alias(('y', 1, 1)))))
338 >,
339 ('z', 1, 0):
340 <Task ('z', 1, 0) dotmany(
341 List((Alias(('x', 1, 0)), Alias(('x', 1, 1)))),
342 List((Alias(('y', 0, 0)), Alias(('y', 1, 0)))))
343 >,
344 ('z', 1, 1):
345 <Task ('z', 1, 1) dotmany(
346 List((Alias(('x', 1, 0)), Alias(('x', 1, 1)))),
347 List((Alias(('y', 0, 1)), Alias(('y', 1, 1)))))
348 >
349 }
350
351 Pass ``concatenate=True`` to concatenate arrays ahead of time.
352 ``concatenate_axes`` is then called on the lists before the arguments are
353 passed to the function.
354
355 Supports Broadcasting rules
356
357 >>> dict(
358 ... blockwise(
359 ... add,
360 ... 'z', 'ij',
361 ... 'x', 'ij',
362 ... 'y', 'ij',
363 ... concatenate=True,
364 ... numblocks={'x': (1, 2), 'y': (2, 2)}
365 ... )
366 ... ) # doctest: +SKIP
367 {
368 ('z', 0, 0): <Task ('z', 0, 0) add(Alias(('x', 0, 0)), Alias(('y', 0, 0)))>,
369 ('z', 0, 1): <Task ('z', 0, 1) add(Alias(('x', 0, 1)), Alias(('y', 0, 1)))>,
370 ('z', 1, 0): <Task ('z', 1, 0) add(Alias(('x', 0, 0)), Alias(('y', 1, 0)))>,
371 ('z', 1, 1): <Task ('z', 1, 1) add(Alias(('x', 0, 1)), Alias(('y', 1, 1)))>
372 }
373
374 Include literals by indexing with ``None``
375
376 >>> dict(
377 ... blockwise(
378 ... add,
379 ... 'z', 'i',
380 ... 'x', 'i',
381 ... 100, None,
382 ... numblocks={'x': (2, )}
383 ... )
384 ... ) # doctest: +NORMALIZE_WHITESPACE
385 {('z', 0): <Task ('z', 0) add(Alias(('x', 0)), DataNode(100))>,
386 ('z', 1): <Task ('z', 1) add(Alias(('x', 1)), DataNode(100))>}
387
388 If the broadcasted value is a delayed object or other dask collection, the
389 key has to be wrapped appropriately as an Alias object.
390
391 >>> from dask import delayed
392 >>> from dask._task_spec import Alias
393 >>> delayed_inc = delayed(inc)(5, dask_key_name='dinc')
394 >>> dict(
395 ... blockwise(
396 ... add,
397 ... 'z', 'i',
398 ... 'x', 'i',
399 ... Alias(delayed_inc.key), None,
400 ... numblocks={'x': (2, )}
401 ... )
402 ... ) # doctest: +NORMALIZE_WHITESPACE
403 {('z', 0): <Task ('z', 0) add(Alias(('x', 0)), Alias('dinc'))>,
404 ('z', 1): <Task ('z', 1) add(Alias(('x', 1)), Alias('dinc'))>}
405
406 See Also
407 --------
408 dask.array.blockwise
409 Blockwise
410 """
411 new_axes = new_axes or {}
412
413 arrind_pairs = list(arrind_pairs)
414
415 # Transform indices to canonical elements
416 # We use terms like _0, and _1 rather than provided index elements
417 unique_indices = {
418 i for ii in arrind_pairs[1::2] if ii is not None for i in ii
419 } | set(output_indices)
420 sub = {k: blockwise_token(i, ".") for i, k in enumerate(sorted(unique_indices))}
421 output_indices = index_subs(tuple(output_indices), sub)
422 a_pairs_list = []
423 for a in arrind_pairs[1::2]:
424 if a is not None:
425 val = tuple(a)
426 else:
427 val = a
428 a_pairs_list.append(index_subs(val, sub))
429
430 arrind_pairs[1::2] = a_pairs_list
431 new_axes = {index_subs((k,), sub)[0]: v for k, v in new_axes.items()}
432
433 # Unpack dask values in non-array arguments
434 inputs = []
435 inputs_indices = []
436 for name, index in toolz.partition(2, arrind_pairs):
437 inputs.append(name)
438 inputs_indices.append(index)
439
440 task_args = list(map(TaskRef, map(blockwise_token, range(len(inputs)))))
441 # Unpack delayed objects in kwargs
442 new_keys = {n for c in dependencies for n in c.__dask_layers__()}
443 if kwargs:
444 # replace keys in kwargs with _0 tokens
445 new_tokens = tuple(
446 blockwise_token(i) for i in range(len(inputs), len(inputs) + len(new_keys))
447 )
448 sub = dict(zip(new_keys, new_tokens))
449 inputs.extend(map(TaskRef, new_keys))
450 inputs_indices.extend((None,) * len(new_keys))
451
452 indices = [(k, v) for k, v in zip(inputs, inputs_indices)]
453 task = Task(output, func, *task_args, **kwargs)
454 subgraph = Blockwise(
455 output,
456 output_indices,
457 task,
458 indices,
459 numblocks=numblocks,
460 concatenate=concatenate,
461 new_axes=new_axes,
462 )
463 return subgraph
464
465
466 class Blockwise(Layer):
467 """Tensor Operation
468
469 This is a lazily constructed mapping for tensor operation graphs.
470 This defines a dictionary using an operation and an indexing pattern.
471 It is built for many operations like elementwise, transpose, tensordot, and
472 so on. We choose to keep these as symbolic mappings rather than raw
473 dictionaries because we are able to fuse them during optimization,
474 sometimes resulting in much lower overhead.
475
476 Parameters
477 ----------
478 output: str
479 The name of the output collection. Used in keynames
480 output_indices: tuple
481 The output indices, like ``('i', 'j', 'k')`` used to determine the
482 structure of the block computations
483 dsk: dict
484 A small graph to apply per-output-block. May include keys from the
485 input indices.
486 indices: tuple[tuple[str, tuple[str, ...] | None], ...]
487 An ordered mapping from input key name, like ``'x'``
488 to input indices, like ``('i', 'j')``
489 Or includes literals, which have ``None`` for an index value.
490 In place of input-key names, the first tuple element may also be a
491 ``BlockwiseDep`` object.
492 numblocks: Mapping[key, Sequence[int]]
493 Number of blocks along each dimension for each input
494 concatenate: bool
495 Whether or not to pass contracted dimensions as a list of inputs or a
496 single input to the block function
497 new_axes: Mapping
498 New index dimensions that may have been created and their size,
499 e.g. ``{'j': 2, 'k': 3}``
500 output_blocks: set[tuple[int, ...]]
501 Specify a specific set of required output blocks. Since the graph
502 will only contain the necessary tasks to generate these outputs,
503 this kwarg can be used to "cull" the abstract layer (without needing
504 to materialize the low-level graph).
505 annotations: dict (optional)
506 Layer annotations
507 io_deps: dict[str, BlockwiseDep] (optional)
508 Dictionary containing the mapping between "place-holder" collection
509 keys and ``BlockwiseDep``-based objects.
510 **WARNING**: This argument should only be used internally (for culling,
511 fusion and cloning of existing Blockwise layers). Explicit use of this
512 argument will be deprecated in the future.
513
514 See Also
515 --------
516 dask.blockwise.blockwise
517 dask.array.blockwise
518 """
519
520 output: str
521 output_indices: tuple[str, ...]
522 task: Task
523 indices: tuple[tuple[str | TaskRef, tuple[str, ...] | None], ...]
524 numblocks: Mapping[str, Sequence[int]]
525 concatenate: bool | None
526 new_axes: Mapping[str, int]
527 output_blocks: set[tuple[int, ...]] | None
528 io_deps: Mapping[str, BlockwiseDep]
529
530 def __init__(
531 self,
532 output: str,
533 output_indices: Iterable[str],
534 task: Task,
535 indices: Iterable[tuple[str | TaskRef | BlockwiseDep, Iterable[str] | None]],
536 numblocks: Mapping[str, Sequence[int]],
537 concatenate: bool | None = None,
538 new_axes: Mapping[str, int] | None = None,
539 output_blocks: set[tuple[int, ...]] | None = None,
540 annotations: Mapping[str, Any] | None = None,
541 io_deps: Mapping[str, BlockwiseDep] | None = None,
542 ):
543 super().__init__(annotations=annotations)
544 self.output = output
545 self.output_indices = tuple(output_indices)
546 self.output_blocks = output_blocks
547 self.task = task
548 assert isinstance(task, Task)
549
550 # Remove `BlockwiseDep` arguments from input indices
551 # and add them to `self.io_deps`.
552 # TODO: Remove `io_deps` and handle indexable objects
553 # in `self.indices` throughout `Blockwise`.
554 _tmp_indices = []
555 numblocks = dict(numblocks)
556 io_deps = dict(io_deps or {})
557 if indices:
558 for dep, ind in indices:
559 if ind is not None:
560 # FIXME: The Blockwise API is a little weird this way
561 assert not isinstance(
562 dep, TaskRef
563 ), "TaskRef objects are only allowed for broadcasted inputs with None as index."
564 if isinstance(dep, BlockwiseDep):
565 name = tokenize(dep)
566 io_deps[name] = dep
567 numblocks[name] = dep.numblocks
568 else:
569 name = dep # type: ignore
570 _tmp_indices.append((name, tuple(ind) if ind is not None else ind))
571 self.numblocks = numblocks
572 self.io_deps = io_deps or {}
573 self.indices = tuple(_tmp_indices)
574
575 # optimize_blockwise won't merge where `concatenate` doesn't match, so
576 # enforce a canonical value if there are no axes for reduction.
577 output_indices_set = set(self.output_indices)
578 if concatenate is not None and all(
579 i in output_indices_set
580 for name, ind in self.indices
581 if ind is not None
582 for i in ind
583 ):
584 concatenate = None
585 self.concatenate = concatenate
586 self.new_axes = new_axes or {}
587
588 @property
589 def dims(self):
590 """Returns a dictionary mapping between each index specified in
591 `self.indices` and the number of output blocks for that indice.
592 """
593 if not hasattr(self, "_dims"):
594 self._dims = _make_dims(self.indices, self.numblocks, self.new_axes)
595 return self._dims
596
597 def __repr__(self):
598 return f"Blockwise<{self.indices} -> {self.output}>"
599
600 @property
601 def _dict(self):
602 if hasattr(self, "_cached_dict"):
603 return self._cached_dict["dsk"]
604 else:
605 keys = tuple(map(blockwise_token, range(len(self.indices))))
606
607 dsk = _make_blockwise_graph(
608 self.task,
609 self.output,
610 self.output_indices,
611 *list(toolz.concat(self.indices)),
612 new_axes=self.new_axes,
613 numblocks=self.numblocks,
614 concatenate=self.concatenate,
615 output_blocks=self.output_blocks,
616 dims=self.dims,
617 io_deps=self.io_deps,
618 keys=keys,
619 )
620
621 self._cached_dict = {"dsk": dsk}
622 return self._cached_dict["dsk"]
623
624 def get_output_keys(self):
625 if self.output_blocks:
626 # Culling has already generated a list of output blocks
627 return {(self.output, *p) for p in self.output_blocks}
628
629 # Return all possible output keys (no culling)
630 return {
631 (self.output, *p)
632 for p in itertools.product(
633 *[range(self.dims[i]) for i in self.output_indices]
634 )
635 }
636
637 def __getitem__(self, key):
638 return self._dict[key]
639
640 def __iter__(self):
641 return iter(self._dict)
642
643 def __len__(self) -> int:
644 # same method as `get_output_keys`, without manifesting the keys themselves
645 return (
646 len(self.output_blocks)
647 if self.output_blocks
648 else prod(self.dims[i] for i in self.output_indices)
649 )
650
651 def is_materialized(self):
652 return hasattr(self, "_cached_dict")
653
654 def _cull_dependencies(self, all_hlg_keys, output_blocks):
655 """Determine the necessary dependencies to produce `output_blocks`.
656
657 This method does not require graph materialization.
658 """
659
660 # Check `concatenate` option
661 concatenate = None
662 if self.concatenate is True:
663 from dask.array.core import concatenate_axes as concatenate
664
665 # Generate coordinate map
666 (coord_maps, concat_axes, dummies) = _get_coord_mapping(
667 self.dims,
668 self.output_indices,
669 self.numblocks,
670 self.indices,
671 concatenate,
672 )
673
674 # Gather constant dependencies (for all output keys)
675 const_deps = set()
676 for arg, ind in self.indices:
677 if isinstance(arg, TaskRef):
678 arg = arg.key
679 if ind is None:
680 try:
681 if arg in all_hlg_keys:
682 const_deps.add(arg)
683 except TypeError:
684 pass # unhashable
685
686 # Get dependencies for each output block
687 key_deps = {}
688 for out_coords in output_blocks:
689 deps = set()
690 coords = out_coords + dummies
691 for cmap, axes, (arg, ind) in zip(coord_maps, concat_axes, self.indices):
692 if ind is not None and arg not in self.io_deps:
693 arg_coords = tuple(coords[c] for c in cmap)
694 if axes:
695 tups = _lol_product((arg,), arg_coords)
696 deps.update(flatten(tups))
697 if concatenate:
698 tups = (concatenate, tups, axes)
699 else:
700 tups = (arg,) + arg_coords
701 deps.add(tups)
702 key_deps[(self.output,) + out_coords] = deps | const_deps
703
704 # Add valid-key dependencies from io_deps
705 for key, io_dep in self.io_deps.items():
706 if io_dep.produces_keys:
707 for out_coords in output_blocks:
708 key = (self.output,) + out_coords
709 valid_key_dep = io_dep[out_coords]
710 if isinstance(valid_key_dep, TaskRef):
711 valid_key_dep = valid_key_dep.key
712 key_deps[key] |= {valid_key_dep}
713
714 return key_deps
715
716 def _cull(self, output_blocks):
717 return Blockwise(
718 self.output,
719 self.output_indices,
720 self.task,
721 self.indices,
722 self.numblocks,
723 concatenate=self.concatenate,
724 new_axes=self.new_axes,
725 output_blocks=output_blocks,
726 annotations=self.annotations,
727 io_deps=self.io_deps,
728 )
729
730 def cull(
731 self, keys: set, all_hlg_keys: Iterable
732 ) -> tuple[Layer, Mapping[Key, set[Key]]]:
733 # Culling is simple for Blockwise layers. We can just
734 # collect a set of required output blocks (tuples), and
735 # only construct graph for these blocks in `make_blockwise_graph`
736
737 output_blocks: set[tuple[int, ...]] = set()
738 for key in keys:
739 if key[0] == self.output:
740 output_blocks.add(key[1:])
741 culled_deps = self._cull_dependencies(all_hlg_keys, output_blocks)
742 out_size_iter = (self.dims[i] for i in self.output_indices)
743 if prod(out_size_iter) != len(culled_deps):
744 culled_layer = self._cull(output_blocks)
745 return culled_layer, culled_deps
746 else:
747 return self, culled_deps
748
749 def clone(
750 self,
751 keys: set[Key],
752 seed: Hashable,
753 bind_to: Key | None = None,
754 ) -> tuple[Layer, bool]:
755 names = {get_name_from_key(k) for k in keys}
756 # We assume that 'keys' will contain either all or none of the output keys of
757 # each of the layers, because clone/bind are always invoked at collection level.
758 # Asserting this is very expensive, so we only check it during unit tests.
759 if "PYTEST_CURRENT_TEST" in os.environ:
760 assert not self.get_output_keys() - keys
761 for name, nb in self.numblocks.items():
762 if name in names:
763 for block in product(*(list(range(nbi)) for nbi in nb)):
764 assert (name, *block) in keys
765
766 is_leaf = True
767
768 indices = []
769 k: Key | TaskRef
770 for k, idxv in self.indices:
771 # Note: k may not be a key and thus not be hashable in the case where
772 # one or more args of blockwise() are sequences of literals;
773 # e.g. k = (list, [0, 1, 2])
774 # See https://github.com/dask/dask/issues/8978
775
776 if ishashable(k) and k in names:
777 is_leaf = False
778 k = clone_key(k, seed) # type: ignore
779 elif isinstance(k, TaskRef) and k.key in names:
780 is_leaf = False
781 k = TaskRef(clone_key(k.key, seed))
782
783 indices.append((k, idxv))
784
785 numblocks: dict[str, Sequence[int]] = {}
786 for k, nbv in self.numblocks.items():
787 if k in names:
788 is_leaf = False
789 k = clone_key(k, seed)
790 numblocks[k] = nbv
791
792 if bind_to is not None and is_leaf:
793 from dask.graph_manipulation import chunks
794
795 # It's always a Delayed generated by dask.graph_manipulation.checkpoint;
796 # the layer name always matches the key
797 assert isinstance(bind_to, str)
798 newtask = Task(
799 clone_key(self.task.key, seed),
800 chunks.bind,
801 self.task,
802 TaskRef(blockwise_token(len(indices))),
803 )
804 indices.append((TaskRef(bind_to), None))
805 else:
806 newtask = self.task.substitute({}, key=clone_key(self.task.key, seed))
807
808 return (
809 Blockwise(
810 output=clone_key(self.output, seed),
811 output_indices=self.output_indices,
812 task=newtask,
813 indices=indices,
814 numblocks=numblocks,
815 concatenate=self.concatenate,
816 new_axes=self.new_axes,
817 output_blocks=self.output_blocks,
818 annotations=self.annotations,
819 io_deps=self.io_deps,
820 ),
821 (bind_to is not None and is_leaf),
822 )
823
824
825 def _get_coord_mapping(
826 dims,
827 out_indices,
828 numblocks,
829 argpairs,
830 concatenate,
831 ):
832 """Calculate coordinate mapping for graph construction.
833
834 This function handles the high-level logic behind Blockwise graph
835 construction. The output is a tuple containing: The mapping between
836 input and output block coordinates (`coord_maps`), the axes along
837 which to concatenate for each input (`concat_axes`), and the dummy
838 indices needed for broadcasting (`dummies`).
839
840 Used by `make_blockwise_graph` and `Blockwise._cull_dependencies`.
841
842 Parameters
843 ----------
844 dims : dict
845 Mapping between each index specified in `argpairs` and
846 the number of output blocks for that index. Corresponds
847 to the Blockwise `dims` attribute.
848 out_indices : tuple
849 Corresponds to the Blockwise `output_indices` attribute.
850 numblocks : dict
851 Corresponds to the Blockwise `numblocks` attribute.
852 argpairs : tuple
853 Corresponds to the Blockwise `indices` attribute.
854 concatenate : bool
855 Corresponds to the Blockwise `concatenate` attribute.
856 """
857
858 block_names = set()
859 all_indices = set()
860 for name, ind in argpairs:
861 if ind is not None:
862 block_names.add(name)
863 for x in ind:
864 all_indices.add(x)
865 assert set(numblocks) == block_names, (numblocks, block_names)
866
867 dummy_indices = all_indices - set(out_indices)
868
869 # For each position in the output space, we'll construct a
870 # "coordinate set" that consists of
871 # - the output indices
872 # - the dummy indices
873 # - the dummy indices, with indices replaced by zeros (for broadcasting), we
874 # are careful to only emit a single dummy zero when concatenate=True to not
875 # concatenate the same array with itself several times.
876 # - a 0 to assist with broadcasting.
877
878 index_pos, zero_pos = {}, {}
879 for i, ind in enumerate(out_indices):
880 index_pos[ind] = i
881 zero_pos[ind] = -1
882
883 _dummies_list = []
884 for i, ind in enumerate(dummy_indices):
885 index_pos[ind] = 2 * i + len(out_indices)
886 zero_pos[ind] = 2 * i + 1 + len(out_indices)
887 reps = 1 if concatenate else dims[ind]
888 _dummies_list.append([list(range(dims[ind])), [0] * reps])
889
890 # ([0, 1, 2], [0, 0, 0], ...) For a dummy index of dimension 3
891 dummies = tuple(itertools.chain.from_iterable(_dummies_list))
892 dummies += (0,)
893
894 # For each coordinate position in each input, gives the position in
895 # the coordinate set.
896 coord_maps = []
897
898 # Axes along which to concatenate, for each input
899 concat_axes = []
900 for arg, ind in argpairs:
901 if ind is not None:
902 coord_maps.append(
903 [
904 zero_pos[i] if nb == 1 else index_pos[i]
905 for i, nb in zip(ind, numblocks[arg])
906 ]
907 )
908 concat_axes.append([n for n, i in enumerate(ind) if i in dummy_indices])
909 else:
910 coord_maps.append(None)
911 concat_axes.append(None)
912
913 return coord_maps, concat_axes, dummies
914
915
916 def _make_blockwise_graph(
917 task,
918 output,
919 out_indices,
920 *arrind_pairs,
921 numblocks=None,
922 concatenate=None,
923 new_axes=None,
924 output_blocks=None,
925 dims=None,
926 io_deps=None,
927 keys=None,
928 ):
929 if numblocks is None:
930 raise ValueError("Missing required numblocks argument.")
931 new_axes = new_axes or {}
932 io_deps = io_deps or {}
933 argpairs = list(toolz.partition(2, arrind_pairs))
934
935 if concatenate is True:
936 from dask.array.core import concatenate_axes as concatenate
937
938 # Dictionary mapping {i: 3, j: 4, ...} for i, j, ... the dimensions
939 dims = dims or _make_dims(argpairs, numblocks, new_axes)
940
941 # Generate the abstract "plan" before constructing
942 # the actual graph
943 (coord_maps, concat_axes, dummies) = _get_coord_mapping(
944 dims,
945 out_indices,
946 numblocks,
947 argpairs,
948 concatenate,
949 )
950
951 # Apply Culling.
952 # Only need to construct the specified set of output blocks.
953 # Note that we must convert itertools.product to list,
954 # because we may need to loop through output_blocks more than
955 # once below (itertools.product already uses an internal list,
956 # so this is not a memory regression)
957 output_blocks = output_blocks or list(
958 itertools.product(*[range(dims[i]) for i in out_indices])
959 )
960 from dask._task_spec import DataNode
961
962 dsk = {}
963 for out_coords in output_blocks:
964 this_task = task
965 coords = out_coords + dummies
966 args = []
967 for cmap, axes, (arg, ind), key in zip(
968 coord_maps, concat_axes, argpairs, keys, strict=True
969 ):
970 if key not in task.dependencies:
971 # FIXME: This feels like a bug
972 continue
973 if ind is None:
974 if not isinstance(arg, (GraphNode, TaskRef)):
975 this_task = this_task.substitute({key: DataNode(None, arg)})
976 else:
977 this_task = this_task.substitute({key: arg})
978 continue
979 arg_coords = tuple(coords[c] for c in cmap)
980 if arg in io_deps:
981 val = parse_input(io_deps[arg].get(arg_coords, arg_coords))
982 if not isinstance(val, GraphNode):
983 val = DataNode(None, val)
984 this_task = this_task.substitute({key: val})
985 else:
986 subs = {}
987 if axes:
988 tups = _lol_product((arg,), arg_coords, as_taskref=True)
989 if concatenate:
990 tups = Task(key, concatenate, tups, axes)
991 subs[key] = tups
992 else:
993 subs[key] = (arg, *arg_coords)
994 this_task = this_task.substitute(subs)
995 new_key = (output,) + out_coords
996 assert isinstance(this_task, Task)
997 dsk[new_key] = Task.fuse(this_task, *args, key=new_key)
998 return dsk
999
1000
1001 def _lol_product(head, values, as_taskref=False):
1002 """List of list of tuple keys, similar to `itertools.product`.
1003
1004 Parameters
1005 ----------
1006 head : tuple
1007 Prefix prepended to all results.
1008 values : sequence
1009 Mix of singletons and lists. Each list is substituted with every
1010 possible value and introduces another level of list in the output.
1011
1012 Examples
1013 --------
1014 >>> _lol_product(('x',), (1, 2, 3))
1015 ('x', 1, 2, 3)
1016 >>> _lol_product(('x',), (1, [2, 3], 4, [5, 6])) # doctest: +NORMALIZE_WHITESPACE
1017 [[('x', 1, 2, 4, 5), ('x', 1, 2, 4, 6)],
1018 [('x', 1, 3, 4, 5), ('x', 1, 3, 4, 6)]]
1019 """
1020 if not values:
1021 if as_taskref:
1022 return TaskRef(head)
1023 return head
1024 elif isinstance(values[0], list):
1025 # FIXME: Constructor of List is odd
1026 if as_taskref:
1027 return List(
1028 *(
1029 _lol_product(head + (x,), values[1:], as_taskref=as_taskref)
1030 for x in values[0]
1031 )
1032 )
1033 else:
1034 return list(
1035 _lol_product(head + (x,), values[1:], as_taskref=as_taskref)
1036 for x in values[0]
1037 )
1038 else:
1039 return _lol_product(head + (values[0],), values[1:], as_taskref=as_taskref)
1040
1041
1042 def lol_tuples(head, ind, values, dummies):
1043 """List of list of tuple keys
1044
1045 Parameters
1046 ----------
1047 head : tuple
1048 The known tuple so far
1049 ind : Iterable
1050 An iterable of indices not yet covered
1051 values : dict
1052 Known values for non-dummy indices
1053 dummies : dict
1054 Ranges of values for dummy indices
1055
1056 Examples
1057 --------
1058 >>> lol_tuples(('x',), 'ij', {'i': 1, 'j': 0}, {})
1059 ('x', 1, 0)
1060
1061 >>> lol_tuples(('x',), 'ij', {'i': 1}, {'j': range(3)})
1062 [('x', 1, 0), ('x', 1, 1), ('x', 1, 2)]
1063
1064 >>> lol_tuples(('x',), 'ijk', {'i': 1}, {'j': [0, 1, 2], 'k': [0, 1]}) # doctest: +NORMALIZE_WHITESPACE
1065 [[('x', 1, 0, 0), ('x', 1, 0, 1)],
1066 [('x', 1, 1, 0), ('x', 1, 1, 1)],
1067 [('x', 1, 2, 0), ('x', 1, 2, 1)]]
1068 """
1069 if not ind:
1070 return head
1071 if ind[0] not in dummies:
1072 return lol_tuples(head + (values[ind[0]],), ind[1:], values, dummies)
1073 else:
1074 return [
1075 lol_tuples(head + (v,), ind[1:], values, dummies) for v in dummies[ind[0]]
1076 ]
1077
1078
1079 def optimize_blockwise(graph, keys=()):
1080 """High level optimization of stacked Blockwise layers
1081
1082 For operations that have multiple Blockwise operations one after the other, like
1083 ``x.T + 123`` we can fuse these into a single Blockwise operation. This happens
1084 before any actual tasks are generated, and so can reduce overhead.
1085
1086 This finds groups of Blockwise operations that can be safely fused, and then
1087 passes them to ``rewrite_blockwise`` for rewriting.
1088
1089 Parameters
1090 ----------
1091 graph : HighLevelGraph
1092 keys : Iterable
1093 The keys of all outputs of all collections.
1094 Used to make sure that we don't fuse a layer needed by an output
1095
1096 Returns
1097 -------
1098 HighLevelGraph
1099
1100 See Also
1101 --------
1102 rewrite_blockwise
1103 """
1104 out = _optimize_blockwise(graph, keys=keys)
1105 while out.dependencies != graph.dependencies:
1106 graph = out
1107 out = _optimize_blockwise(graph, keys=keys)
1108 return out
1109
1110
1111 def _optimize_blockwise(full_graph, keys=()):
1112 keep = {k[0] if type(k) is tuple else k for k in keys}
1113 layers = full_graph.layers
1114 dependents = reverse_dict(full_graph.dependencies)
1115 roots = {k for k in full_graph.layers if not dependents.get(k)}
1116 stack = list(roots)
1117
1118 out = {}
1119 dependencies = {}
1120 seen = set()
1121 io_names = set()
1122
1123 while stack:
1124 layer = stack.pop()
1125 if layer in seen or layer not in layers:
1126 continue
1127 seen.add(layer)
1128
1129 # Outer loop walks through possible output Blockwise layers
1130 if isinstance(layers[layer], Blockwise):
1131 blockwise_layers = {layer}
1132 deps = set(blockwise_layers)
1133 io_names |= layers[layer].io_deps.keys()
1134 while deps: # we gather as many sub-layers as we can
1135 dep = deps.pop()
1136
1137 if dep not in layers:
1138 stack.append(dep)
1139 continue
1140 if not isinstance(layers[dep], Blockwise):
1141 stack.append(dep)
1142 continue
1143 if dep != layer and dep in keep:
1144 stack.append(dep)
1145 continue
1146 if layers[dep].concatenate != layers[layer].concatenate:
1147 stack.append(dep)
1148 continue
1149 if (
1150 sum(k == dep for k, ind in layers[layer].indices if ind is not None)
1151 > 1
1152 ):
1153 stack.append(dep)
1154 continue
1155 if blockwise_layers and not _can_fuse_annotations(
1156 layers[next(iter(blockwise_layers))].annotations,
1157 layers[dep].annotations,
1158 ):
1159 stack.append(dep)
1160 continue
1161
1162 # passed everything, proceed
1163 blockwise_layers.add(dep)
1164
1165 # traverse further to this child's children
1166 output_indices = set(layers[dep].output_indices)
1167 input_indices = {
1168 i for _, ind in layers[dep].indices if ind for i in ind
1169 }
1170 is_io_superset = output_indices.issuperset(input_indices)
1171 for d in full_graph.dependencies.get(dep, ()):
1172 # Don't allow reductions to proceed
1173 if is_io_superset and len(dependents[d]) <= 1:
1174 deps.add(d)
1175 else:
1176 stack.append(d)
1177
1178 # Merge these Blockwise layers into one
1179 new_layer = rewrite_blockwise([layers[l] for l in blockwise_layers])
1180 out[layer] = new_layer
1181
1182 # Get the new (external) dependencies for this layer.
1183 # This corresponds to the dependencies defined in
1184 # full_graph.dependencies and are not in blockwise_layers
1185 new_deps = set()
1186 for l in blockwise_layers:
1187 new_deps |= set(
1188 {
1189 d
1190 for d in full_graph.dependencies[l]
1191 if d not in blockwise_layers and d in full_graph.dependencies
1192 }
1193 )
1194 for k, v in new_layer.indices:
1195 if v is None:
1196 new_deps |= keys_in_tasks(full_graph.dependencies, [k])
1197 elif k not in io_names:
1198 new_deps.add(k)
1199 dependencies[layer] = new_deps
1200 else:
1201 out[layer] = layers[layer]
1202 dependencies[layer] = full_graph.dependencies.get(layer, set())
1203 stack.extend(full_graph.dependencies.get(layer, ()))
1204
1205 return HighLevelGraph(out, dependencies)
1206
1207
1208 def _unique_dep(dep, ind):
1209 # Append blockwise index information to dependency name
1210 return dep + "_" + "_".join(str(i) for i in list(ind))
1211
1212
1213 def _can_fuse_annotations(a: dict | None, b: dict | None) -> bool:
1214 """
1215 Treat the special annotation keys, as fusable since we can apply simple
1216 rules to capture their intent in a fused layer.
1217 """
1218 if a == b:
1219 return True
1220
1221 if dask.config.get("optimization.annotations.fuse") is False:
1222 return False
1223
1224 fusable = {"retries", "priority", "resources", "workers", "allow_other_workers"}
1225 if (not a or all(k in fusable for k in a)) and (
1226 not b or all(k in fusable for k in b)
1227 ):
1228 return True
1229
1230 return False
1231
1232
1233 def _fuse_annotations(*args: dict) -> dict:
1234 """
1235 Given an iterable of annotations dictionaries, fuse them according
1236 to some simple rules.
1237 """
1238 # First, do a basic dict merge -- we are presuming that these have already
1239 # been gated by `_can_fuse_annotations`.
1240 annotations = toolz.merge(*args)
1241 # Max of layer retries
1242 retries = [a["retries"] for a in args if "retries" in a]
1243 if retries:
1244 annotations["retries"] = max(retries)
1245 # Max of layer priorities
1246 priorities = [a["priority"] for a in args if "priority" in a]
1247 if priorities:
1248 annotations["priority"] = max(priorities)
1249 # Max of all the layer resources
1250 resources = [a["resources"] for a in args if "resources" in a]
1251 if resources:
1252 annotations["resources"] = toolz.merge_with(max, *resources)
1253 # Intersection of all the worker restrictions
1254 workers = [a["workers"] for a in args if "workers" in a]
1255 if workers:
1256 annotations["workers"] = list(set.intersection(*[set(w) for w in workers]))
1257 # More restrictive of allow_other_workers
1258 allow_other_workers = [
1259 a["allow_other_workers"] for a in args if "allow_other_workers" in a
1260 ]
1261 if allow_other_workers:
1262 annotations["allow_other_workers"] = all(allow_other_workers)
1263
1264 return annotations
1265
1266
1267 def rewrite_blockwise(inputs):
1268 """Rewrite a stack of Blockwise expressions into a single blockwise expression
1269
1270 Given a set of Blockwise layers, combine them into a single layer. The provided
1271 layers are expected to fit well together. That job is handled by
1272 ``optimize_blockwise``
1273
1274 Parameters
1275 ----------
1276 inputs : list[Blockwise]
1277
1278 Returns
1279 -------
1280 blockwise: Blockwise
1281
1282 See Also
1283 --------
1284 optimize_blockwise
1285 """
1286 if len(inputs) == 1:
1287 # Fast path: if there's only one input we can just use it as-is.
1288 return inputs[0]
1289
1290 fused_annotations = _fuse_annotations(
1291 *[i.annotations for i in inputs if i.annotations]
1292 )
1293 inputs = {inp.output: inp for inp in inputs}
1294 dependencies = {
1295 inp.output: {d for d, v in inp.indices if v is not None and d in inputs}
1296 for inp in inputs.values()
1297 }
1298 dependents = reverse_dict(dependencies)
1299
1300 new_index_iter = (
1301 c + (str(d) if d else "") # A, B, ... A1, B1, ...
1302 for d in itertools.count()
1303 for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1304 )
1305
1306 [root] = [k for k, v in dependents.items() if not v]
1307
1308 # Our final results. These will change during fusion below
1309 indices = list(inputs[root].indices)
1310 new_axes = inputs[root].new_axes
1311 concatenate = inputs[root].concatenate
1312 task = inputs[root].task
1313 dsk = {task.key: task}
1314
1315 changed = True
1316 while changed:
1317 changed = False
1318 for i, (dep, current_dep_indices) in enumerate(indices):
1319 if current_dep_indices is None:
1320 continue
1321 if dep not in inputs:
1322 continue
1323
1324 changed = True
1325
1326 # Change dep name to avoid fusing the same dep
1327 # (in different iteration orders) into a single
1328 # subgraph key/dependency
1329 # (see: https://github.com/dask/dask/issues/8535)
1330 local_dep = dep if dep == root else _unique_dep(dep, current_dep_indices)
1331
1332 # Replace _n with dep name in existing tasks
1333 # (inc, _0) -> (inc, 'b')
1334 dsk = {
1335 k: v.substitute({blockwise_token(i): local_dep}) for k, v in dsk.items()
1336 }
1337
1338 # Remove current input from input indices
1339 # [('a', 'i'), ('b', 'i')] -> [('a', 'i')]
1340 indices.pop(i)
1341
1342 sub = {
1343 blockwise_token(i): blockwise_token(i - 1)
1344 for i in range(i + 1, len(indices) + 1)
1345 }
1346 dsk = {k: v.substitute(sub) for k, v in dsk.items()}
1347
1348 # Change new input_indices to match give index from current computation
1349 # [('c', j')] -> [('c', 'i')]
1350 new_indices = inputs[dep].indices
1351 sub = dict(zip(inputs[dep].output_indices, current_dep_indices))
1352 contracted = {
1353 x
1354 for _, j in new_indices
1355 if j is not None
1356 for x in j
1357 if x not in inputs[dep].output_indices
1358 }
1359 extra = dict(zip(contracted, new_index_iter))
1360 sub.update(extra)
1361 new_indices = [(x, index_subs(j, sub)) for x, j in new_indices]
1362
1363 # Update new_axes
1364 for k, v in inputs[dep].new_axes.items():
1365 new_axes[sub[k]] = v
1366
1367 # Bump new inputs up in list
1368 sub = {}
1369 # Map from (id(key), inds or None) -> index in indices. Used to deduplicate indices.
1370 index_map = {(id(k), inds): n for n, (k, inds) in enumerate(indices)}
1371 for ii, index in enumerate(new_indices):
1372 id_key = (id(index[0]), index[1])
1373 if id_key in index_map: # use old inputs if available
1374 sub[blockwise_token(ii)] = blockwise_token(index_map[id_key])
1375 else:
1376 index_map[id_key] = len(indices)
1377 sub[blockwise_token(ii)] = blockwise_token(len(indices))
1378 indices.append(index)
1379 if dep != local_dep:
1380 key = local_dep
1381 else:
1382 key = dep
1383 new_dsk = {key: inputs[dep].task.substitute(sub, key=key)}
1384
1385 # indices.extend(new_indices)
1386 dsk.update(new_dsk)
1387
1388 # De-duplicate indices like [(a, ij), (b, i), (a, ij)] -> [(a, ij), (b, i)]
1389 # Make sure that we map everything else appropriately as we remove inputs
1390 new_indices = []
1391 seen = {}
1392 sub = {} # like {_0: _0, _1: _0, _2: _1}
1393 for i, x in enumerate(indices):
1394 if x[1] is not None and x in seen:
1395 sub[i] = seen[x]
1396 else:
1397 if x[1] is not None:
1398 seen[x] = len(new_indices)
1399 sub[i] = len(new_indices)
1400 new_indices.append(x)
1401
1402 sub = {blockwise_token(k): blockwise_token(v) for k, v in sub.items()}
1403 dsk = {k: v.substitute(sub) for k, v in dsk.items() if k not in sub.keys()}
1404 task = Task.fuse(*dsk.values(), key=root)
1405 indices_check = {k for k, v in indices if v is not None}
1406 numblocks = toolz.merge([inp.numblocks for inp in inputs.values()])
1407 numblocks = {k: v for k, v in numblocks.items() if v is None or k in indices_check}
1408
1409 # Update IO-dependency information
1410 io_deps = {}
1411 for v in inputs.values():
1412 io_deps.update(v.io_deps)
1413
1414 return Blockwise(
1415 root,
1416 inputs[root].output_indices,
1417 task,
1418 new_indices,
1419 numblocks=numblocks,
1420 new_axes=new_axes,
1421 concatenate=concatenate,
1422 annotations=fused_annotations,
1423 io_deps=io_deps,
1424 )
1425
1426
1427 @_deprecated()
1428 def zero_broadcast_dimensions(lol, nblocks):
1429 """
1430 >>> lol = [('x', 1, 0), ('x', 1, 1), ('x', 1, 2)]
1431 >>> nblocks = (4, 1, 2) # note singleton dimension in second place
1432 >>> lol = [[('x', 1, 0, 0), ('x', 1, 0, 1)],
1433 ... [('x', 1, 1, 0), ('x', 1, 1, 1)],
1434 ... [('x', 1, 2, 0), ('x', 1, 2, 1)]]
1435
1436 >>> zero_broadcast_dimensions(lol, nblocks) # doctest: +SKIP
1437 [[('x', 1, 0, 0), ('x', 1, 0, 1)],
1438 [('x', 1, 0, 0), ('x', 1, 0, 1)],
1439 [('x', 1, 0, 0), ('x', 1, 0, 1)]]
1440
1441 See Also
1442 --------
1443 lol_tuples
1444 """
1445 f = lambda t: (t[0],) + tuple(0 if d == 1 else i for i, d in zip(t[1:], nblocks))
1446 return homogeneous_deepmap(f, lol)
1447
1448
1449 def broadcast_dimensions(argpairs, numblocks, sentinels=(1, (1,)), consolidate=None):
1450 """Find block dimensions from arguments
1451
1452 Parameters
1453 ----------
1454 argpairs : iterable
1455 name, ijk index pairs
1456 numblocks : dict
1457 maps {name: number of blocks}
1458 sentinels : iterable (optional)
1459 values for singleton dimensions
1460 consolidate : func (optional)
1461 use this to reduce each set of common blocks into a smaller set
1462
1463 Examples
1464 --------
1465 >>> argpairs = [('x', 'ij'), ('y', 'ji')]
1466 >>> numblocks = {'x': (2, 3), 'y': (3, 2)}
1467 >>> broadcast_dimensions(argpairs, numblocks)
1468 {'i': 2, 'j': 3}
1469
1470 Supports numpy broadcasting rules
1471
1472 >>> argpairs = [('x', 'ij'), ('y', 'ij')]
1473 >>> numblocks = {'x': (2, 1), 'y': (1, 3)}
1474 >>> broadcast_dimensions(argpairs, numblocks)
1475 {'i': 2, 'j': 3}
1476
1477 Works in other contexts too
1478
1479 >>> argpairs = [('x', 'ij'), ('y', 'ij')]
1480 >>> d = {'x': ('Hello', 1), 'y': (1, (2, 3))}
1481 >>> broadcast_dimensions(argpairs, d)
1482 {'i': 'Hello', 'j': (2, 3)}
1483 """
1484 # List like [('i', 2), ('j', 1), ('i', 1), ('j', 2)]
1485 argpairs2 = [(a, ind) for a, ind in argpairs if ind is not None]
1486 L = toolz.concat(
1487 [
1488 zip(inds, dims)
1489 for (x, inds), (x, dims) in toolz.join(
1490 toolz.first, argpairs2, toolz.first, numblocks.items()
1491 )
1492 ]
1493 )
1494
1495 g = toolz.groupby(0, L)
1496 g = {k: {d for i, d in v} for k, v in g.items()}
1497
1498 g2 = {k: v - set(sentinels) if len(v) > 1 else v for k, v in g.items()}
1499
1500 if consolidate:
1501 return toolz.valmap(consolidate, g2)
1502
1503 if g2 and not set(map(len, g2.values())) == {1}:
1504 raise ValueError("Shapes do not align %s" % g)
1505
1506 return toolz.valmap(toolz.first, g2)
1507
1508
1509 def _make_dims(indices, numblocks, new_axes):
1510 """Returns a dictionary mapping between each index specified in
1511 `indices` and the number of output blocks for that indice.
1512 """
1513 dims = broadcast_dimensions(indices, numblocks)
1514 for k, v in new_axes.items():
1515 dims[k] = len(v) if isinstance(v, tuple) else 1
1516 return dims
1517
1518
1519 def fuse_roots(graph: HighLevelGraph, keys: list):
1520 """
1521 Fuse nearby layers if they don't have dependencies
1522
1523 Often Blockwise sections of the graph fill out all of the computation
1524 except for the initial data access or data loading layers::
1525
1526 Large Blockwise Layer
1527 | | |
1528 X Y Z
1529
1530 This can be troublesome because X, Y, and Z tasks may be executed on
1531 different machines, and then require communication to move around.
1532
1533 This optimization identifies this situation, lowers all of the graphs to
1534 concrete dicts, and then calls ``fuse`` on them, with a width equal to the
1535 number of layers like X, Y, and Z.
1536
1537 This is currently used within array and dataframe optimizations.
1538
1539 Parameters
1540 ----------
1541 graph : HighLevelGraph
1542 The full graph of the computation
1543 keys : list
1544 The output keys of the computation, to be passed on to fuse
1545
1546 See Also
1547 --------
1548 Blockwise
1549 fuse
1550 """
1551 layers = ensure_dict(graph.layers, copy=True)
1552 dependencies = ensure_dict(graph.dependencies, copy=True)
1553 dependents = reverse_dict(dependencies)
1554
1555 for name, layer in graph.layers.items():
1556 deps = graph.dependencies[name]
1557 if (
1558 isinstance(layer, Blockwise)
1559 and len(deps) > 1
1560 and not any(dependencies[dep] for dep in deps) # no need to fuse if 0 or 1
1561 and all(len(dependents[dep]) == 1 for dep in deps)
1562 and all(layer.annotations == graph.layers[dep].annotations for dep in deps)
1563 ):
1564 new = toolz.merge(layer, *[layers[dep] for dep in deps])
1565 new, _ = fuse(new, keys, ave_width=len(deps))
1566
1567 for dep in deps:
1568 del layers[dep]
1569 del dependencies[dep]
1570
1571 layers[name] = new
1572 dependencies[name] = set()
1573
1574 return HighLevelGraph(layers, dependencies)
1575
1576
1577 def _blockwise_unpack_collections_task_spec(expr):
1578 # FIXME This is a copy of the delayed.unpack_collections function with the
1579 # addition of the TaskSpec class. Eventually this should all be consolidated
1580 # but to reduce the number of changes we'll vendor this here
1581 # FIXME: There is also a dask.base version of unpack_collections that looks
1582 # similar but is different. At the very least the names should be fixed
1583 if isinstance(expr, Delayed):
1584 return TaskRef(expr._key), (expr,)
1585
1586 if base.is_dask_collection(expr):
1587 if hasattr(expr, "optimize"):
1588 # Optimize dask-expr collections
1589 expr = expr.optimize()
1590
1591 finalized = finalize(expr)
1592 return TaskRef(finalized._key), (finalized,)
1593
1594 if type(expr) is type(iter(list())):
1595 expr = list(expr)
1596 elif type(expr) is type(iter(tuple())):
1597 expr = tuple(expr)
1598 elif type(expr) is type(iter(set())):
1599 expr = set(expr)
1600
1601 typ = type(expr)
1602
1603 if typ in (list, tuple, set):
1604 args, collections = utils.unzip(
1605 (_blockwise_unpack_collections_task_spec(e) for e in expr), 2
1606 )
1607 collections = tuple(toolz.unique(toolz.concat(collections), key=id))
1608 if not collections:
1609 return expr, ()
1610 args = List(*args)
1611 # Ensure output type matches input type
1612 if typ is not list:
1613 args = Task(None, typ, args)
1614 return args, collections
1615
1616 if typ is dict:
1617 args, collections = _blockwise_unpack_collections_task_spec(
1618 [[k, v] for k, v in expr.items()]
1619 )
1620 if not collections:
1621 return expr, ()
1622 return Dict(args), collections
1623
1624 if typ is slice:
1625 args, collections = _blockwise_unpack_collections_task_spec(
1626 [expr.start, expr.stop, expr.step]
1627 )
1628 if not collections:
1629 return expr, ()
1630 return Task(None, slice, *args), collections
1631
1632 if is_dataclass(expr):
1633 args, collections = _blockwise_unpack_collections_task_spec(
1634 [
1635 [f.name, getattr(expr, f.name)]
1636 for f in fields(expr)
1637 if hasattr(expr, f.name) # if init=False, field might not exist
1638 ]
1639 )
1640 if not collections:
1641 return expr, ()
1642 try:
1643 _fields = {
1644 f.name: getattr(expr, f.name)
1645 for f in fields(expr)
1646 if hasattr(expr, f.name)
1647 }
1648 replace(expr, **_fields)
1649 except (TypeError, ValueError) as e:
1650 if isinstance(e, ValueError) or "is declared with init=False" in str(e):
1651 raise ValueError(
1652 f"Failed to unpack {typ} instance. "
1653 "Note that using fields with `init=False` are not supported."
1654 ) from e
1655 else:
1656 raise TypeError(
1657 f"Failed to unpack {typ} instance. "
1658 "Note that using a custom __init__ is not supported."
1659 ) from e
1660 return Task(None, typ, **dict(args)), collections
1661
1662 if utils.is_namedtuple_instance(expr):
1663 args, collections = _blockwise_unpack_collections_task_spec([v for v in expr])
1664 if not collections:
1665 return expr, ()
1666 return Task(None, typ, *args), collections
1667
1668 return expr, ()