Skip to content

Changes to chunking behaviour in dask==2.26.0 #6646

Closed

Description

@JSKenyon

What happened:
One of my projects broke, fairly catastrophically, after updating to dask==2.26.0. In particular, chunk sizes of arrays get mangled in completely mysterious ways. This does not happen when using dask<=2.25.0.

What you expected to happen:
I would have expected no change to existing chunking behaviour.

Minimal Complete Verifiable Example:
This issue aims to get more dask-knowledgeable eyes on this issue on xarray.

Environment:

  • Dask version: 2.26.0
  • Python version: 3.6.9
  • Operating System: Pop!_OS 18.04 LTS
  • Install method (conda, pip, source): pip

Activity

  1. JSKenyon commented on Sep 16, 2020

    @JSKenyon
    ContributorAuthor

    I have managed to reproduce on the linked issue.

  2. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    My initial guess is that this is from #6514. Do you have time to verify that?

  3. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    I've at least verified that the example provided in pydata/xarray#4428 (comment), so odds are pretty high that #6514 is to blame.

    I'll need to think through how best to handle this. (#6270 / pydata/xarray#4112 for background). cc @dcherian if you have thoughts they'd be appreciated.

  4. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    Here's a Dask-only example

    import dask.array as da
    import numpy as np
    
    data = da.random.random([10000, 16, 4], chunks=(10000, 16, 4))
    dtype = np.float32
    
    upsample_factor = 1024 // data.shape[1]
    selection = np.repeat(np.arange(data.shape[1]), upsample_factor)
    print("before: ", data)
    
    result = data[:, selection, :]
    print("after : ", result)

    2.25.0

    before:  dask.array<random_sample, shape=(10000, 16, 4), dtype=float64, chunksize=(10000, 16, 4), chunktype=numpy.ndarray>
    after :  dask.array<getitem, shape=(10000, 1024, 4), dtype=float64, chunksize=(10000, 1024, 4), chunktype=numpy.ndarray>
    

    Latest:

    before:  dask.array<random_sample, shape=(10000, 16, 4), dtype=float64, chunksize=(10000, 16, 4), chunktype=numpy.ndarray>
    after :  dask.array<getitem, shape=(10000, 1024, 4), dtype=float64, chunksize=(10000, 342, 4), chunktype=numpy.ndarray>
    
  5. lazarillo commented on Sep 16, 2020

    @lazarillo

    Could this be related to #6640 that I just submitted?

    Somehow it seems like they are similar.

  6. dcherian commented on Sep 16, 2020

    @dcherian
    Collaborator

    It's definitely #6514, xarray's sortby ends up indexing with a list of ints....

    I don't have any good ideas here.

    Are there other places where dask automatically rechunks to get nice chunk sizes without being explicitly asked to do so? Maybe dask users should be expected to explicitly ask for no automatic rechunking:

    with dask.do_not_rechunk():
        subset = dask_array[[1, 2, 3]]

    or maybe the reverse (ask for automatic rechunking because the next line could have bad consequences). Is this the most backward compatible option?

    with dask.auto_rechunk():
        ...

    cc @shoyer

  7. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    @lazarillo no, this is specific to dask array.

  8. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    Are there other places where dask automatically rechunks to get nice chunk sizes without being explicitly asked to do so?

    I think da.reshape might be one (though I have that PR for enabling control over that). There might be others.

    Do we think that these two usecases (pydata/xarray#4112, pydata/xarray#4428) demonstrate fundamentally incompatible requirements, or is there some way to distinguish them? Maybe a rule like "if my chunks already exceed the array.chunk-size, don't make them smaller"?

    Edit: I haven't checked if that rule applies to pydata/xarray#4428 though.

  9. mrocklin commented on Sep 16, 2020

    @mrocklin
    Member

    Are there other places where dask automatically rechunks to get nice chunk sizes without being explicitly asked to do so?

    I think da.reshape might be one (though I have that PR for enabling control over that). There might be others.

    gufuncs, fft maybe. I would like to do this more with operations like tensordot and such. I would love to know more about constraints that people have.

  10. dcherian commented on Sep 16, 2020

    @dcherian
    Collaborator

    rechunking in reshape seems mostly unavoidable though.

    Maybe a rule like "if my chunks already exceed the array.chunk-size, don't make them smaller"?

    Maybe array.chunk-size isn't a good metric. For example, I don't think many xarray users are aware of array.chunk-size (perhaps this isn't a consideration for dask?)

    Can we compare expected-chunk-size to maximum-chunk-size for this particular array? That way automatic rechunking does not make things worse than they currently are. We could also pass maximum-chunk-size to rechunk and avoid creating many more chunks/tasks

  11. JSKenyon commented on Sep 16, 2020

    @JSKenyon
    ContributorAuthor

    For what it is worth, I don't believe that dask should do this without explicitly being told to. I only provided an excerpt on the linked issue, but consider the case where you have a single xarray.Dataset holding several dask arrays, indexed with by the same values but containing different data types. The behaviour that has been introduced means that an xarray.sel will produce different chunk sizes (and potentially counts) based on the data type. This leads to completely inconsistently chunked arrays throughout the dataset. It is this which broke my code base. I personally think @dcherian's suggestion involving a dask.auto_rechunk context manager seems sensible if you know you are about to do something dangerous.

  12. TomAugspurger commented on Sep 16, 2020

    @TomAugspurger
    Member

    For what it is worth, I don't believe that dask should do this without explicitly being told to.

    Did you see the original issue pydata/xarray#4112? In that issue we determined that we didn't want large chunks to be created when slicing with a list of integers.

  13. JSKenyon commented on Sep 16, 2020

    @JSKenyon
    ContributorAuthor

    I did glance over the issue, but it is a bit late my time to dig in. Will go through it more thoroughly in the morning. My instinct is that this change is surprising - I did something, and the result was not what it was before or what I expected. I did go through my own code and try to quash the problems this change introduced, but it forces me to repeatedly do xds.chunk operations to coerce the chunks to what I expect. If this is what is expected going forward, I can accept that, but I had a very frustrating day trying to diagnose why the chunking kept going awry between select and sort operations. I do have large chunks in this specific use case, but is because the data should not be split - the numerical operations which are done subsequently (in Numba via blockwise) require the entire chunk.

    The solution involving chunk size offered on the xarray issue might be sufficient to restore the behaviour I had previously. That said, I am a little surprised that this hasn't broken any other workflows.

  14. JSKenyon commented on Sep 17, 2020

    @JSKenyon
    ContributorAuthor

    @TomAugspurger Running the example given by the OP in pydata/xarray#4112 still gives unbalanced chunks (with dask==2.26.0), at least on my system. I am now a bit confused, because I thought this change solved that?

  15. TomAugspurger commented on Sep 17, 2020

    @TomAugspurger
    Member
  16. 5 remaining items

  17. TomAugspurger commented on Sep 22, 2020

    @TomAugspurger
    Member

    I'm still not terribly happy with hiding such potentially important behavior behind a config option, but I really don't see a way to support both usecases cleanly.

    If we go the context-manager route, then what should the default be (split large chunks, match the chunking implied by indexer?). I think the safest is to split by default, since a user doing arr[indexer].rechunk(desired) should always work if we split large chunks. But if arr[indexer] creates a too large chunk then .rechunk() won't work, since the parent task would have failed.

  18. kefirbandi commented on Sep 22, 2020

    @kefirbandi

    Hi Guys, I admit I didn't have time to read all of the above comments, but my performance dropped drastically between 2.25.0 and 2.26.0. I am loading large multifile netcdf files with xarray. With 2.25.0 all netcdf files fit in one chunk.

    WIth 2.26.0 chunk size is much smaller than the original. In my case the xarray dataset .load() time increased from ~40 sec to ~22 minutes.

    If after I (lazy) load with xarray, but before I do the eager load (with .load()) I do a rechunking to the pre 2.26.0 chunk size, then I get the 2.25.0 performance.

  19. TomAugspurger commented on Sep 22, 2020

    @TomAugspurger
    Member

    @kefirbandi do you have an example of that? Is it the loading from disk that's slow, or subsequent operations?

  20. kefirbandi commented on Sep 22, 2020

    @kefirbandi

    @kefirbandi do you have an example of that? Is it the loading from disk that's slow, or subsequent operations?

    It is not easy to give an example as I can't provide the netcdf files. What I did in xarray was
    open

    1. open_mf_netcdf, to lazy load the data, then
    2. .sel(), to reduce the size by selecting certain values from certain dimensions and then
    3. .load() to fetch the restricted data to memory

    It was the last step (3) that got a slowdown between 2.25 and 2.26
    But if I reset the chunksize between steps 1 and 2 then 3 takes the same time as it did in 2.25

  21. dcherian commented on Sep 22, 2020

    @dcherian
    Collaborator

    sel(), to reduce the size by selecting certain values from certain dimensions and then

    I guess the new chunk sizes at this step are badly aligned with how the dataset is split among files on disk? This example suggests that we should use the existing chunks tuple as a hint instead of array.chunk-size

    I think the safest is to split by default,

    I agree. It's irrecoverable otherwise as you point out

  22. kefirbandi commented on Sep 22, 2020

    @kefirbandi

    sel(), to reduce the size by selecting certain values from certain dimensions and then

    I guess the new chunk sizes at this step are badly aligned with how the dataset is split among files on disk? This example suggests that we should use the existing chunks tuple as a hint instead of array.chunk-size

    In my case I have 3 dimensions: date, F1 and F2. On the disk I have one file for each date. Size of F1 and F2 are ~3000.
    When I load with 2.26.0 the chunksize will be 1*150*150 (roughly). With 2.25.0 it was 1*3000*3000, which was is what I expected.
    Then I select along F1 and F2 dimensions (but not the date) and I end up having chunks of 1*1*1.
    (But this is not consistent. In certain cases I end up with 1*3*3 or 1*4*4, although the code is the same)

  23. TomAugspurger commented on Sep 22, 2020

    @TomAugspurger
    Member

    I think the safest is to split by default,

    I agree. It's irrecoverable otherwise as you point out

    Undercutting myself here, I guess an option would be for users to do their indexing operation, have it blow up on them, search for how to fix it, and hopefully find the config option.

    This example suggests that we should use the existing chunks tuple as a hint instead of array.chunk-size

    This is probably worth exploring, but I can't seem to make it work in my head. Earlier I was struggling with how to relate the new chunksize to the old chunksize, but maybe we should be looking at the number of chunks, rather than the size?

    Previously, the rule was something like array[indexer] will have something like one output block per input block touched (assuming a sorted indexer). I can't figure out a rule that would preserve that really, other than perhaps special casing the just one chunk case (if you do array[indexer] on an axis with one chunk then we keep it as one chunk).

  24. JSKenyon commented on Sep 23, 2020

    @JSKenyon
    ContributorAuthor

    Undercutting myself here, I guess an option would be for users to do their indexing operation, have it blow up on them, search for how to fix it, and hopefully find the config option.

    My feeling is that it is ok for an operation to fail/blow-up if dask is doing precisely what it is told to do. I think that there is danger in attempting to be too flexible.

    If my understanding of the situation is correct, in order to address pydata/xarray#4112, the behaviour of indexing was changed to split the problem into smaller chunks (based on array.chunk-size). This prevents individual chunks from exploding in memory, but has the side effect of changing the chunking of the result.

    I don't know enough about the internals of everything to know which of the following would be possible, but these are the ideas that have occurred to me:

    1. Add a kwarg to functions which use indexing of the form allow_rechunking=True/False. That way even if the default is to split (True), reverting to the old behaviour is as simple as adding a kwarg.
    2. Add an extra layer that automatically rechunks the output to be compatible with the input. This would mean that things can be sliced and rechunked arbitrarily internally, but the returned dask.Array object would be unchanged. I imagine that there is overhead to this approach, but it would likely "just work".
    3. Add a context manager/config option in line with @dcherian's suggestion which either disables rechunking in some limited scope, or globally, as desired (see Behaviour change in xarray.Dataset.sortby/sel between dask==2.25.0 and dask==2.26.0 pydata/xarray#4428 (comment), suggesting that this is already done/doable).

    As mentioned, I cannot say which approach would be easiest/best, but my instinct is that point 2 could potentially alleviate the tension between the two issues. This means that dask can do its best to produce a result which won't explode in memory, but the user can still rely on the resulting dask.Array having the expected number of chunks. For cases like pydata/xarray#4112, the "expected" output chunking could be derived from the highest resolution chunking on the input, as I imagine that there is less user expectation regarding the chunking of the output (though it would be sensible for both outputs to share chunking for alignment reasons).

  25. TomAugspurger commented on Sep 23, 2020

    @TomAugspurger
    Member

    This prevents individual chunks from exploding in memory, but has the side effect of changing the chunking of the result.

    You're understanding is exactly correct, but the "side-effect" is more of a direct consequence :)

    Add a kwarg to functions which use indexing of the form allow_rechunking=True/False. That way even if the default is to split (True), reverting to the old behaviour is as simple as adding a kwarg.

    We could perhaps do that for dask.array.take, but it wouldn't be an option for array[indexer].

    Add an extra layer that automatically rechunks the output to be compatible with the input.

    Could you expand on this a bit? I don't understand the "automatically rechunk" part (I understand that Dask / the user could .rechunk(), but that would run into the (potentially) too large chunk issue).

    Below you mention "expected number of chunks", but that's a bit unclear (to me). I think your expectation (confirmed by previous releases) is that Array[ordered_concrete_list_of_indices] will return one chunk per input chunk on that axis (that is touched by indices). Which is reasonable, but leads to the issue with potentially too large chunks.

    I think @JSKenyon is not the only one expecting / relying on that behavior. So perhaps we make it the default behavior and provide an option to enable this too-large-chunk splitting?

  26. JSKenyon commented on Sep 23, 2020

    @JSKenyon
    ContributorAuthor

    Could you expand on this a bit? I don't understand the "automatically rechunk" part (I understand that Dask / the user could .rechunk(), but that would run into the (potentially) too large chunk issue).

    I think that I have argued myself around on this point. I guess that I wasn't thinking about the upper limit case, where len(indices) >>> len(chunk_axis). It is this case where a one-to-one chunk mapping can fail as without subdivision a result chunk may be incredibly large. I can see the value of the change in dealing with this scenario. That being said, I think that the one-to-one chunking along an axis is the more intuitive default (at least to me, possibly based on expereice with previous verisons). I think that subdividing is a good idea and great option for users with that particular problem, but I also think that having it happen automatically is likely to cause confusion, as it did in my case. I think in this instance it might be ok to rely on users to deal with the problem when it arises, rather than solving it before. Perhaps a warning, similar to the ones printed when an operation increases the number of chunks dramatically, for the case when a chunk would massively increase in size would be sufficient? That way users are informed and can enable subdivision if necessary.

  27. TomAugspurger commented on Sep 23, 2020

    @TomAugspurger
    Member

    I like the suggestion of defaulting to the old behavior (no splitting) but printing a warning if too large of chunks are detected (maybe this should be some factor of array.chunk-size).

    The warning would instruct people to set the config option to split large chunks, or provide some value to disable the warning.

    I'll try to get this implemented later today so it can be ready for Friday's release (cc @jrbourbeau).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions