Skip to content

Implement task-based array shuffle - #11262

Merged
phofl merged 17 commits into
dask:mainfrom
phofl:array-shuffle
Aug 5, 2024
Merged

phofl merged 17 commits into
dask:mainfrom
phofl:array-shuffle

Conversation

@phofl

@phofl phofl commented Jul 31, 2024

Copy link
Copy Markdown
Collaborator

This is a first rough implementation of an array-based shuffle that uses the task implementation. Not polished and probably has a few edge cases that aren't covered yet.

TLDR: We are preserving chunk sizes (roughly) compared to take but we still have a very large graph, which strains the scheduler pretty heavily. Subsequent results are easier to process though in case of a random access pattern because the chunks stay reasonable. An improvement over random access take generally speaking, but still not very good

Let's mess around with a toy example:

import dask.array as da

n = 1500
arr = da.random.random((n, n, n), chunks=
(50, 50, 50))
arr
Screenshot 2024-07-31 at 11 57 00

Our indexer has a random access pattern (and we access 5 elements at a time, but we could do random stuff here).

import numpy as np
from dask.core import flatten

idx = np.arange(0, n)
np.random.shuffle(idx)

indexer = []
for i in range(0, n, 5):
    indexer.append(idx[i:i+5].tolist())
take_indexer = list(flatten(indexer))

indexer
result = arr.shuffle(indexer, axis=1)
result
Screenshot 2024-07-31 at 11 57 21

Shuffling keeps the number of chunks consistent. Doing the equivalent take blows up the number of chunks

expected = arr[slice(None), take_indexer, slice(None)]
expected
Screenshot 2024-07-31 at 11 57 35

The number of tasks are in the same ballpark though, the growth is still exponential in a case of an all to all pattern.

Screenshot 2024-07-31 at 11 57 54

Generating close to a million tasks for a 27k chunks array is not great.

@phofl
phofl marked this pull request as draft July 31, 2024 09:59
@fjetter

fjetter commented Jul 31, 2024

Copy link
Copy Markdown
Member

I assume this is pretty much equivalent to arr.take(...).rechunk(arr.chunks) isn't it?

@github-actions

github-actions Bot commented Jul 31, 2024 •

Copy link
Copy Markdown
Contributor

Unit Test Results

See test report for an extended history of previous test failures. This is useful for diagnosing flaky tests.

     15 files  ±  0       15 suites  ±0   3h 29m 59s ⏱️ + 2m 54s
 13 140 tests + 11   12 072 ✅ + 11   1 068 💤 ±0  0 ❌ ±0 
162 938 runs  +143  140 150 ✅ +145  22 788 💤  - 2  0 ❌ ±0 

Results for commit 281ff9b. ± Comparison against base commit f95007b.

♻️ This comment has been updated with latest results.

@phofl

phofl commented Jul 31, 2024

Copy link
Copy Markdown
Collaborator Author

I assume this is pretty much equivalent to arr.take(...).rechunk(arr.chunks) isn't it?

roughly, we can be smarter with respect to how many tasks we create, i.e. if you have a 6 x 6 array with 3 x 3 chunks and an indexer on axis 1 of

[[0, 3, 1], [4, 2, 5]]

take would create a task per element, because they aren't in order. We can sort and then re-order to only slice once per chunk. Shuffle also ensures that a group of elements ends up in the same chunk.

That said, worst case task graph size is roughly the same yes.

@mrocklin

Copy link
Copy Markdown
Member

