Skip to content

Reuse tensordot memory tricks in matmul #6874

Closed

Description

@mrocklin

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).

dask/dask/array/routines.py

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:

  1. Find a way to back matmul by tensordot, so that the reduction trick is shared with a common codebase
  2. 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

  1. tomwhite commented on Nov 30, 2020

    @tomwhite
    Contributor

    Unlike matmul, tensordot doesn't broadcast leading axes, so I'm not sure it's possible to rewrite matmul in terms of tensordot.

    For example:

    >>> x = np.random.random((7, 11, 15))
    >>> y = np.random.random((7, 15, 19))
    >>> (x @ y).shape
    (7, 11, 19)
    >>> np.tensordot(x, y, ((2,), (1,))).shape
    (7, 11, 7, 19)

    It is possible to implement matmul using einsum though, see 9472b69...tomwhite:matmul-memory-usage, so that might be a way to solve this issue, since Dask's einsum implementation doesn't use concatenate=True.

  2. mrocklin commented on Nov 30, 2020

    @mrocklin
    MemberAuthor
  3. eric-czech commented on Nov 30, 2020

    @eric-czech
    Contributor

    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 matmul and einsum as @tomwhite currently has it parameterized in that diff: https://gist.github.com/eric-czech/3c39785ebb08088775326154bbeddcc2

    The conclusions I draw from this are:

    1. Neither supports scalars
    2. The einsum version produces results that it perhaps shouldn't for matmul, e.g. multiplying a (10,1) array by another (10,1) is possible w/ einsum but not the current matmul function. 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 as einsum supporting repetition of values in contracted axes of unit length, which matmul doesn't currently do.
  4. mrocklin commented on Nov 30, 2020

    @mrocklin
    MemberAuthor
  5. tomwhite commented on Nov 30, 2020

    @tomwhite
    Contributor

    I tried many different combinations of inputs

    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 matmul does (if we decided to go down the einsum route).

    It's probably better on our part if we use the np.matmul call on a per-chunk basis when we can

    matmul will always contract, so I don't see how we can use the tensordot trick with it (which relies on not contracting in the chunks, then doing the contraction via reductions). Using tensordot on the chunks is a possibility for some cases though (basically if either array has 2 dimensions or less).

  6. mrocklin commented on Nov 30, 2020

    @mrocklin
    MemberAuthor

    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.

  7. tomwhite commented on Nov 30, 2020

    @tomwhite
    Contributor

    Ah ok - it's more complicated than I thought!

  8. tomwhite commented on Dec 3, 2020

    @tomwhite
    Contributor

    It might be simplest to just delegate to dot for the common 2D case, and use the existing implementation for other cases. I opened #6924 for this.

  9. ravwojdyla commented on Dec 22, 2020

    @ravwojdyla
    Contributor

    @tomwhite @mrocklin tried implementing matmul as tensordot, 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.

  10. jsignell commented on Jan 12, 2021

    @jsignell
    Member

    Was this closed by #7000?

  11. ravwojdyla commented on Jan 12, 2021

    @ravwojdyla
    Contributor

    @jsignell yes. And if I may add, I believe before the release, #7050 should be fixed/closed as well.

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