Repository navigation
Description
Currently the dask array matmul implemenation is similar to the tensordot implemenation (understandably) but lacks a clever trick that tensordot uses to avoid contractions in blockwise (which can result in large pileups of intermediate results).
Lines 290 to 329 in ff3ea6c
| @derived_from(np) | |
| def matmul(a, b): | |
| a = asanyarray(a) | |
| b = asanyarray(b) | |
| if a.ndim == 0 or b.ndim == 0: | |
| raise ValueError("`matmul` does not support scalars.") | |
| a_is_1d = False | |
| if a.ndim == 1: | |
| a_is_1d = True | |
| a = a[np.newaxis, :] | |
| b_is_1d = False | |
| if b.ndim == 1: | |
| b_is_1d = True | |
| b = b[:, np.newaxis] | |
| if a.ndim < b.ndim: | |
| a = a[(b.ndim - a.ndim) * (np.newaxis,)] | |
| elif a.ndim > b.ndim: | |
| b = b[(a.ndim - b.ndim) * (np.newaxis,)] | |
| out = blockwise( | |
| np.matmul, | |
| tuple(range(1, a.ndim + 1)), | |
| a, | |
| tuple(range(1, a.ndim - 1)) + (a.ndim - 1, 0), | |
| b, | |
| tuple(range(1, a.ndim - 1)) + (0, a.ndim), | |
| dtype=result_type(a, b), | |
| concatenate=True, | |
| ) | |
| if a_is_1d: | |
| out = out[..., 0, :] | |
| if b_is_1d: | |
| out = out[..., 0] | |
| return out |
Tensordot uses only outer products in blockwise (there are no shared indices in the blockwise call) , and then uses a sum call to reduce these. Because sum uses tree reductions, this results in nicer memory usage. Matmul doesn't use this trick.
I briefly tried replacing the blockwise call in matmul with a call to our internal dot function, but various tests failed. It would be good to do one of two things:
- Find a way to back matmul by tensordot, so that the reduction trick is shared with a common codebase
- Replicate the reduction trick in matmul
This was originally reported by @eric-czech and @tomwhite in https://github.com/pystatgen/sgkit/issues/375#issuecomment-731060672
Activity
tomwhite commentedon Nov 30, 2020
Unlike
matmul,tensordotdoesn't broadcast leading axes, so I'm not sure it's possible to rewritematmulin terms oftensordot.For example:
It is possible to implement
matmulusingeinsumthough, see 9472b69...tomwhite:matmul-memory-usage, so that might be a way to solve this issue, since Dask'seinsumimplementation doesn't useconcatenate=True.mrocklin commentedon Nov 30, 2020
eric-czech commentedon Nov 30, 2020
FWIW, I tried many different combinations of inputs (always two arrays of different shapes/chunkings) and found that there appear to no large differences between
matmulandeinsumas @tomwhite currently has it parameterized in that diff: https://gist.github.com/eric-czech/3c39785ebb08088775326154bbeddcc2The conclusions I draw from this are:
einsumversion produces results that it perhaps shouldn't formatmul, e.g. multiplying a(10,1)array by another(10,1)is possible w/einsumbut not the currentmatmulfunction. Similarly, multiplying a(1,1)array by a(10,1)is ok w/einsum. There are many more cases like that but they seem to generalize aseinsumsupporting repetition of values in contracted axes of unit length, whichmatmuldoesn't currently do.mrocklin commentedon Nov 30, 2020
tomwhite commentedon Nov 30, 2020
Thanks for trying those out @eric-czech. For the cases that differ, we could check that the axis lengths are compatible and raise an error like
matmuldoes (if we decided to go down theeinsumroute).matmulwill always contract, so I don't see how we can use thetensordottrick with it (which relies on not contracting in the chunks, then doing the contraction via reductions). Usingtensordoton the chunks is a possibility for some cases though (basically if either array has 2 dimensions or less).mrocklin commentedon Nov 30, 2020
The tensordot trick actually does contract in the chunks (otherwise the intermediate results would be possibly huge).
However, we lie to the intermediate Dask Array so that it thinks that it hasn't contracted and that it should do the sum appropriately. The intermediate dask array has shape and chunk structure metadata that is intentionally incorrect.
tomwhite commentedon Nov 30, 2020
Ah ok - it's more complicated than I thought!
Avoid unbounded memory usage in matmul by delegating to dot in
tomwhite commentedon Dec 3, 2020
It might be simplest to just delegate to
dotfor the common 2D case, and use the existing implementation for other cases. I opened #6924 for this.ravwojdyla commentedon Dec 22, 2020
@tomwhite @mrocklin tried implementing
matmulastensordot, and it's possible but rather complicated and doesn't perform too well (for input above 2d, it get's complicated due to outer products nature of tensordot). So instead tried to implement a new matmul without concatenated contraction blockwise -> #7000.jsignell commentedon Jan 12, 2021
Was this closed by #7000?
ravwojdyla commentedon Jan 12, 2021
@jsignell yes. And if I may add, I believe before the release, #7050 should be fixed/closed as well.