Repository navigation
Limit max chunk size when reshaping dask arrays - #8124
Conversation
|
Thanks @GenevieveBuckley for the quick fix! With this PR and import dask.array
# this array has 80MB chunks
arr = dask.array.random.random((300, 180, 4, 18483), chunks=(-1, -1, 1, 183))
# this array has 8GB chunks
arr.reshape(300, 180, -1)If we instead provide |
|
I'm also noticing that the test I added is failing, but only on Windows? I don't have a Windows machine handy to test things out on locally, so I'm just making a note of it here to come back to. |
|
I just tried out another approach, splitting the big chunks into two if the largest chunksize falls above the limit. outchunks = list(outchunks)
max_chunksize = [max(c) for c in outchunks]
if limit is None:
limit = parse_bytes(config.get("array.chunk-size"))
nbytes = x.dtype.itemsize
while (np.prod(max_chunksize) * nbytes) > limit:
idx = np.argmax(max_chunksize)
reduced_chunks = []
for c in outchunks[idx]:
if c >= max(max_chunksize):
# split big chunk into two
reduced_chunks.append(np.ceil(c/2).astype(int))
reduced_chunks.append(np.floor(c/2).astype(int))
else:
reduced_chunks.append(c)
outchunks[idx] = reduced_chunks
max_chunksize = [max(c) for c in outchunks]
outchunks = tuple(outchunks)I don't like it quite as much:
|
🤦🏾 you're right.
|
Hm, can you elaborate on this? (Like, I'm not sure that it's right... but I'm also not sure that it's wrong, so hearing other people's reasoning might help me sort through why I'm unsure about it)
This works for you, but is not a generalized solution we can use across the board. People reshape arrays in all kinds of ways. |
Right the idea there is that we tell normalize_chunks to only change chunksize for the new axes instead of passing Looking at this a little more, it looks like this logic might have to live in |
|
@GenevieveBuckley and @dcherian What is the status of this PR, it looks like we were onto something, but it looks like it is not a generalized case. If this is a dead-end, should we close this PR? |
Progress has definitely stalled. I think we should keep it open though, unless we have a new PR that supersedes it. |
|
I spent some time today looking at whether we could modify Short summary: we could address the issue for this particular problem by running the Also, although this problem only pops up when |
I think I have an idea for how we can implement this idea in a more general way.
|
|
I'm happy with this, I think it's ready for final review/merge now. Nice way to end the week! 🎉 |
|
It looks like we have some legit fails on Windows see https://github.com/dask/dask/runs/4332313529?check_suite_focus=true#step:6:21146 I'm not sure what is causing the overflow, any ideas about what could it be? |
dcherian
left a comment
There was a problem hiding this comment.
Thanks @GenevieveBuckley this is exciting!
| # Decrememt counter if multiple same-size matches exist | ||
| elif matching_chunks[out] > 1: |
There was a problem hiding this comment.
| # Decrememt counter if multiple same-size matches exist | |
| elif matching_chunks[out] > 1: | |
| # Decrement counter if multiple same-size matches exist | |
| else: |
| limit = parse_bytes(config.get("array.chunk-size")) | ||
| if max_chunksize_in_bytes > limit: | ||
| # Leave chunk sizes unaltered where possible | ||
| matching_chunks = Counter(inchunks) & Counter(outchunks) |
There was a problem hiding this comment.
This would fail for something like
inchunks = ((1,1,1), (2,2,2))
outchunks = ((2,2,2), (3,3,3))
from collections import Counter
Counter(inchunks) & Counter(outchunks)
# Counter({(2, 2, 2): 1})
but I can't think of an array example that would result in a similar situation.
There was a problem hiding this comment.
I think that is the desired behaviour in those circumstances? I agree, this would be easier to talk about if we had an array example.
General rule is: if you have output chunks that look like they match chunks from an input dimension, preserve the chunk structure, otherwise use "auto" chunking.
Co-authored-by: Deepak Cherian <[email protected]>
Thanks for flagging this @ncclementi |
Co-authored-by: Deepak Cherian <[email protected]>
|
Update: the integer overflow is happening when we multiply many potentially very large numbers together. Switching to use EDIT: Huh, apparently the |
|
For convenience, here's an example of the failing test: Click to expand - test failing because of overflow error:================================== FAILURES ===================================
______________________ test_reshape_avoids_large_chunks _______________________
[gw1] win32 -- Python 3.7.12 C:\Miniconda3\envs\test-environment\python.exe
def test_reshape_avoids_large_chunks():
limit = parse_bytes("128MiB")
x = da.random.random((300, 180, 4, 18483), chunks=(-1, -1, 1, 183))
> result = x.reshape(300, 180, -1)
dask\array\tests\test_array_core.py:1215:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
dask\array\core.py:1998: in reshape
return reshape(self, shape, merge_chunks=merge_chunks)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
x = dask.array<random_sample, shape=(300, 180, 4, 18483), dtype=float64, chunksize=(300, 180, 1, 183), chunktype=numpy.ndarray>
shape = (300, 180, 73932), merge_chunks = True, limit = None
def reshape(x, shape, merge_chunks=True, limit=None):
"""Reshape array to new shape
Parameters
----------
shape : int or tuple of ints
The new shape should be compatible with the original shape. If
an integer, then the result will be a 1-D array of that length.
One shape dimension can be -1. In this case, the value is
inferred from the length of the array and remaining dimensions.
merge_chunks : bool, default True
Whether to merge chunks using the logic in :meth:`dask.array.rechunk`
when communication is necessary given the input array chunking and
the output shape. With ``merge_chunks==False``, the input array will
be rechunked to a chunksize of 1, which can create very many tasks.
limit: int (optional)
The maximum block size to target in bytes,
if freedom is given to choose
Notes
-----
This is a parallelized version of the ``np.reshape`` function with the
following limitations:
1. It assumes that the array is stored in `row-major order`_
2. It only allows for reshapings that collapse or merge dimensions like
``(1, 2, 3, 4) -> (1, 6, 4)`` or ``(64,) -> (4, 4, 4)``
.. _`row-major order`: https://en.wikipedia.org/wiki/Row-_and_column-major_order
When communication is necessary this algorithm depends on the logic within
rechunk. It endeavors to keep chunk sizes roughly the same when possible.
See :ref:`array-chunks.reshaping` for a discussion the tradeoffs of
``merge_chunks``.
See Also
--------
dask.array.rechunk
numpy.reshape
"""
# Sanitize inputs, look for -1 in shape
from .slicing import sanitize_index
shape = tuple(map(sanitize_index, shape))
known_sizes = [s for s in shape if s != -1]
if len(known_sizes) < len(shape):
if len(shape) - len(known_sizes) > 1:
raise ValueError("can only specify one unknown dimension")
# Fastpath for x.reshape(-1) on 1D arrays, allows unknown shape in x
# for this case only.
if len(shape) == 1 and x.ndim == 1:
return x
missing_size = sanitize_index(x.size / reduce(mul, known_sizes, 1))
shape = tuple(missing_size if s == -1 else s for s in shape)
if np.isnan(sum(x.shape)):
raise ValueError(
"Array chunk size or shape is unknown. shape: %s\n\n"
"Possible solution with x.compute_chunk_sizes()" % str(x.shape)
)
if reduce(mul, shape, 1) != x.size:
raise ValueError("total size of new array must be unchanged")
if x.shape == shape:
return x
meta = meta_from_array(x, len(shape))
name = "reshape-" + tokenize(x, shape)
if x.npartitions == 1:
key = next(flatten(x.__dask_keys__()))
dsk = {(name,) + (0,) * len(shape): (M.reshape, key, shape)}
chunks = tuple((d,) for d in shape)
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])
return Array(graph, name, chunks, meta=meta)
# Logic or how to rechunk
din = len(x.shape)
dout = len(shape)
if not merge_chunks and din > dout:
x = x.rechunk({i: 1 for i in range(din - dout)})
inchunks, outchunks = reshape_rechunk(x.shape, shape, x.chunks)
# Check output chunks are not too large
> max_chunksize_in_bytes = np.prod([max(i) for i in outchunks]) * x.dtype.itemsize
E RuntimeWarning: overflow encountered in long_scalars
dask\array\reshape.py:235: RuntimeWarning
|
According to this stackoverflow answer, They suggest using this instead of from functools import reduce
import operator
reduce(operator.mul, [1,2,3,4], 1) |
…perator mul instead
…multiple dimensions
|
I think I've fixed the test errors now @ncclementi |
|
Hooray! things work. I have only two small comments: The docs are not building properly, I wonder if that could get fix by merging main, unless you've tried that and it's a different problem.
Nice you found a workaround this, I wonder if in the future (when deprecating python 3.7) we would desire to use |
I don't think that's necessary, there's no particular evidence to suggest I wouldn't mind if someone changed it later on, but I also don't think we need to worry about tracking this as a follow up task. I don't think it's that important. |
|
I've merged |
I don't have anyone particular in mind. @jrbourbeau is around fairly frequently, and is listed on both the dask/maintainer and dask/array teams. So perhaps he might like to look over it, or suggest someone else appropriate. |
|
@jsignell would you have time to take a look at this? |
|
@martindurant maybe this one fits your interests? |
|
Sorry I missed the earlier ping @GenevieveBuckley I thought I'd be around more than ended up happening this week. I'm looking this over now. |
|
I don't understand why the dask dataframe tests are failing on Windows with python 3.7. I don't think it has anything to do with this PR? I've merged the main branch in to see if that would help, but it hasn't resolved everything. |
|
I agree that the failing tests are unrelated. They are also showing up on main. |
|
Thanks for sticking with this @GenevieveBuckley! This is now in :) |
| ], | ||
| ) | ||
| def test_reshape_avoids_large_chunks(shape, chunks, reshape_size): | ||
| limit = parse_bytes("128MiB") |
There was a problem hiding this comment.
Sorry, just getting around to looking at this now. IIUC it looks like this limit isn't being passed down to reshape, so this test is checking the default limit, but not a user-specified one. Looking a bit more, we should probably add a limit= keyword to Array.reshape as well as the top-level reshape function
There was a problem hiding this comment.
Also, maybe this line should use config.get("array.chunk-size") in case the default value of 128 MiB changes in the future
There was a problem hiding this comment.
These are all good suggestions, I've opened #8494 to include them



Limits the maximum chunk size when reshaping dask arrays.
black dask/flake8 dask/isort dask