Skip to content

Optimize tensordot with rechunk #2225

Open

Description

@mrocklin

Dask.array tensordot operations can be made significantly faster by doing an initial rechunk pass, making all axes over which we intend to contract single-chunked.

For example, if we have the following block-chunked arrays:

import dask.array as da
x = da.random.random((500, 500, 500), chunks=(50, 50, 50))
y = da.random.random((500, 100), chunks=(50, 50))

And we want to contract over the 1st and 0th dimensions respectively

da.tensordot(x, y, axes=[1, 0]).visualize()

Then we may want to preemptively rechunk so that those axes have only one chunk as follows:

x2 = x.rechunk((..., 500, ...)).persist()
y2 = y.rechunk((500, ...)).persist()

We may want to contract other axes while we expand these ones to make sure that we don't produce chunks that are too large (and to ensure that the resulting tensordot chunks are not too large). In this case though the outputs are small enough even with a 10x increase in size, so we leave the other dimensions as-is.

x2 = x.rechunk((50, 500, 50)).persist()
y2 = y.rechunk((500, 50)).persist()

This does incur some communication costs up front, but it will generally save us more communication down the line.

So I think the question here is the following:

Given the chunks of both arrays and the axis= argument, how should we rechunk these arrays prior to the normal tensordot call. This should both increase the chunksize in the contracted axes to the full extent and possibly reduce the chunksize of the other dimension based on the expected nbytes of out output of the tensordot call.

Snagged this trick from this talk: https://youtu.be/dcT6c-PrloE?t=1584

cc @jcrist and @shoyer who might find this interesting. cc @pitrou who did the rechunk logic and might be able to recommend something.