A couple questions / thoughts (but I haven't thought about this as much, so feel free to disregard)

Multi-stage

Let's imagine a pathological case where we have two chunks and and indexer that switches back and forth between them

chunks = ((100000, 100000),)
indexer = [0, 100000, 1, 100001, 2, 100002]

Optimally we should be able to do this in around 6 tasks I think, assuming we're willing to do the take in a couple of stages, in worst case we'll do it in 200,000 tasks. What happens with this implementation?

Also, it may not make sense to invest in the multi-stage implementation here for various reasons, I'm just making sure that we have that option on our radar.

Lots of Rechunking

If we did the multi-stage thing, then suddenly we're strongly incentivized to rechunk ahead of time to make the take dimension very large. This could be useful for two reasons:

  1. The input chunk sizes are too small (I think that we should be willing to override small input chunk sizes for intermediate results)
  2. The input chunking direction isn't optimal for the take operation

Just some thoughts. It could be that we've already been thinking about these or that they're bad for some reason. No need to anchor on them, just bringing them up in case they're useful.

@mrocklin

Copy link
Copy Markdown
Member

(I think the answer to my question is in @phofl's last comment, but I felt that my example here helped make the difference a bit more stark)

@phofl

phofl commented Jul 31, 2024

Copy link
Copy Markdown
Collaborator Author

Optimally we should be able to do this in around 6 tasks I think, assuming we're willing to do the take in a couple of stages, in worst case we'll do it in 200,000 tasks. What happens with this implementation?

We do this in 6 tasks at the moment. We sort the indexer and then resort after selecting the data.

@mrocklin

Copy link
Copy Markdown
Member

We do this in 6 tasks at the moment. We sort the indexer and then resort after selecting the data

Oh grand!

So I guess we're experiencing here a task blowup of shape/chunkshape for the take dimension, in this case that's 1500/50 == 30x. So 27k * 30 == ~800k, which tracks. This is a lot better than the number of chunk transitions in the indexer, which is what we had before. This seems great!

@phofl

phofl commented Jul 31, 2024

Copy link
Copy Markdown
Collaborator Author

So I guess we're experiencing here a task blowup of shape/chunkshape for the take dimension, in this case that's 1500/50 == 30x. So 27k * 30 == ~800k, which tracks. This is a lot better than the number of chunk transitions in the indexer, which is what we had before. This seems great!

Yes that's correct, that should be the upper bound.

Just to align expectations: This is still pretty bad, less bad than before, but far away from actually being good

@dcherian

Copy link
Copy Markdown
Collaborator

Looks like the approach in #3901?

@phofl

phofl commented Jul 31, 2024

Copy link
Copy Markdown
Collaborator Author

Yep very similar approach. Task graph will be smaller but both leverage the same technique.

This is not the state that I would like to end up in though.

A more general question: Is this the kind of API could be used in Xarray for a group by-transform or group by-reduce if you don't want to do a tree reduction? Basically what we discussed here: pydata/xarray#9220

@phofl phofl changed the title Array shuffle Implement task-based array shuffle Aug 1, 2024
@phofl
phofl marked this pull request as ready for review August 1, 2024 15:29
@phofl

phofl commented Aug 1, 2024

Copy link
Copy Markdown
Collaborator Author

This should be ready for a closer look.

@dcherian is this an API that would satisfy the XArray requirements for a groupby - transform approach?

We can add the P2P backend in the background after we align on how we want to process things

@phofl

phofl commented Aug 1, 2024 •

Copy link
Copy Markdown
Collaborator Author

With #11267, take performance is a lot better:

https://github.com/coiled/benchmarks/actions/runs/10202090066/artifacts/1765715083

def _create_indexer(n, chunk_n):
    idx = np.arange(0, n)
    np.random.shuffle(idx)

    indexer = []
    for i in range(0, n, chunk_n):
        indexer.append(idx[i : i + chunk_n].tolist())
    return indexer


def test_take(small_client, new_array):
    n = 2000
    chunk_n = 250
    x = da.random.random((n, n, n), chunks=(chunk_n, chunk_n, chunk_n))
    indexer = list(flatten(_create_indexer(n, chunk_n)))
    x[:, indexer, :].sum().compute()

This is the largest array that still works with the current take implementation, everything larger just kills the cluster

Screenshot 2024-08-01 at 18 44 43

@hendrikmakait
hendrikmakait self-requested a review August 2, 2024 12:51
Comment thread dask/array/_shuffle.py
indexer: list[list[int]]
The indexer that determins which elements along the dimension will end up in the
same chunk. Multiple groups can be in the same chunk to avoid fragmentation, but
each group will end up in exactly one chunk.

@dcherian dcherian Aug 2, 2024 •

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 behaviour is problematic for

import dask.array
import xarray as xr

time = xr.date_range("2001-01-01", "2010-01-01", freq="D")
ds = xr.Dataset(
    {
        "data": (
            ("x", "y", "time"),
            dask.array.random.random((10000, 1000, len(time)), chunks=(-1, -1, 1)),
        )
    },
    coords={"time": ("time", time)},
)
ds.resample(time="Y")._group_indices

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Can you say a bit more?

Is the problem that the chunks will become too large or that we fuse multiple groups together?

If the latter, then we could add control for this behavior to turn fusion of groups off.

If chunks that are too large:
Would your preferred alternative be to have one group in multiple chunks along the time dimension in your example or split the other dimensions into multiple chunks instead of -1 and -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.

one group in multiple chunks along the time dimension in your

I feel like its preferrable to do this and then have the user do the rechunk-to-one-block-while-adjusting-others.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Is the user in this case xarray or users from xarray?

When we put one group into multiple chunks, all chunks that have parts of the group should be in consecutive chunks, so that

x = x.rechunk(("x": "foo", "y": "bar", "time": 365})

would put all values of said group into a single chunk in your example?

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.

^ yes. Once the groups are in order, we can use slicing to extract each group and pass to the user.

Basically it'd be nice to preserve the cases where the map approach works nicely today.

array.resample(time="Y").reduce(np.mean)

Today this dispatches to dask.array.mean with each group split across multiple chunks, so we get the tree reduction.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep ok, got it. This is what you would use take for after #11267 (what we discussed in the other issue). take uses the same algorithm under the hood but is not placing everything into a single group.

Comment thread dask/array/_shuffle.py Resolved
Comment thread dask/array/core.py Resolved
Comment thread dask/array/tests/test_shuffle.py Outdated
chunks = (3, 2, 3)
with dask.config.set({"array.shuffle.chunksize-tolerance": 1}):
result = darr.shuffle(indexer, axis=1)
expected = arr[:, list(flatten(indexer))]

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.

nit: I'd personally find this test more readable if we just replaced list(flatten(indexer)) with the corresponding literal values.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

sounds good

Comment thread dask/array/tests/test_shuffle.py Outdated
assert result.chunks[1] == chunks


def test_shuffle_config_tolerance(arr, darr):

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.

Should we test different tolerances?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

sure

Comment thread dask/dask-schema.yaml
description: |
Tolerance for the shuffle algorithm when creating output chunks.
Default is 1.25. This means that the shuffle algorithm can exceed
the average input chunk size along this dimension by 25%.

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.

Do we also impose a lower limit? When thinking about tolerances, I think about limits in both directions. If it's only an upper limit, it might make sense to make this explicit in the naming.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

only upper,

Comment thread dask/array/_shuffle.py
----------
x: dask array
Array to be shuffled.
indexer: list[list[int]]

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.

nit: It might be safer to convert the indexer to a tuple[tuple[int]] internally to avoid unintentional modification.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I am messing with list methods later, do you want to protect against modifying the input?

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.

do you want to protect against modifying the input?

Yes, I was wondering if that would be helpful here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I would rather copy in this case, you ok with?

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.

sounds good!

Comment thread dask/array/_shuffle.py Resolved
Comment thread dask/array/_shuffle.py Resolved
Comment thread dask/array/_shuffle.py
this_slice = slices.copy()

# Cache the takers to allow de-duplication when serializing
# Ugly!

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.

Suggested change
# Ugly!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Hm I wanted to express that this is necessary but very ugly, so this is kind of intended

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.

Ah, makes sense.

@hendrikmakait hendrikmakait left a comment

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.

LGTM assuming CI is green. Thanks, @phofl

Comment thread dask/array/_shuffle.py
----------
x: dask array
Array to be shuffled.
indexer: list[list[int]]

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.

sounds good!

Comment thread dask/array/_shuffle.py
this_slice = slices.copy()

# Cache the takers to allow de-duplication when serializing
# Ugly!

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.

Ah, makes sense.

@dcherian

dcherian commented Aug 5, 2024

Copy link
Copy Markdown
Collaborator

s this an API that would satisfy the XArray requirements for a groupby - transform approach?

I think this gets part of the way there, yes. pydata/xarray#9220 (comment)

@phofl
phofl merged commit 8fa8d2e into dask:main Aug 5, 2024
@phofl
phofl deleted the array-shuffle branch August 5, 2024 15:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants