Skip to content

Limit max chunk size when reshaping dask arrays - #8124

Merged
jsignell merged 18 commits into
dask:mainfrom
GenevieveBuckley:issue-8110
Dec 14, 2021
Merged

jsignell merged 18 commits into
dask:mainfrom
GenevieveBuckley:issue-8110

Conversation

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

Limits the maximum chunk size when reshaping dask arrays.

Comment thread dask/array/reshape.py Resolved
@dcherian

dcherian commented Sep 7, 2021 •

Copy link
Copy Markdown
Collaborator

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)

I get
image

If we instead provide inchunks as previous_chunks, it then preserves the chunking along the first two axes which seems desirable to me (and what I expected)

image

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

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.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I get
image

If we instead provide inchunks as previous_chunks, it then preserves the chunking along the first two axes which seems desirable to me (and what I expected)

image

I did notice this. I don't have a good sense of the costs/benefits though.

I'm not entirely sure whether it makes sense to set previous_chunks=inchunks (in terms of the code logic, I'm not discussing whether the result is desirable or not right now)

For this particular example:

  1. If previous_chunks=outchunks, we get the chunk structure shown above that you didn't really like
  2. If previous_chunks=None or previous_chunks=inchunks, then we get your preferred chunk structure

In the second case, it seems like we're effectively ignoring the work done by the reshape_rechunk function, and I don't know enough about that function to properly understand the potential pitfalls of ignoring it.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

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:

  • it's not as concise as using the normalize_chunks function
  • odd things happen to the chunks if the input chunksize was an odd number (you get alternating chunks, with the size differing by one pixel along one of the dimensions)

@dcherian

dcherian commented Sep 8, 2021

Copy link
Copy Markdown
Collaborator

I'm not entirely sure whether it makes sense to set previous_chunks=inchunks

🤦🏾 you're right.

outchunks is ((300,), (180,), (18483, 18483, 18483, 18483)) before normalizing, so we just need to preserve that. This seems to work. IT might only make sense when axes are being combined?

	outchunks = normalize_chunks(
            [outchunks[0], outchunks[1], "auto"],
            shape=shape,
            limit=limit,
            dtype=x.dtype,
            previous_chunks=outchunks,
        )

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I'm not entirely sure whether it makes sense to set previous_chunks=inchunks

🤦🏾 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)

outchunks is ((300,), (180,), (18483, 18483, 18483, 18483)) before normalizing, so we just need to preserve that. This seems to work. IT might only make sense when axes are being combined?

	outchunks = normalize_chunks(
            [outchunks[0], outchunks[1], "auto"],
            shape=shape,
            limit=limit,
            dtype=x.dtype,
            previous_chunks=outchunks,
        )

This works for you, but is not a generalized solution we can use across the board. People reshape arrays in all kinds of ways.

@dcherian

dcherian commented Sep 8, 2021 •

Copy link
Copy Markdown
Collaborator

but is not a generalized solution we can use across the board.

Right the idea there is that we tell normalize_chunks to only change chunksize for the new axes instead of passing "auto" for all axes. But I don't think that works either

Looking at this a little more, it looks like this logic might have to live in reshape_rechunk. The key seems to be determining input and output chunksizes so that the reshape operation can be applied blockwise. So it looks like we can't arbitrarily change either inchunks or outchunks independently.

@ncclementi

ncclementi commented Oct 14, 2021 •

Copy link
Copy Markdown
Member

@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?

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

@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.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I spent some time today looking at whether we could modify reshape_rechunk to handle this logic. I'm not convinced that's the best place for it.

Short summary: we could address the issue for this particular problem by running the reshape_rechunk logic over the axes in the opposite order (reshape_rechunk looks at the axes in order from the last to the first, we could go the other way), but that's not a fully generalized solution (even if we check for each individual problem whether it makes more sense to go through the axes forwards or backwards, for some nether will work best).

Also, although this problem only pops up when din < dout (when combining smaller axes dimensions into a larger one), you can't really test whether this will put us over the chunk size limit, because you need to know all the other chunk dimensions too & those aren't all computed yet. So I think the idea in this PR, to have a retrospective sanity check makes more sense.

@GenevieveBuckley

GenevieveBuckley commented Nov 26, 2021 •

Copy link
Copy Markdown
Contributor Author

outchunks is ((300,), (180,), (18483, 18483, 18483, 18483)) before normalizing, so we just need to preserve that. This seems to work. IT might only make sense when axes are being combined?

	outchunks = normalize_chunks(
            [outchunks[0], outchunks[1], "auto"],
            shape=shape,
            limit=limit,
            dtype=x.dtype,
            previous_chunks=outchunks,
        )

I think I have an idea for how we can implement this idea in a more general way.

(Note to self: on Monday try hacky idea with collections counter to find the matching dimensions) EDIT: Was quicker than I thought, just tried it now.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Looks pretty good to me now!

image

@GenevieveBuckley

GenevieveBuckley commented Nov 26, 2021 •

Copy link
Copy Markdown
Contributor Author

I'm happy with this, I think it's ready for final review/merge now. Nice way to end the week! 🎉

@ncclementi

Copy link
Copy Markdown
Member

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 dcherian left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @GenevieveBuckley this is exciting!

Comment thread dask/array/reshape.py Resolved
Comment thread dask/array/reshape.py Outdated
Comment on lines +251 to +252
# Decrememt counter if multiple same-size matches exist
elif matching_chunks[out] > 1:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
# Decrememt counter if multiple same-size matches exist
elif matching_chunks[out] > 1:
# Decrement counter if multiple same-size matches exist
else:

Comment thread dask/array/reshape.py Resolved
Comment thread dask/array/reshape.py
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread dask/array/tests/test_array_core.py Resolved
Co-authored-by: Deepak Cherian <[email protected]>
@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

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?

Thanks for flagging this @ncclementi
I'll have a think about this, but I don't have a Windows computer on hand to test things with, so that might be a bit limiting.

@GenevieveBuckley

GenevieveBuckley commented Nov 30, 2021 •

Copy link
Copy Markdown
Contributor Author

Update: the integer overflow is happening when we multiply many potentially very large numbers together. Switching to use math.prod instead of numpy.prod looks like it might fix the issue here.

EDIT: Huh, apparently the math module isn't finding a prod function on Windows. I'm in a meeting now, but will look into this more tomorrow.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

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


@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Update: the integer overflow is happening when we multiply many potentially very large numbers together. Switching to use math.prod instead of numpy.prod looks like it might fix the issue here.

EDIT: Huh, apparently the math module isn't finding a prod function on Windows. I'm in a meeting now, but will look into this more tomorrow.

According to this stackoverflow answer, math.prod is only available for python 3.8 and above, so that's why all our python 3.7 tests are failing.

They suggest using this instead of math.prod:

from functools import reduce
import operator

reduce(operator.mul, [1,2,3,4], 1)

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I think I've fixed the test errors now @ncclementi

@ncclementi

Copy link
Copy Markdown
Member

Hooray! things work.
Thanks @GenevieveBuckley we should probably ping a maintainer to get this in. Do you have someone in mind to review this?

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.

According to this stackoverflow answer, math.prod is only available for python 3.8 and above, so that's why all our python 3.7 tests are failing.

Nice you found a workaround this, I wonder if in the future (when deprecating python 3.7) we would desire to use math.prod and maybe leave a comment to change this when the time comes, or leave a comment to say why math.prod is not used in case someone tries to change it back.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

According to this stackoverflow answer, math.prod is only available for python 3.8 and above, so that's why all our python 3.7 tests are failing.

Nice you found a workaround this, I wonder if in the future (when deprecating python 3.7) we would desire to use math.prod and maybe leave a comment to change this when the time comes, or leave a comment to say why math.prod is not used in case someone tries to change it back.

I don't think that's necessary, there's no particular evidence to suggest reduce(mul, ... is not as good, it's just slightly less readable. And functools reduce gets used all over the place in Dask, so it's not unreasonable to expect developers should be able to work out the meaning.

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.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

I've merged main into this branch, let's see if that fixes the docs build errors.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

Hooray! things work.
Thanks @GenevieveBuckley we should probably ping a maintainer to get this in. Do you have someone in mind to review this?

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.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

@jsignell would you have time to take a look at this?

@GenevieveBuckley

Copy link
Copy Markdown
Contributor Author

@martindurant maybe this one fits your interests?

Comment thread dask/array/reshape.py Resolved
@jsignell

Copy link
Copy Markdown
Member

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.

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

Copy link
Copy Markdown
Contributor Author

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.

@jsignell

Copy link
Copy Markdown
Member

I agree that the failing tests are unrelated. They are also showing up on main.

@jsignell
jsignell merged commit 51a830c into dask:main Dec 14, 2021
@jsignell

Copy link
Copy Markdown
Member

Thanks for sticking with this @GenevieveBuckley! This is now in :)

],
)
def test_reshape_avoids_large_chunks(shape, chunks, reshape_size):
limit = parse_bytes("128MiB")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Also, maybe this line should use config.get("array.chunk-size") in case the default value of 128 MiB changes in the future

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These are all good suggestions, I've opened #8494 to include them

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