Activity

  1. mrocklin commented on Apr 19, 2017

    @mrocklin
    MemberAuthor

    @TomAugspurger if you find yourself with free time you might find this issue interesting. I also think that it is valuable for distributing algorithms that you care about.

  2. mrocklin commented on Jun 1, 2017

    @mrocklin
    MemberAuthor

    @pitrou if you find yourself with some free time you might find this task interesting. The speedups can be substantial and this has relevance for future paid work.

  3. jni commented on Jul 18, 2017

    @jni
    Contributor

    @mrocklin I followed link to this issue from your SciPy talk (which as usual was full of new and exciting things). I just want to point out a related issue: preemptively determining/rechunking the output array. Perhaps with an "out=" kwarg? The use case is computing a (1000, 1000) column correlation matrix from a 100,000 row / 1000 column csv file (let's ignore the format for now ;). After setting chunks to (100000, 1), I couldn't find a way to do this without getting a "number of chunks increasing by factor of 1000" warning.

  4. lsorber commented on Sep 20, 2017

    @lsorber

    This does incur some communication costs up front, but it will generally save us more communication down the line.

    Are there any estimates or measurements of the rechunking cost available at runtime?

    An einsum implementation (#732) with rechunking would be even better, as tensordot could then call that instead.

  5. mrocklin commented on Sep 20, 2017

    @mrocklin
    MemberAuthor

    Are there any estimates or measurements of the rechunking cost available at runtime?

    We know the size of every chunk both before and after. Every task has around 100-300us of overhead.

    An einsum implementation (#732) with rechunking would be even better, as tensordot could then call that instead.

    Are you saying that einsum is likely to be faster than tensordot or that it is more general?

    If you have any interest in implementing einsum then that would be quite welcome.

  6. lsorber commented on Sep 20, 2017

    @lsorber

    We know the size of every chunk both before and after. Every task has around 100-300us of overhead.

    I was mostly referring to the communication cost of rechunking, is there any data available on that?

    I mean that einsum is more general yes, since you can specify both inner and outer products (and it would do singleton expansion -- which tensordot doesn't seem to do?). Since that is the case, it makes sense to design rechunking on the einsum level and have those benefits flow down to tensordot automatically.

    I think dask has a lot of potential and would love to contribute in the near future. Feature requests like this one together with access to some of the more recent scalable linear algebra algorithms could really help scale NumPy work to new levels. I can't promise anything yet though, unfortunately.

  7. mrocklin commented on Sep 20, 2017

    @mrocklin
    MemberAuthor

    I suspect that the performance benefits of using level-3 BLAS operations like GEMM will encourage folks to keep tensordot around. I could be wrong though. This is something that one would have to take up with numpy.

    Communication costs differ based on scheduler. We don't generally have this information while constructing the task graph. In my experience the computation costs of tensordot operations tend to overwhelm the communication costs, particularly when contractions are involved. This is generally true of level-3 blas operations. You can be fairly sloppy.

  8. mrocklin commented on Sep 20, 2017

    @mrocklin
    MemberAuthor

    I think it would be great to have someone pushing on dask.array for numerical linear algebra applications. I care about this topic, but tend not to pursue it personally just because of other work priorities.

  9. lsorber commented on Sep 21, 2017

    @lsorber

    You can write/implement any einsum as a batch of independent GEMMs, so it should be able to benefit from the same fast kernels that tensordot does. I also agree that tensordot is still worth having for those cases where you don't need the full flexibility of an einsum. Under the covers it could simply call einsum though.

    I think einsum is an operation where dask could really shine as a distributed scheduler, because it is an example of a powerful tool where the distribution and scheduling can make a big difference in performance.

  10. jakirkham commented on Oct 13, 2017

    @jakirkham
    Member

    I don't know if you guys saw this, but I think the plan is for NumPy 1.14.0 to use optimized BLAS kernels when possible. ( numpy/numpy#9425 )

  11. jakirkham commented on Apr 23, 2018

    @jakirkham
    Member

    It's worth noting that despite work to make NumPy's einsum use optimized BLAS calls when possible, one can still get bad performance in common cases (e.g. matmul). ( numpy/numpy#7569 )

  12. mrocklin commented on May 16, 2018

    @mrocklin
    MemberAuthor

    The right place to implement the optimization described in the original post is possibly in atop, rather than tensordot.

    Edit: I no longer believe this to be true because we also need to incorporate the sum into this process, which happens outside of atop for the tree reductions.

  13. mrocklin commented on Jun 14, 2018

    @mrocklin
    MemberAuthor

    I spent this morning working on this problem with pen and paper. Here are my thoughts after a few hours:

    Our data gets replicated a number of times equal to the product of the number of chunks along each outer dimension. So considering the following example:

    x = da.ones((1000, 1000, 1000), chunks=(100, 200, 100))
    y = da.ones((1000, 1000), chunks=(100, 200))
    z = tensordot(x, y, axes=(0, 0))  # this requires 5 * 10 communications per chunk

    Then naively each chunk communicates with 5 * 10 other chunks. In a shared memory situation this isn't so bad, but in a distributed memory situation it's pretty unusable.

    The solution then, is to decrease the number of chunks in outer (non-contracted) dimensions. The following would perform better

    x = da.ones((1000, 1000, 1000), chunks=(10, 1000, 500))
    y = da.ones((1000, 1000), chunks=(10, 1000))
    z = tensordot(x, y, axes=(0, 0))  # this requires 1 * 2 communications per chunk

    However there are some costs to be aware of here:

    1. By increasing the chunksize of the outer dimensions we also increase the chunksize of our result, which is only outer dimensions. This might quickly become too large.

    2. Our input chunks now have very larger outer dimensions (like our output chunks) but also still have full inner dimensions. We'll need to rechunk these to be much smaller to compensate.

    3. If we squeeze our inner dimensions down to 1 then we need to worry about what happens when several of these stack together when performing the sum. Generally we won't want our inner dimensions to decrease below the split_every parameter that controls how many intermediate chunks are used in a tree summation (this is available by dask.config.get('array.split_every').

    4. The process of rechunking also introduces constraints

      1. There is a single communication cost across the array (but this is additive rather than multiplicative like with tensordot)

      2. Rechunking also hurts streamability, or low-memory action. Consider the following example

        x = da.ones((100, 100), chunks=(50, 2)).rechunk((2, 50))

        This requires that full (50, 50) subarrays are in memory at once

    So a naive solution to this problem might be to rechunk all of the outer dimensions to the full dimension size, and rechunk all inner dimensions to be as small as possible in order to compensate, and hope that both result and all intermediate rechunkings fit comfortably in memory. This will fail in plenty of cases.

    However, we do have one benefit to consider:

    1. Once all-but-one of the outer dimensions are single chunked, it no longer makes sense to single-chunk the last outer dimension

      Recall that unpleasant rechunking generally requires a full communication of the data. This made sense when we were competing against the multiplicative cost of multiplying for every chunked dimension, but once every other outer dimension has a single chunk then the multiplicative factor is 1 * 1 * 1 * 1 ... = 1, and so we can choose to accept this communication and not rechunk.

    I anticipate that having freedom along one outer dimension of our choice will be very helpful in the common case.

    So a pragmatic common-case solution here might be to find the outer dimension that we least want to single-chunk, and then try hard to single-chunk all other outer dimensions. The measurement of chunk-desirability depends both on the amount of data in the array associated to that outer-dimension (each outer dimension is associated to exactly one array) and the current chunking of that array.

  14. convexset commented on Jun 15, 2018

    @convexset
    Contributor

    What I'm seeing from this discussion is two major objectives:

    • chunking to reduce communication (while keeping to a maximum chunk size)
    • chunk to meet a specified output chunking outcome (while considering maximum chunk size; so 1 argument on output chunks, another on max memory)

    They seem to be relatively compatible.

    My proposal would be to ask for a max chunk size option (like 10 MiB, possibly more readily given) and a output chunking (possibly less readily given), and work with those two objectives. Some rechunking might be needed in post processing to achieve both.

    Hmmm....

    x = da.ones((1000, 1000, 1000), chunks=(100, 200, 100))  # this requires 5 communications per chunk
    y = da.ones((1000, 1000), chunks=(100, 200))  # this requires 5 * 10 communications per chunk
    
    z = tensordot(x, y, axes=(0, 0))
    # output: chunks=(200, 100, 200)
    

    and

    x = da.ones((1000, 1000, 1000), chunks=(100, 1000, 500))    # this requires 2 communications per chunk
    y = da.ones((1000, 1000), chunks=(100, 500))  # this requires 1 * 2 communications per chunk
    
    z = tensordot(x, y, axes=(0, 0))
    # output: chunks=(1000, 500, 500)... ouch
    
  15. convexset commented on Jun 15, 2018

    @convexset
    Contributor

    There may need to be some norms with regards to what "level" of communication is sensible.

    While theoretically, increasing chunk sizes does not involve as much communication ("transmissions") as reducing chunk sizes, practically, when chunk sizes are reduced, workers might just be reorganizing their memory.

  16. GenevieveBuckley commented on Jul 20, 2021

    @GenevieveBuckley
    Contributor
    1. If we squeeze our inner dimensions down to 1 then we need to worry about what happens when several of these stack together when performing the sum. Generally we won't want our inner dimensions to decrease below the split_every parameter that controls how many intermediate chunks are used in a tree summation (this is available by dask.config.get('array.split_every').

    Can you clarify what you mean by "squeeze our inner dimensions down to 1" @mrocklin. Are you talking about squeezing the whole dimension, or about changing the chunking of that dimension?

    I also don't see any kind of key named split_every in the dask config dictionary, so I'm not sure we can rely on this. I do have a key named split-large-chunks, but it has a value of None.

    dask.config.get('array.slicing.split-large-chunks') == None  # returns True
  17. mrocklin commented on Jul 20, 2021

    @mrocklin
    MemberAuthor

    Can you clarify what you mean by "squeeze our inner dimensions down to 1" @mrocklin. Are you talking about squeezing the whole dimension, or about changing the chunking of that dimension?

    All of this will probably make more sense after you've been beaten up a bit by tensordot. I encourage you to run things and see things fail in different ways. I'm anticipating issues that may or may not arise after we've solved a couple of problems. Probably you should ignore what I'm about to say until you've crashed your computer a couple dozen times. That being said, here we go.

    I'm saying that as we increase the size of the outer dimensions, a desire to keep modest sized chunks will naturally cause us to choose chunks with smaller sizes along inner dimensions. I suspect that this will have a negative effect when we choose to perform eventual reductions. Currently when doing a reduction we first collapse each chunk, and then we collect many of those chunks together. If each chunk only has size one then we don't get much of a size reduction on that first pass, which could become awkward when we collect many of those chunks together. I suspect that we might run into situations where this causes us to run out of RAM.

    So instead after the first pass we might choose to collect these chunks in groups, and then reduce down each group. Then we could collect the groups together and reduce them again. This gradual approach may allow us to perform the reduction in small space, even if we don't benefit much from fat inner dimensions.

  18. GenevieveBuckley commented on Jul 20, 2021

    @GenevieveBuckley
    Contributor

    The clarification helps, thank you.

  19. GenevieveBuckley commented on Jul 27, 2021

    @GenevieveBuckley
    Contributor

    Copying over comments from #7124 that really belong more in this issue thread:

    Terminology:
    We didn't use these particular phrases in my maths classes, but here's what I think they're being used to mean in these discussions

    • inner dimensions <- are summed over by tensordot
    • outer dimensions <- not summed over by tensordot

    For tensordot, it looks like the process should go something like this:

    1. Work out which are the outer dimension axes for arrays a and b
    2. Use the auto_chunks function to work out what the best chunk size is for the tensordot array output, given the chunk size limit from dask.config.get('array.chunk-size')
    3. Work backwards from this to figure out how the input tensordot arrays should be rechunked for the outer dimension axes.
    4. Inner dimension axes - do we (a) make no change to the chunking here, (b) rechunk all inner dimensions to a chunksize of 1, or (c) rechunk inner dimensions to some smaller chunksize but ?? what size they should be.
    5. Rechunk the tensordot input arrays
    6. Set kwarg align_arrays=False when tensordot hands over to blockwise (might need to double check if there is any extra logic in the unify_chunks function we now need to take care of in tensordot?)

    I've written some code for this, while I was trying to work out the process. I'll need a bit more clarity around the questions in point 4 and 6 above. (Hacky code here)

    It is clear that the rechunking logic is going to have to happen in tensordot before it gets to blockwise, blockwise just doesn't know enough information to do what we want.

    Matt responds:

    Most of my comments below are relevant for #2225 rather than this issue (I think that that issue is a bigger deal than this one). It's worth noting that these are two different concerns and not necessarily fully compatible.

    First, I highly recommend multiplying two matrices two-dimensional matrices together and experimenting with chunking structure before trying to generalize any of this. I also recommend using the dask.distributed scheduler and having the dashboard up. The chunking structure will make a very large impact on if the computation finishes or not. I think that you probably need to feel this pain viscerally a bit before these issues make much sense.

    I would also be totally ok with a first pass that only worked in the 2d x 2d case. This is the common case, probably much easier to get right, and much less likely to stall out with a half-finished PR.

    and also

    I think that if you build up a small set of interesting examples that you'll be able to try out different approaches, like what you propose above, and see how they work. I think that this will quickly give you more intuition than anyone here has. The approach that you lay out above sounds sensible to me, but I would bet large amounts of money that it's wrong. I don't think that anyone today knows enough to be able to tell if any approach is solid or not. I'm certainly not able to do so.

  20. GenevieveBuckley commented on Jul 27, 2021

    @GenevieveBuckley
    Contributor

    Ok, I think I have it now.

    The approach I outlined above was wrong - you shouldn't focus on the shape of the final output array to work out the optimal chunk sizes. Instead, you should focus on trying to maximize the chunk length/width along the axes that will be summed over by tensordot.

    I've updated my gist with this demo

    import dask
    import dask.array as da
    import numpy as np
    
    
    def _inner_axes(a_ndim, b_ndim, axes):
        """Given tensordot axes argument, return list of axes to sum over."""
        if isinstance(axes, (int, float)):
            if axes == 0:
                inner_axes_a = []
                inner_axes_b = []
            elif axes > 0:
                inner_axes_a = list(range(a_ndim))[-axes:]
                inner_axes_b = list(range(b_ndim))[:axes]
        else:
            axes_a, axes_b = axes
            if isinstance(axes_a, (int, float)):
                axes_a = [axes_a]
            if isinstance(axes_b, (int, float)):
                axes_b = [axes_b]
            inner_axes_a = [i for i in range(a.ndim) if i in axes_a]
            inner_axes_b = [i for i in range(b.ndim) if i in axes_b]
        return inner_axes_a, inner_axes_b
      
      
    def find_optimal_chunks(array, inner_axes, limit=None):
        if limit is None:
            limit = dask.utils.parse_bytes(dask.config.get('array.chunk-size'))
    
        inner_chunks = [array.shape[ax] for ax in inner_axes]
        while limit < (np.prod(inner_chunks) * array.dtype.itemsize):
            inner_chunks[np.argmax(inner_chunks)] = np.max(inner_chunks) // 2
    
        optimal_chunks = []
        for ax in range(array.ndim):
            if ax in inner_axes:
                idx = inner_axes.index(ax)
                optimal_chunks.append(inner_chunks[idx])
            else:
                optimal_chunks.append('auto')
        return optimal_chunks
      
    print("Example")
    a = da.ones((100, 10_000_000), chunks=(100, 10_000_000))
    b = da.ones((10_000_000, 100), chunks=(10_000_000, 100))
    # a = da.ones((50, 20_000_000), chunks=(50, 20_000_000))  # optimal chunks (1, 10_000_000)
    # b = da.ones((20_000_000, 50), chunks=(20_000_000, 50))  # optimal_chunks (10_000_000, 1)
    axes = [1, 0]
    
    inner_axes_a, inner_axes_b = _inner_axes(a.ndim, b.ndim, axes)
    optimal_chunks_a = find_optimal_chunks(a, inner_axes_a)
    optimal_chunks_b = find_optimal_chunks(b, inner_axes_b)
    print("optimal_chunks_a:", optimal_chunks_a)
    print("optimal_chunks_b:", optimal_chunks_b)
    
    aa = a.rechunk(optimal_chunks_a)
    bb = b.rechunk(optimal_chunks_b)
    z = da.tensordot(aa, bb, axes=axes)
    z = z.rechunk(['auto' for _ in range(z.ndim)])
    z.compute()  # time consuming, but stays nicely within memeory
  21. GenevieveBuckley commented on Jul 27, 2021

    @GenevieveBuckley
    Contributor

    One problem:
    I put that final rechunk in there because for more commonly used parameters for tensordot (eg: axes=1 with 2D input arrays), we can often end up with a final output array with chunks equal to a single pixel. That's something to avoid, and popping a rechunk statement in here seems to work well. Except...

    But there's also the other end of the spectrum, where not very many axes have been summed over, so the output array (and also the output chunks) can be very large. For these cases (eg: axes=0), rechunking the final output array z is extremely time consuming. What's worse is that it's time consuming while building the task graph, rather than only at computation time.

    So, what to do?

    • Rechunk the output only if the chunk sizes are very small
    • Rechunk the output only if it is 2D or smaller (maybe? this is a very indirect way to guess rechunking will take a long time)
    • not rechunk the final output at all
    • ... something else?
  22. GenevieveBuckley commented on Jul 27, 2021

    @GenevieveBuckley
    Contributor

    Also, I haven't looked at how this will interact with unify_chunks - possibly poorly under some circumstances. Most likely I shouldn't faff around too much more with this, but instead put in a pull request so we can all play around with it a bit.

  23. mrocklin commented on Jul 27, 2021

    @mrocklin
    MemberAuthor
  24. GenevieveBuckley commented on Jul 27, 2021

    @GenevieveBuckley
    Contributor

    Jeremy summarized these two goals earlier:

    1. chunking to reduce communication (while keeping to a maximum chunk size)
    2. chunk to meet a specified output chunking outcome (while considering maximum chunk size; so 1 argument on output chunks, another on max memory)

    So far I've optimized for (1) but not necessarily (2).

    Addressing (1) means the computation in tensordot works nicely. Addressing (2) might help for convenience of operations after tensordot. Output chunks that are too big or too small will cause problems for subsequent operations. We might like to add some extra rules as a nod towards (2), but not too much because that is likely to impact performance.

  25. mrocklin commented on Jul 27, 2021

    @mrocklin
    MemberAuthor
  26. GenevieveBuckley commented on Aug 13, 2021

    @GenevieveBuckley
    Contributor

    Here is a sketch of the continuum of 2D array shapes we can have for a tensordot operation:
    https://docs.google.com/drawings/d/1qdq60Exvz1GvVIGd54Bo74n99j1k8-QDVxYEZd5uH4A/edit?usp=sharing

    The three important stages are where:

    1. The output array is smaller than one or both input arrays (the easiest to deal with)
    2. The output array size is equal to the largest input array
    3. The output array size is larger than both input arrays (the hardest to deal with)

    From what I can tell, it's not a case of needing different rules for different situations, it's just that there are no perfect solutions for the harder cases. For (3) we can limit the chunksize of the output array, at the cost of data duplication across the cluster. That's not good, but there isn't another good solution available - the only other alternative will crash the computation as the workers run out of memory.

  27. GenevieveBuckley commented on Aug 13, 2021

    @GenevieveBuckley
    Contributor

    There are a couple of general rules that apply everywhere:

    I think this means that for any tensordot operation A.B = C, we find which array shape is largest, A, B, or C. Then we use normalize_chunks to find the biggest, squarest chunks for that array. Then, we fill in what the chunk shapes should be for the other arrays (which should be easy enough because all the chunk boundaries need to line up with one another).

  28. mrocklin commented on Aug 13, 2021

    @mrocklin
    MemberAuthor

    Thank you for sharing these diagrams @GenevieveBuckley .

    @tomwhite , do these match your operational experience?

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions