Skip to content

Implement da.einsum #732

Closed
Closed

Description

@shoyer

I think this should be a simple wrapper on top of dask.array.core.atop.

Activity

  1. shoyer commented on Sep 19, 2015

    @shoyer
    MemberAuthor

    This version appears to work:

    In [13]: from dask.array.core import asarray, atop
    
    In [23]: def seq_add(a, b):
        ...:     result = 0
        ...:     for ai, bi in zip(a, b):
        ...:         result += np.einsum('ki,jk->ij', ai, bi)
        ...:     return result
    
    In [24]: atop(seq_add, 'ij', asarray(a), 'ki', asarray(b), 'jk').compute()
    Out[24]:
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    
    In [25]: np.einsum('ki,jk->ij', a, b)
    Out[25]:
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    
    In [26]: import dask.array as da
    
    In [27]: atop(seq_add, 'ij', da.from_array(a, 2), 'ki', da.from_array(b, 2), 'jk').compute()
    Out[27]:
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    

    So this looks like a partial solution:

    from toolz import concat
    
    def einsum(subscripts, *args):
        in_inds, out_inds = subscripts.split('->')
        in_inds = in_inds.split(',')
    
        def kernel(*args):
            result = 0
            for a in zip(*args):
                result += np.einsum(subscripts, *a)
            return result
    
        return atop(kernel, out_inds, *concat(zip(args, in_inds)))

    But it fails for some variants of einsum:

    In [50]: einsum('ki,jk->ij', da.from_array(a, 2), da.from_array(b, 2)).compute()
    Out[50]:
    array([[10, 28, 46, 64],
           [13, 40, 67, 94]])
    
    In [51]: np.einsum('ki,jk->j', a, b)
    Out[52]: array([ 23,  68, 113, 158])
    
    In [52]: einsum('ki,jk->j', da.from_array(a, 2), da.from_array(b, 2)).compute()
    ValueError: einstein sum subscripts string contains too many subscripts for operand 0
    
  2. matthewwillian commented on Oct 11, 2015

    @matthewwillian

    Has any progress been made on implementing this ?

  3. shoyer commented on Oct 11, 2015

    @shoyer
    MemberAuthor

    Nope, this is as far as I got. I would encourage you to try finishing it up if you're interested. I think we just need some sort of recursion inside the kernel function to handle nested arguments.

  4. matthewwillian commented on Oct 11, 2015

    @matthewwillian

    Cool. I will take a look.

  5. mrocklin commented on Nov 9, 2015

    @mrocklin
    Member

    @matthewwillian did you need einsum for an application or were you looking to get in to development?

  6. datnamer commented on Nov 11, 2015

    @datnamer

    I maybe misunderstanding the technology, but couldn't dask array integration with the elemental distributed computation library give us for free a lot of these use cases? Or maybe they can be easily rewritten in ufora( which seems to be getting numpy support anyway).

    Why spend the maintenance and time to rengineer these methods?

  7. mrocklin commented on Nov 11, 2015

    @mrocklin
    Member

    Integration with a foreign library is likely more costly than implementing einsum, which I anticipate can be done in 10-20 lines of code.

    However, your general theme of "why make an array library when others already exist" has general merit. People probably reinvent wheels because existing wheels don't do exactly what they want. Elemental itself is a reinvention on top of of several other systems. A lot of novelty comes with a lot of redundancy.

  8. datnamer commented on Nov 11, 2015

    @datnamer

    If all anyone wanted was einsum, I agree. However the upfront cost of integrating elemental will be amortized over all the future use cases and feature requests that it will fulfill, including those that are novel enough to be triggered. This along with speed and maintenance benefits seems compelling to me.

    To your second point, I don't think it would replace dask, but leverage it (I could be wrong). To keep dask light, it could be an option dependancy.

    I think enabling the sorts of out of core algorithms that elemental would facilitate can be useful for modeling pocket data. (On a single machine or only multiple node?)

  9. mrocklin commented on Nov 11, 2015

    @mrocklin
    Member

    If this is something you're interested in working on that would be great!

  10. datnamer commented on Nov 11, 2015

    @datnamer

    Maybe at some point. Right now I just wanted to make what I thought was a helpful suggestion :)

  11. mrocklin commented on Nov 11, 2015

    @mrocklin
    Member

    Suggestions are always welcome. I am aware of and have great respect for Elemental. At the moment I don't see a way to integrate the two systems, nor do I know of concrete use cases where access to both systems would be very valuable (usually one or the other will do) and so I don't plan to spend my personal time on it, though I would encourage others to look into it and report back. Internally the two systems work very differently.

    I suggest that we continue this conversation on another issue rather than this one, which is mostly about implementing einsum within dask.array.

  12. datnamer commented on Nov 11, 2015

    @datnamer

    Ah ok. Didn't realize they were fundamentally incompatible. Sorry for the noise

  13. matthewwillian commented on Nov 12, 2015

    @matthewwillian

    @mrocklin i had initially needed einsum for an application, but ended up solving the specific problem with a more naive approach. in spite of that, i did get a chance to work towards solving the problem, but got wrapped up in other things and thus wasn't able to bring it to completion.

    in general, i am somewhat interested in contributing to the project. if this is still something that needs doing i'd be happy to take another swing. any suggestions for other ways to contribute would also be welcome.

  14. shoyer commented on Oct 5, 2016

    @shoyer
    MemberAuthor

    With the new concatenate=True argument to atop, this version seems to work:

    import numpy as np
    from functools import partial
    
    def einsum(subscripts, *args):
        in_inds, out_inds = subscripts.split('->')
        in_inds = in_inds.split(',')
        kernel = partial(np.einsum, subscripts)
        args = [arg for arg_pair in zip(args, in_inds) for arg in arg_pair]
        return da.atop(kernel, out_inds, *args, concatenate=True)
  15. jdmcclain47 commented on Oct 6, 2016

    @jdmcclain47

    I was using this simple-ish code on my desktop and got the exception "Client not running".

    import numpy as np
    from distributed import Client
    import dask.dataframe as dd
    import dask.array as da
    from functools import partial
    from dask.dot import dot_graph
    
    client = Client()
    
    def einsum(subscripts, *args):
        in_inds, out_inds = subscripts.split('->')
        in_inds = in_inds.split(',')
        kernel = partial(np.einsum, subscripts)
        args = [arg for arg_pair in zip(args, in_inds) for arg in arg_pair]
        return da.atop(kernel, out_inds, *args, concatenate=True)
    
    nocc = 40
    nvir = 40
    nocc_blksize = min(nocc,4)
    nvir_blksize = min(nvir,20)
    fov = da.ones((nocc,nvir),chunks=(nocc_blksize,nvir_blksize))
    t1  = da.ones((nvir,nocc),chunks=(nvir_blksize,nocc_blksize))
    
    def tdot(arr,arr2):
        return einsum('ij,jm->im',arr,arr2)
    
    y = client.submit(tdot, fov, t1)
    y = y.result()
  16. mrocklin commented on Oct 6, 2016

    @mrocklin
    Member

    Submit is for sending individual python functions on python objects. If you're already using dask collections like dask.array then you probably want to stick to compute and persist.

    import numpy as np
    from distributed import Client
    import dask.dataframe as dd
    import dask.array as da
    from functools import partial
    from dask.dot import dot_graph
    
    def einsum(subscripts, *args):
        in_inds, out_inds = subscripts.split('->')
        in_inds = in_inds.split(',')
        kernel = partial(np.einsum, subscripts)
        args = [arg for arg_pair in zip(args, in_inds) for arg in arg_pair]
        return da.atop(kernel, out_inds, *args, concatenate=True)
    
    nocc = 40
    nvir = 40
    nocc_blksize = min(nocc,4)
    nvir_blksize = min(nvir,20)
    fov = da.ones((nocc,nvir),chunks=(nocc_blksize,nvir_blksize))
    t1  = da.ones((nvir,nocc),chunks=(nvir_blksize,nocc_blksize))
    
    y = einsum('ij,jm->im', fov, t1)
    y = y.compute()

    But really you don't need dask.distributed for this at all, I would consider using the default single threaded scheduler until you need the features of the distributed scheduler:

    import numpy as np
    import dask.array as da
    from functools import partial
    
    def einsum(subscripts, *args):
        in_inds, out_inds = subscripts.split('->')
        in_inds = in_inds.split(',')
        kernel = partial(np.einsum, subscripts)
        args = [arg for arg_pair in zip(args, in_inds) for arg in arg_pair]
        return da.atop(kernel, out_inds, *args, concatenate=True)
    
    nocc = 40
    nvir = 40
    nocc_blksize = min(nocc,4)
    nvir_blksize = min(nvir,20)
    fov = da.ones((nocc,nvir),chunks=(nocc_blksize,nvir_blksize))
    t1  = da.ones((nvir,nocc),chunks=(nvir_blksize,nocc_blksize))
    
    y = einsum('ij,jm->im', fov, t1)
    y = y.compute()
  17. jdmcclain47 commented on Oct 6, 2016

    @jdmcclain47

    This was just a simple example for testing it out - for most cases we will be using 4 index tensors that will be much larger (~100 GB up to 1 TB).

    I'm instead getting an error now (using your 2nd case above without the client for now):

    Traceback (most recent call last):
      File "mp2.py", line 28, in <module>
        y = y.compute()
      File "/Library/Python/2.7/site-packages/dask/base.py", line 86, in compute
        return compute(self, **kwargs)[0]
      File "/Library/Python/2.7/site-packages/dask/base.py", line 179, in compute
        results = get(dsk, keys, **kwargs)
      File "/Library/Python/2.7/site-packages/dask/threaded.py", line 58, in get
        **kwargs)
      File "/Library/Python/2.7/site-packages/dask/async.py", line 481, in get_async
        raise(remote_exception(res, tb))
    dask.async.TypeError: 'concatenate' is an invalid keyword for einsum
    

    Thank you guys for the help! I apologize if it seems like I'm not doing too much work here in hunting down errors - my group is testing out software packages that might suit our needs in scaling up our codes without having to worry anymore about the nitty-gritty details of task-scheduling. Also, I figure you guys can do in 2 minutes what would take me 2+ hours to find out. :)

  18. TomAugspurger commented on Oct 6, 2016

    @TomAugspurger
    Member

    @jdmcclain47 you'll need to grab a recent copy of dask off github. The concatenate=True keyword was added in #1609 a couple days ago.

  19. jdmcclain47 commented on Oct 6, 2016

    @jdmcclain47

    ah thanks, works like a charm!

  20. mrocklin commented on Oct 6, 2016

    @mrocklin
    Member

    @shoyer any desire to open a PR with einsum? Seems like it has found some use before even being in the repository :)

    In the future we might consider breaking this into two atop calls to reduce the data a bit per-chunk before moving it and concatenating.

  21. chrisbarber commented on Jan 16, 2017

    @chrisbarber
    Contributor

    A slight modification to support the einsum(op0, sublist0, op1, sublist1, ..., [sublistout]) variant:

    import numpy as np
    
    def einsum(*args):
        args = list(args)
        out_inds = args.pop()
        in_inds = args[1::2]
        
        def kernel(*operands):
            return np.einsum(*([arg for arg_pair in zip(operands, in_inds) for arg in arg_pair]+[out_inds]))
        
        return da.atop(kernel, out_inds, *args, concatenate=True)
  22. chrisbarber commented on Jan 18, 2017

    @chrisbarber
    Contributor

    This version is parallelizable along the contracted axes and avoids concatenation:

    def einsum(*args):
        args = list(args)
        out_inds = args.pop()
        in_inds = args[1::2]
        arrays = args[0::2]
        dtype = arrays[0].dtype
        
        full_inds = list(set().union(*in_inds))
        contract_inds = tuple(set(full_inds)-set(out_inds))
        
        def kernel(*operands):
            chunk = np.einsum(*([arg for arg_pair in zip(operands, in_inds) for arg in arg_pair]+[out_inds]))
            chunk.shape = tuple([1 if ind not in out_inds else chunk.shape[out_inds.index(ind)] for ind in full_inds])
            return chunk
        
        adjust_chunks = {ind: 1 for ind in contract_inds}
        full = da.atop(kernel, full_inds, *args, dtype=dtype, adjust_chunks=adjust_chunks)
        contracted = da.sum(full, axis=contract_inds, dtype=dtype)
        return contracted
  23. mrocklin commented on Jan 18, 2017

    @mrocklin
    Member

    Any interest in opening a full PR @chrisbarber ? Would love to have you as a contributor.

  24. GuillaumeLeclerc commented on Mar 2, 2018

    @GuillaumeLeclerc

    This feature would be very useful 😄

  25. chrisbarber commented on Mar 2, 2018

    @chrisbarber
    Contributor

    I regret not having had time to create a full PR for this. If it helps anyone though here is the implementation I have been running with for some time now; iirc it fixes a couple bugs vs my previous comment and also handles casting better.

    def da_einsum(*args, **kwargs):
        args = list(args)
        out_inds = args.pop()
        in_inds = args[1::2]
        arrays = args[0::2]
        dtype = kwargs.get('dtype')
        einsum_dtype = dtype
        if dtype is None:
            dtype = np.result_type(*[a.dtype for a in arrays])
        casting = kwargs.get('casting')
        if casting is None:
            casting = 'safe'
        
        full_inds = list(set().union(*in_inds))
        contract_inds = tuple(set(full_inds)-set(out_inds))
        
        def einsum(*operands, **kwargs):
            kernel_dtype = kwargs.get('kernel_dtype')
            casting = kwargs.get('casting')
            chunk = np.einsum(dtype=kernel_dtype, casting=casting, *([arg for arg_pair in zip(operands, in_inds) for arg in arg_pair]+[out_inds]))
            chunk = np.array(chunk)
            chunk.shape = tuple([1 if ind not in out_inds else chunk.shape[out_inds.index(ind)] for ind in full_inds])
            return chunk
        
        adjust_chunks = {ind: 1 for ind in contract_inds}
        result = da.atop(einsum, full_inds, *args, dtype=dtype, kernel_dtype=einsum_dtype, casting=casting, adjust_chunks=adjust_chunks)
        if contract_inds:
            result = da.sum(result, axis=contract_inds)
        return result
    
    # monkey-patch the method into the module for now
    setattr(da, 'einsum', da_einsum)

    I don't know if it performs well in all cases but it has been working well for my application. I think the only thing missing besides tests and so forth is to merge in support for the string 'ij,jm->im'-style subscripts.

  26. mrocklin commented on Mar 23, 2018

    @mrocklin
    Member

    Here is an interesting implementation of einsum that seems to support dask array: https://github.com/dgasmith/opt_einsum

  27. jakirkham commented on Apr 19, 2018

    @jakirkham
    Member

    Solved in PR ( #3412 ) thanks to @sjperkins.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions