Repository navigation
Clarify block_info documentation - #8425
Conversation
|
@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. |
|
I will say, I tried and failed to insert other keys into the The original documentation (below) makes it sound like you could pass multiple input array arguments, or multiple kwargs with arrays into your
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. |
|
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
left a comment
There was a problem hiding this comment.
@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:
Lines 521 to 523 in f91179f
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
Lines 488 to 489 in f91179f
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.
|
I also struggle with remembering the details of |
That's what I thought, but actually trying that produces an Example script using dask version 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 |
@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. |
|
Sorry, I didn't notice it before, but the reason your code snippet doesn't work is because
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: |
Instead of a vanilla dict, each element of 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). |
Oh whoops! That makes sense, I guess I should have been more careful. Thanks for clearing up the confusion @ParticularMiner |
|
@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 😄 |
|
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) |
|
I think your idea could very well improve things. Though, depending on how often |
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 😄 |
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 So in the following, the block-array associated with the first array ( 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 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! |
|
You are right @ParticularMiner. |
|
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.
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.) |
|
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). |
|
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 How does the following attempt sound?
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. |
No worries, this is a good time for these discussions.
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:But, if you switch the order of the input arrays, it doesn't work (we get an 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 rangeThat's the reason I was trying to convey the first array as being "special", because the process does not appear to commute. |
|
This is a very interesting example! Thank you for sharing it. First things first:
That being said, it is still curious why with your definition of |
2, 3, 4: Slightly simpler examples for return values
|
|
I agree with your last message completely. Also, your choice 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 So if you fix the number of dimensions output by 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 In particular, it turns out that Lines 692 to 696 in 2e5bab9 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 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 |
|
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) |
|
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. |
😄 To be honest, neither can I at this moment. But I will at least say that the docs do mention that |
|
The default number of dimensions in the output are the same as the input array dimensions (unless I've misunderstood your comment).. |
|
Merged the |
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. |
I personally found the documentation about the Dask array
block_infokwarg 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.
block_infokeyword argument in Dask arraymap_blocks#8342Tests added / passed(not applicable)pre-commit run --all-files