Skip to content

Clarify block_info documentation - #8425

Merged
jsignell merged 9 commits into
dask:mainfrom
GenevieveBuckley:block-info-clarify-docs
Dec 10, 2021
Merged

jsignell merged 9 commits into
dask:mainfrom
GenevieveBuckley:block-info-clarify-docs

Conversation

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

I personally found the documentation about the Dask array block_info kwarg difficult to understand. Obviously that's a problem on my end, but it made me wonder if I could make the docs a bit clearer in this area.

This PR is an attempt to prevent skimming & misreading like I did, mostly by introducing bullet points.for each new piece of information.

I'd like to get other people's eyes on this to see if it actually is an improvement, or if I've just rewritten it to make sense for one person who is me.

@github-actions github-actions Bot added the array label Nov 29, 2021
@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

@m-albert do you have thoughts? You understood this part of the docs well originally, and did a good job of explaining it to me clearly as well.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I will say, I tried and failed to insert other keys into the block_info dictionary.

The original documentation (below) makes it sound like you could pass multiple input array arguments, or multiple kwargs with arrays into your map_blocks function and have those be accessible from the block_info dictionary as well, but when I tried that it didn't work (code sample below).

For each argument and keyword arguments that are dask arrays (the positions
of which are the first index), you will receive the shape of the full
array, the number of chunks of the full array in each dimension, the chunk
location (for example the fourth chunk over in the first dimension), and
the array location (for example the slice corresponding to ``40:50``). The
same information is provided for the output, with the key ``None``, plus
the shape and dtype that should be returned.
from pprint import pprint

def func(arr, my_kwarg=arr3, block_info=None):
    pprint(block_info)
    print("========================")
    return arr

import dask.array as da

arr = da.random.random((100,100), chunks=(50, 50))
arr2 = da.random.random((50, 50), chunks=(10, 10))

out = da.map_blocks(func, arr, my_kwarg=arr3)

with dask.config.set(scheduler='sync'):
    out.compute()

For this reason,, I've leaned away from using the same language "for each argument and keyword argument" in the revised text of this PR, because it doesn't seem to give an accurate impression of the actual behaviour.

@ParticularMiner

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

I also found that part of the docs hard to follow. Your expansion on the other hand is much clearer in my view. Great work!

@m-albert m-albert left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GenevieveBuckley I'd agree that the docs regarding this can get much clearer than they currently are.

It's true that block_info doesn't show info for dask arrays included as keyword arguments to map_blocks, although the docs suggest that it does. Actually, the docs say that kwargs shouldn't contain dask arrays:

dask/dask/array/core.py

Lines 521 to 523 in f91179f

**kwargs :
Other keyword arguments to pass to function. Values must be constants
(not dask.arrays)

For several dask arrays passed as regular arguments block_info works though (e.g. def func(arr, arr2, block_info=None): and out = da.map_blocks(func, arr, arr) in your example).

As a general comment, I've noticed that the current block_info explanation is part of the map_blocks function examples (and not of the API doc). This might contribute to why it's so easy to get confused about this functionality. Probably one can only find the right place in the docs with ctrl-f and already knowing about the "block_info" keyword.

Would it make sense to at least mention it further above in the function doc? A good and visible place could be here

dask/dask/array/core.py

Lines 488 to 489 in f91179f

func : callable
Function to apply to every block in the array.

Here's a suggestion:

    func : callable
        Function to apply to every block in the array. If `func` accepts `block_info=` or `block_id=` as keyword arguments, these will be passed dictionaries containing information about input and output chunks/arrays during computation. See examples.

Comment thread dask/array/core.py Resolved
Comment thread dask/array/core.py Resolved
Comment thread dask/array/core.py Resolved
@d-v-b

d-v-b commented Nov 29, 2021

Copy link
Copy Markdown
Member

I also struggle with remembering the details of block_info... What about making block_info (or the values inside it) an object? For backwards compatibility it could support __getitem__ access to the current values.

@GenevieveBuckley

GenevieveBuckley commented Nov 30, 2021 •

Copy link
Copy Markdown
Contributor Author

For several dask arrays passed as regular arguments block_info works though (e.g. def func(arr, arr2, block_info=None): and out = da.map_blocks(func, arr, arr) in your example).

That's what I thought, but actually trying that produces an IndexError during task graph construction. So I don't think that's the expected use.

Example script using dask version 2021.11.1:

import dask.array as da
from pprint import pprint

def func(arr, arr2, block_info=None):
    pprint(block_info)
    print("========================")
    return arr


arr = da.random.random((100,100), chunks=(50, 50))
arr2 = da.random.random((50, 50), chunks=(10, 10))

print("Generating output task graph...")
out = da.map_blocks(func, arr, arr2)

print("Computing result...")
with dask.config.set(scheduler='sync'):
    out.compute()

Produces this

Generating output task graph...
None
========================
None
========================

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_84687/3052542459.py in <module>
     12 
     13 print("Generating output task graph...")
---> 14 out = da.map_blocks(func, arr, arr2)
     15 
     16 print("Computing result...")

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in map_blocks(func, name, token, dtype, chunks, drop_axis, new_axis, meta, *args, **kwargs)
    812                     "shape": shape,
    813                     "num-chunks": num_chunks[i],
--> 814                     "array-location": [
    815                         (starts[i][ij][j], starts[i][ij][j + 1])
    816                         for ij, j in enumerate(arr_k)

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in <listcomp>(.0)
    813                     "num-chunks": num_chunks[i],
    814                     "array-location": [
--> 815                         (starts[i][ij][j], starts[i][ij][j + 1])
    816                         for ij, j in enumerate(arr_k)
    817                     ],

IndexError: tuple index out of range

@GenevieveBuckley

GenevieveBuckley commented Nov 30, 2021 •

Copy link
Copy Markdown
Contributor Author

I also struggle with remembering the details of block_info... What about making block_info (or the values inside it) an object? For backwards compatibility it could support __getitem__ access to the current values.

@d-v-b can you elaborate? I'm not quite sure how this would be easier/simpler to remember, so I might not be fully picturing what you have in mind.

@ParticularMiner

ParticularMiner commented Nov 30, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

Sorry, I didn't notice it before, but the reason your code snippet doesn't work is because map_blocks() expects all dask array arguments to have the same number of blocks/chunks up to broadcasting rules. This is mentioned somewhere in the docs:

The relevant attribute to match is numblocks.

x.numblocks
(10,)
y.numblocks
(10,)
If these match (up to broadcasting rules) then we can map arbitrary functions across blocks

I think the error message and traceback log are not very informative. Hence the confusion.

So the following does work:

import dask.array as da
import dask
from pprint import pprint

def func(arr, arr2, block_info=None):
    pprint(block_info)
    print("========================")
    return arr


arr = da.random.random((100,100), chunks=(50, 50))
arr2 = da.random.random((50, 50), chunks=(25, 25))

print("Generating output task graph...")
out = da.map_blocks(func, arr, arr2, dtype=arr.dtype)

print("Computing result...")
with dask.config.set(scheduler='sync'):
    out.compute()

with output:

Generating output task graph...
None
========================
array([], shape=(0, 0), dtype=object)
========================
Computing result...
{None: {'array-location': [(0, 50), (0, 50)],
        'chunk-location': (0, 0),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(0, 50), (0, 50)],
     'chunk-location': (0, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(0, 25), (0, 25)],
     'chunk-location': (0, 0),
     'num-chunks': (2, 2),
     'shape': (50, 50)}}
========================
{None: {'array-location': [(0, 50), (50, 100)],
        'chunk-location': (0, 1),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(0, 50), (50, 100)],
     'chunk-location': (0, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(0, 25), (25, 50)],
     'chunk-location': (0, 1),
     'num-chunks': (2, 2),
     'shape': (50, 50)}}
========================
{None: {'array-location': [(50, 100), (0, 50)],
        'chunk-location': (1, 0),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(50, 100), (0, 50)],
     'chunk-location': (1, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(25, 50), (0, 25)],
     'chunk-location': (1, 0),
     'num-chunks': (2, 2),
     'shape': (50, 50)}}
========================
{None: {'array-location': [(50, 100), (50, 100)],
        'chunk-location': (1, 1),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(50, 100), (50, 100)],
     'chunk-location': (1, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(25, 50), (25, 50)],
     'chunk-location': (1, 1),
     'num-chunks': (2, 2),
     'shape': (50, 50)}}
========================

@d-v-b

d-v-b commented Nov 30, 2021

Copy link
Copy Markdown
Member

@d-v-b can you elaborate? I'm not quite sure how this would be easier/simpler to remember, so I might not be fully picturing what you have in mind.

Instead of a vanilla dict, each element of block_info could be an object with type hints and immutable fields, and the collection of block infos could also be structured (I always find it confusing that block_info uses None as a key, for example. It would be easier if this was a named field).
e.g.

from dataclasses import dataclass
from typing import Tuple, Dict


@dataclass(frozen=True)
class BlockInfo():
    array_location: Tuple[int, ...]
    chunk_shape: Tuple[int, ...]
    dtype: str
    num_chunks: Tuple[int, ...]
    shape: Tuple[int, ...]


@dataclass(frozen=True)
class BlockInfoCollection():
    input: BlockInfo
    args: Tuple[BlockInfo]
    kwargs: Dict[str, BlockInfo]
    output: BlockInfo

(Feel free to flag this is as off-topic. I think improving the docs is also good).

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Sorry, I didn't notice it before, but the reason your code snippet doesn't work is because map_blocks() expects all dask array arguments to have the same number of blocks/chunks up to broadcasting rules. This is mentioned somewhere in the docs

Oh whoops! That makes sense, I guess I should have been more careful. Thanks for clearing up the confusion @ParticularMiner

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

@d-v-b for the type of change you're proposing, it might be better to open a new issue with the details for discussion. I suspect not many people will see your idea if it stays semi-hidden in this thread 😄

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Ok, I've updated the text to also include cases where there are multiple input Dask arrays.

I think this is pretty much done, unless there are any other review suggestions that pop up. (Thanks everyone who made suggestions so far, it's very helpful)

Comment thread dask/array/core.py Resolved
@ParticularMiner

Copy link
Copy Markdown
Contributor

@d-v-b

I think your idea could very well improve things. Though, depending on how often block_info is referenced in the source code, the suggested changes could involve extensive modification. If you can spare the time and effort, why not submit a PR with your suggested improvements? Another thing I'd watch out for would be its impact on performance.

@d-v-b

d-v-b commented Dec 1, 2021

Copy link
Copy Markdown
Member

@d-v-b for the type of change you're proposing, it might be better to open a new issue with the details for discussion. I suspect not many people will see your idea if it stays semi-hidden in this thread 😄

Yep! I've been meaning to put this into a PR for a while, just haven't found the time :)

@jakirkham

Copy link
Copy Markdown
Member

@d-v-b for the type of change you're proposing, it might be better to open a new issue with the details for discussion. I suspect not many people will see your idea if it stays semi-hidden in this thread 😄

Yep! I've been meaning to put this into a PR for a while, just haven't found the time :)

This is why an issue would be great! Can pretty much just copy-paste what you wrote above 😄

@ParticularMiner

ParticularMiner commented Dec 2, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

The sentence now says:

"(Note that if you pass multiple Dask arrays as input to the function, the arrays must have the same number of chunks, or be able to broadcast to the shape of the first Dask array.)"

Perhaps I misunderstand you. But the term "broadcasting", as used here, applies to the associated "block-arrays", not the arrays themselves. A "block-array" (this is not a term in widespread use: I'm only using it here for lack of a better moniker) is effectively the array obtained by considering its blocks, or chunks, as the array elements. The shape of such a "block-array" is what is stored in the actual array's .numblocks attribute. Hence the broadcasting rules apply not to the .shape attributes of the arrays but rather to their .numblocks attributes. This makes sense, since map_blocks is expected to map (and therefore broadcast where applicable) blocks.

So in the following, the block-array associated with the first array (arr) broadcasts to the block array associated with the second array (arr2). Still, both map_blocks(func, arr, arr2) and map_blocks(func, arr2, arr) work:

arr = da.random.random((100,100), chunks=(50, 100))	# arr.numblocks = (2, 1)
arr2 = da.random.random((50, 50), chunks=(25, 25))	# arr2.numblocks = (2, 2)

The converse is also true:

arr = da.random.random((100,100), chunks=(50, 50))	# arr.numblocks = (2, 2)
arr2 = da.random.random((50, 50), chunks=(25, 50))	# arr2.numblocks = (2, 1)

And so are many other cases, to list only a couple more:

arr = da.random.random((100,100), chunks=(100, 50))	# arr.numblocks = (1, 2)
arr2 = da.random.random((50, 50), chunks=(25, 50))	# arr2.numblocks = (2, 1)
arr = da.random.random((100,100), chunks=(50, 100))	# arr.numblocks = (2, 1)
arr2 = da.random.random((50, 50), chunks=(50, 25))	# arr2.numblocks = (1, 2)

You can further experiment to check whether what I'm saying holds. In fact, the block_info parameter's chunk_location values are interesting to look at to reveal how each block of each array was associated with the blocks of the other arrays.

As I'm writing this I'm beginning to realize that the docs (perhaps too hastily) assume that the reader has already grasped the context of what it is attempting to describe, thus unwittingly creates uncertainty of meaning in the reader's mind. This is why it is very good you're redressing the docs. Thanks!

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

You are right @ParticularMiner.
I appreciate the dedication to correctness (sincerely), but I am struggling to find a way to express this succinctly.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I'm going to add the words "and chunk structure" as a shorthand for what you've described above. Hopefully that should be enough of a trigger for users to go and learn more about it if they need to.

"(Note that if you pass multiple Dask arrays as input to the function, the arrays must have the same number of chunks, or be able to broadcast to the shape and chunk structure of the first Dask array.)"

It's not as comprehensive an explanation as you have above, but also this is not the right place for a comprehensive explanation of that particular concept. If we need this extra detail, just not in this spot, we should open another issue with the comment above copy-pasted and try and identify a good spot to put it. (Multiple small PRs are generally quicker to merge, I'm not just fobbing you off here.)

Comment thread dask/array/core.py Resolved
@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Ok, PR ready for review/merge.

If someone has a nicer way to phrase that sentence, we can add it.

If we need a more detailed description of how Dask arrays can/can't broadcast elsewhere in the docs, an issue should be opened for that (can copy-paste the text of comments in this thread).

@ParticularMiner

ParticularMiner commented Dec 6, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

I understand. No problem. I did not intend to have my full explanation added to the docs — just thought it might help guide you to amend that particular sentence I was addressing. In reality, I was a bit worried I would come across as being pedantic. 😄

I also appreciate the fact that it is difficult to summarize into a few words. I just checked, and found that the .numblocks attribute has not been explained at all in the docs (see link). This makes it even more difficult.

How does the following attempt sound?

"(Note that if you pass multiple Dask arrays as input to map_blocks, the arrays must match each other by having matching numbers of chunks, or blocks, along corresponding dimensions up to broadcasting rules.)"

By including the clause "the arrays must match each other" I hope to convey a sense of commutativity to the matching condition. In that way, the first array no longer seems special.

Also, I'm assuming the reader will grasp what broadcasting means in this context, or else will research what it means. A good article on broadcasting (in a different context) is numpy's, which I mention here in case you feel it is useful to include a link to. The Dask docs refer to numpy's docs very often anyway.

@GenevieveBuckley

GenevieveBuckley commented Dec 7, 2021 •

Copy link
Copy Markdown
Contributor Author

In reality, I was a bit worried I would come across as being pedantic. smile

No worries, this is a good time for these discussions.

By including the clause "the arrays must match each other" I hope to convey a sense of commutativity to the matching condition. In that way, the first array no longer seems special.

It's not actually commutative though (at least according to my small experiments). Here's an example.

This works well...

import dask
import dask.array as da
import numpy as np
from pprint import pprint

def func(a1, a2, block_info=None):
    pprint(block_info)
    print("========================")
    return a1


arr1 = da.random.random((100, 100), chunks=(50, 50))
arr2 = da.random.random((50), chunks=(25))

print("Generating output task graph...")
result1 = da.map_blocks(func, arr1, arr2)

print("Computing result...")
with dask.config.set(scheduler='sync'):
    result1.compute()
    print("Success!")
Click to expand output:
Generating output task graph...
None
========================
None
========================
None
========================
array([], shape=(0, 0), dtype=object)
========================
Computing result...
{None: {'array-location': [(0, 50), (0, 50)],
        'chunk-location': (0, 0),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(0, 50), (0, 50)],
     'chunk-location': (0, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(0, 25)],
     'chunk-location': (0,),
     'num-chunks': (2,),
     'shape': (50,)}}
========================
{None: {'array-location': [(50, 100), (0, 50)],
        'chunk-location': (1, 0),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(50, 100), (0, 50)],
     'chunk-location': (1, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(0, 25)],
     'chunk-location': (0,),
     'num-chunks': (2,),
     'shape': (50,)}}
========================
{None: {'array-location': [(0, 50), (50, 100)],
        'chunk-location': (0, 1),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(0, 50), (50, 100)],
     'chunk-location': (0, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(25, 50)],
     'chunk-location': (1,),
     'num-chunks': (2,),
     'shape': (50,)}}
========================
{None: {'array-location': [(50, 100), (50, 100)],
        'chunk-location': (1, 1),
        'chunk-shape': (50, 50),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 100)},
 0: {'array-location': [(50, 100), (50, 100)],
     'chunk-location': (1, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)},
 1: {'array-location': [(25, 50)],
     'chunk-location': (1,),
     'num-chunks': (2,),
     'shape': (50,)}}
========================
Success!

But, if you switch the order of the input arrays, it doesn't work (we get an IndexError)

print("Generating output task graph...")
result2 = da.map_blocks(func, arr2, arr1)

print("Computing result...")
with dask.config.set(scheduler='sync'):
    result2.compute()
Click to expand output and error message:
Generating output task graph...
None
========================
None
========================
None
========================
array([], shape=(0, 0), dtype=object)
========================
Computing result...
{None: {'array-location': [(0, 50), (0, 25)],
        'chunk-location': (0, 0),
        'chunk-shape': (50, 25),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 50)},
 0: {'array-location': [(0, 25)],
     'chunk-location': (0,),
     'num-chunks': (2,),
     'shape': (50,)},
 1: {'array-location': [(0, 50), (0, 50)],
     'chunk-location': (0, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)}}
========================
{None: {'array-location': [(50, 100), (0, 25)],
        'chunk-location': (1, 0),
        'chunk-shape': (50, 25),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 50)},
 0: {'array-location': [(0, 25)],
     'chunk-location': (0,),
     'num-chunks': (2,),
     'shape': (50,)},
 1: {'array-location': [(50, 100), (0, 50)],
     'chunk-location': (1, 0),
     'num-chunks': (2, 2),
     'shape': (100, 100)}}
========================
{None: {'array-location': [(0, 50), (25, 50)],
        'chunk-location': (0, 1),
        'chunk-shape': (50, 25),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 50)},
 0: {'array-location': [(25, 50)],
     'chunk-location': (1,),
     'num-chunks': (2,),
     'shape': (50,)},
 1: {'array-location': [(0, 50), (50, 100)],
     'chunk-location': (0, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)}}
========================
{None: {'array-location': [(50, 100), (25, 50)],
        'chunk-location': (1, 1),
        'chunk-shape': (50, 25),
        'dtype': dtype('float64'),
        'num-chunks': (2, 2),
        'shape': (100, 50)},
 0: {'array-location': [(25, 50)],
     'chunk-location': (1,),
     'num-chunks': (2,),
     'shape': (50,)},
 1: {'array-location': [(50, 100), (50, 100)],
     'chunk-location': (1, 1),
     'num-chunks': (2, 2),
     'shape': (100, 100)}}
========================

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_138721/1000983004.py in <module>
     17 print("Computing result...")
     18 with dask.config.set(scheduler='sync'):
---> 19     result.compute()
     20     print("Success!")

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(self, **kwargs)
    286         dask.base.compute
    287         """
--> 288         (result,) = compute(self, traverse=False, **kwargs)
    289         return result
    290 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in compute(*args, **kwargs)
    569 
    570     results = schedule(dsk, keys, **kwargs)
--> 571     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    572 
    573 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/base.py in <listcomp>(.0)
    569 
    570     results = schedule(dsk, keys, **kwargs)
--> 571     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    572 
    573 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in finalize(results)
   1121     while isinstance(results2, (tuple, list)):
   1122         if len(results2) > 1:
-> 1123             return concatenate3(results)
   1124         else:
   1125             results2 = results2[0]

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in concatenate3(arrays)
   4889     if not ndim:
   4890         return arrays
-> 4891     chunks = chunks_from_arrays(arrays)
   4892     shape = tuple(map(sum, chunks))
   4893 

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in chunks_from_arrays(arrays)
   4676 
   4677     while isinstance(arrays, (list, tuple)):
-> 4678         result.append(tuple(shape(deepfirst(a))[dim] for a in arrays))
   4679         arrays = arrays[0]
   4680         dim += 1

~/anaconda3/envs/dask/lib/python3.8/site-packages/dask/array/core.py in <genexpr>(.0)
   4676 
   4677     while isinstance(arrays, (list, tuple)):
-> 4678         result.append(tuple(shape(deepfirst(a))[dim] for a in arrays))
   4679         arrays = arrays[0]
   4680         dim += 1

IndexError: tuple index out of range

That's the reason I was trying to convey the first array as being "special", because the process does not appear to commute.

@ParticularMiner

ParticularMiner commented Dec 7, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

This is a very interesting example! Thank you for sharing it.

First things first:

  1. I'm presuming there are a few typos, and that you meant to write

    arr1 = da.random.random((100, 100), chunks=(50, 50))
    arr2 = da.random.random((50), chunks=(25))
    result = da.map_blocks(func, arr1, arr2)
    result = da.map_blocks(func, arr2, arr1)

    instead of this:

    arr2 = da.random.random((100, 100), chunks=(50, 50))
    arr2 = da.random.random((50), chunks=(25))
    result = da.map_blocks(func, arr, arr2)
    result = da.map_blocks(func, arr2, arr1)

    right? If that's true then you may continue reading otherwise what I say below wouldn't make sense.

  2. As you said, map_blocks(func, arr1, arr2) works while map_blocks(func, arr2, arr1) does not. But note that the chunk-function func is manifestly non-commutative by means of the following line:

    return a1

    and that is the real reason why the first array is special. In other words, the user is the one making it special, not map_blocks.

  3. To make this assertion more evident, I will change the return statement of func to:

    return a2

    without changing anything else, and you will find that this time map_blocks(func, arr2, arr1) works while map_blocks(func, arr1, arr2) does not (that is, the converse of the above point is true).

  4. Furthermore, if, for instance, I change the return statement of func to

       return np.array([[np.max(a1)]])

    then both map_blocks(func, arr1, arr2) and map_blocks(func, arr2, arr1) work.

  5. The conclusion I've come to is this: I agree with you that map_blocks() is not commutative. That is clear from your example. Though commutativity lies entirely in the hands of the user, not map_blocks(). However, the foregoing arguments also clearly show that the first array argument to map_blocks() is not special. Thus the statement:

    (Note that if you pass multiple Dask arrays as input to map_blocks, the arrays must match each other by having matching numbers of chunks, or blocks, along corresponding dimensions up to broadcasting rules.)"

    is not wrong.

That being said, it is still curious why with your definition of func, map_blocks(func, arr2, arr1) fails while map_blocks(func, arr1, arr2) does not. I understand why the latter succeeds, but not why the former fails. I'm still trying to figure out whether that is a bug in dask or it is to be expected.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author
  1. Oops yes, I had a lot of typos. I was trying to rename variables for clarify, rather than reusing the same names, and did not do a very good job of it. I've updated my comment above, thank you.

2, 3, 4: Slightly simpler examples for return values

  • return a1 (non-commutative)
  • return a2 (non-commutative)
  • return np.array([[1,]]) (commutative)
  • return None (as you say, gives an IndexError in both situations. This isn't too surprising, because Dask needs to be able to concatenate/join the results back together and only really understands how to do that for numpy arrays / pandas dataframes. We see the same problem pop up if the returned output is a python list, but a numpy array of the list data would work just fine)
  1. This is reasonable 😄

@ParticularMiner

ParticularMiner commented Dec 7, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

I agree with your last message completely. Also, your choice return np.array([[1]]) is indeed a much better example than mine. What I did in [4.] was rash — completely removing a return statement is never right for map_blocks() which always expects an output array. I've updated [4.] in my last message above with your suggestion. Thanks for the correction.

The following is an aside. No need to consider it in the PR, if you do not want to.

In fact, your suggestion hints at the answer to the question I was puzzling over: why does map_blocks(lambda x, y: x, arr2, arr1) not work but map_blocks(lambda x, y: x, arr1, arr2) does? I think the reason is simply because the number of dimensions output by func = lambda x, y: x changes with the order of (arr1, arr2).

So if you fix the number of dimensions output by func, say like this:

def func(a1, a2, block_info=None):
   # add more dimensions to output if a2.ndim > a1.ndim
    newaxes=(slice(None),)*a1.ndim + (np.newaxis,)*(a2.ndim - a1.ndim)
    return a1[newaxes]

then both map_blocks(func, arr2, arr1) and map_blocks(func, arr1, arr2) work.

In particular, it turns out that map_blocks always expects the output to have the same number of dimensions as the input array with the largest number of dimensions. This is apparent from the source code of map_blocks():

dask/dask/array/core.py

Lines 692 to 696 in 2e5bab9

if arrs:
out_ind = tuple(range(max(a.ndim for a in arrs)))[::-1]
else:
out_ind = ()

Those input arrays with lower numbers of dimensions obtain additional dimensions, each of size 1, in accordance with broadcasting rules. Yet these arrays are not passed with their newly obtained dimensions into func. This could actually be a bug!

Accordingly, if you set the input arrays as follows:

arr1 = da.random.random((100, 100), chunks=(50, 50))
arr2 = da.random.random((50, 1), chunks=(25, 1))

then both map_blocks(lambda x, y: x, arr2, arr1) and map_blocks(lambda x, y: x, arr1, arr2) work, since here, arr1 and arr2 have the same number of dimensions.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Ooh, fascinating.

Maybe if there was an easy way to pass in the arrays with their expanded dimensions, that might be the simplest? (I have not looked at this code closely and can't comment on how feasible that is likely to be - you'll know much better than me)

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Could someone from @dask/maintenance take a look a this docs PR when you get a chance? Thanks!

FYI, we're also having a side conversation here about a possible bug but that'll be addressed separately if a nice solution is found, so it's not a blocker for this docs PR.

@ParticularMiner

ParticularMiner commented Dec 8, 2021 •

Copy link
Copy Markdown
Contributor

@GenevieveBuckley

Maybe if there was an easy way to pass in the arrays with their expanded dimensions, that might be the simplest? (I have not looked at this code closely and can't comment on how feasible that is likely to be - you'll know much better than me)

😄 To be honest, neither can I at this moment. But I will at least say that the docs do mention that map_blocks() offers additional keyword arguments drop_axis and new_axis that allow the user to change the number of dimensions of the output. The docs just don't say what the default number of dimensions of the output are in the first place. 😆 Well, I guess that's what block_info[None] is for. Though you can only access that during runtime.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

The default number of dimensions in the output are the same as the input array dimensions (unless I've misunderstood your comment)..

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Merged the main branch in, let's see if that will fix the failing MacOS checks (those can't have had anything to do with this PR, I don't think).

@ParticularMiner

Copy link
Copy Markdown
Contributor

The default number of dimensions in the output are the same as the input array dimensions (unless I've misunderstood your comment)..

True. For one input array or multiple input arrays of the same number of dimensions. But it doesn't say what the default is if the arrays have different numbers of dimensions.

@GenevieveBuckley GenevieveBuckley changed the title Try to clarify block_info documentation Clarify block_info documentation Dec 10, 2021
Comment thread dask/array/core.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants