Repository navigation
Description
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
mrocklin commentedon Apr 19, 2017
@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.
mrocklin commentedon Jun 1, 2017
@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.
jni commentedon Jul 18, 2017
@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.
lsorber commentedon Sep 20, 2017
Are there any estimates or measurements of the rechunking cost available at runtime?
An
einsumimplementation (#732) with rechunking would be even better, astensordotcould then call that instead.mrocklin commentedon Sep 20, 2017
We know the size of every chunk both before and after. Every task has around 100-300us of overhead.
Are you saying that
einsumis likely to be faster thantensordotor that it is more general?If you have any interest in implementing
einsumthen that would be quite welcome.lsorber commentedon Sep 20, 2017
I was mostly referring to the communication cost of rechunking, is there any data available on that?
I mean that
einsumis more general yes, since you can specify both inner and outer products (and it would do singleton expansion -- whichtensordotdoesn't seem to do?). Since that is the case, it makes sense to design rechunking on theeinsumlevel and have those benefits flow down totensordotautomatically.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.
mrocklin commentedon Sep 20, 2017
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.
mrocklin commentedon Sep 20, 2017
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.
lsorber commentedon Sep 21, 2017
You can write/implement any
einsumas a batch of independent GEMMs, so it should be able to benefit from the same fast kernels thattensordotdoes. I also agree thattensordotis still worth having for those cases where you don't need the full flexibility of aneinsum. Under the covers it could simply calleinsumthough.I think
einsumis 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.jakirkham commentedon Oct 13, 2017
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 )
jakirkham commentedon Apr 23, 2018
It's worth noting that despite work to make NumPy's
einsumuse optimized BLAS calls when possible, one can still get bad performance in common cases (e.g.matmul). ( numpy/numpy#7569 )mrocklin commentedon May 16, 2018
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.
mrocklin commentedon Jun 14, 2018
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:
Then naively each chunk communicates with
5 * 10other 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
However there are some costs to be aware of here:
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.
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.
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_everyparameter that controls how many intermediate chunks are used in a tree summation (this is available bydask.config.get('array.split_every').The process of rechunking also introduces constraints
There is a single communication cost across the array (but this is additive rather than multiplicative like with tensordot)
Rechunking also hurts streamability, or low-memory action. Consider the following example
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:
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.
convexset commentedon Jun 15, 2018
What I'm seeing from this discussion is two major objectives:
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....
and
convexset commentedon Jun 15, 2018
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.
GenevieveBuckley commentedon Jul 20, 2021
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_everyin the dask config dictionary, so I'm not sure we can rely on this. I do have a key namedsplit-large-chunks, but it has a value of None.mrocklin commentedon Jul 20, 2021
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.
GenevieveBuckley commentedon Jul 20, 2021
The clarification helps, thank you.
GenevieveBuckley commentedon Jul 27, 2021
Copying over comments from #7124 that really belong more in this issue thread:
Matt responds:
and also
GenevieveBuckley commentedon Jul 27, 2021
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
GenevieveBuckley commentedon Jul 27, 2021
One problem:
I put that final rechunk in there because for more commonly used parameters for tensordot (eg:
axes=1with 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 arrayzis 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?
GenevieveBuckley commentedon Jul 27, 2021
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.mrocklin commentedon Jul 27, 2021
GenevieveBuckley commentedon Jul 27, 2021
Jeremy summarized these two goals earlier:
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.
mrocklin commentedon Jul 27, 2021
GenevieveBuckley commentedon Aug 13, 2021
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:
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.
GenevieveBuckley commentedon Aug 13, 2021
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 usenormalize_chunksto 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).mrocklin commentedon Aug 13, 2021
Thank you for sharing these diagrams @GenevieveBuckley .
@tomwhite , do these match your operational experience?