Skip to content

einsum implementation - #3412

Merged
mrocklin merged 47 commits into
dask:masterfrom
sjperkins:einsum-implementation
Apr 19, 2018
Merged

mrocklin merged 47 commits into
dask:masterfrom
sjperkins:einsum-implementation

Conversation

@sjperkins

@sjperkins sjperkins commented Apr 16, 2018 •

Copy link
Copy Markdown
Member
  • Tests added / passed
  • Passes flake8 dask
  • Fully documented, including docs/source/changelog.rst for all changes
    and one of the docs/source/*-api.rst files for new API

@sjperkins

Copy link
Copy Markdown
Member Author

Based on the implementation by @chrisbarber. My first two test cases worked easily and I hoped it would be trivial but there's something going wrong with the third one, based on one of opt_einsum's doc examples.

Putting this up here as a WIP and for input from people who know einsum better than I do!

/cc @dgasmith and @jcmgray

@sjperkins sjperkins changed the title Dask einsum implementation [WIP] Dask einsum implementation Apr 16, 2018
@sjperkins

Copy link
Copy Markdown
Member Author

Hmmmm, relaxing the comparison in the third test from np.all(result.compute() == np_result) to np.allclose(result.compute(), np_result) results in a working test case.

@dgasmith

dgasmith commented Apr 16, 2018 •

Copy link
Copy Markdown

Cool, starts to use the new internal einsum optimizer. My main comment would be that this would require NumPy 1.12+ when the optimize tech was inserted. I do not know the current NumPy requirements for Dask.

Some operations may be reordered which is fine, but will not return exactly the same result due to limitations of floating point arithmetic. Hence the np.allclose, but feel free to tighten the tolerance to rtol=1.e-15.

@mrocklin

Copy link
Copy Markdown
Member

cc @shoyer @jakirkham you may want to see this

Comment thread dask/array/tests/test_routines.py Outdated
assert da.result_type(a, c) == np.float64


def test_einsum():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Einsum seems tricky enough that I suggest we consider building an additional test that is parametrized over many different kinds of situations:

Perhaps something like the following (untested):

@pytest.mark.parametrize('signature', [
    'abc,bad->abcd', 
    'ab,bc-> ...' 
    ...
])
def test_einsum(signature):
    dimensions = {'a': 5, 'b': 6, 'c': 7, 'd': 5, 'e': 6}

    def shape_from_string(s):
        return tuple(dimensions[c] for c in s)

    np_inputs = [np.random.random(shape_from_string(s) for s in signature.split('->')[0].split(',')]
    da_inputs = [da.from_array(x, chunks=4) for x in np_inputs]

    assert_eq(np.einsum(signature, *np_inputs), 
              da.einsum(signature, *da_inputs))

@shoyer

shoyer commented Apr 16, 2018

Copy link
Copy Markdown
Member

I think it would be straightforward to only support optimize if using NumPy 1.12+. We could set a default value of optimize=None which means "optimize if possible."

A comment on the implementation: it would be best to avoid using concatenate=True, which means that all chunks corresponding to contracted dimensions get concatenated together. In practice, this means that concatenate=True imposes significantly higher memory requirements and shows much less benefit due to palatalization.

Instead, we should keep all contracted dimensions as size 1 in each chunk with atop, and then sum in another pass over all the dimensions with size 1 chunks. Instead of calling einsum() as the mapped function with atop, you would use a version of einsum() that keeps contracted dimensions as size one instead of removing them, like keepdims=True for numpy.sum(). The implementation would look somewhat similar to my implementation of dask.array.isin in #3363.

@shoyer

shoyer commented Apr 16, 2018

Copy link
Copy Markdown
Member

Actually, it looks like @chrisbarber's latest version of einsum over in #732 (comment) already uses my suggestion above to avoid concatenate=True.

The optimize keyword can be bool or str
@sjperkins

Copy link
Copy Markdown
Member Author

I'll take a look at implementing your review comments over the next couple of days.

@sjperkins

Copy link
Copy Markdown
Member Author

Changes seemed fairly easy to make. Would you mind taking a look?

Comment thread dask/array/routines.py Outdated
casting=kwargs['casting'],
dtype=kwargs['kernel_dtype'],
order=kwargs['order'],
optimize=kwargs['optimize'])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be able to pop a few values from kwargs and pass the rest through. That could also smooth over the differences between the supported optimize case and non-optimize/unsupported case. Thus simplifying the surrounding code.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for using pop, e.g.,

def _einsum_kernel(*operands, **kwargs):
    subscripts = kwargs.pop('subscripts')
    ncontract_inds = kwargs.pop('ncontract_inds')
    chunk = np.einsum(subsripts, *operands, **kwargs)
    ...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used pop

Comment thread dask/array/routines.py Outdated
casting=kwargs['casting'],
dtype=kwargs['kernel_dtype'],
order=kwargs['order'],
optimize=kwargs['optimize'])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for using pop, e.g.,

def _einsum_kernel(*operands, **kwargs):
    subscripts = kwargs.pop('subscripts')
    ncontract_inds = kwargs.pop('ncontract_inds')
    chunk = np.einsum(subsripts, *operands, **kwargs)
    ...

Comment thread dask/array/routines.py Outdated
def einsum(subscripts, *operands, **kwargs):
casting = kwargs.get('casting', 'safe')
dtype = kwargs.get('dtype')
optimize = kwargs.get('optimize', True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking something like:

optimize = kwargs.get('optimize')

...

if optimize is None:
    optimize = can_optimize

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optimize can be {True, False, 'greedy', 'optimal'}, so it would be best not to be destructive of the user's input.

Comment thread dask/array/routines.py Outdated
# If output isn't provided, it's equal to
# the sorted list of all indices
if output_str is None:
output_str = list(sorted(all_inds_set))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought repeated indices are summed over by default?

@pytest.mark.parametrize('einsum_signature', [
'abc,bad->abcd',
'abcdef,bcdfg->abcdeg',
'ea,fb,abcd,gc,hd->efgh',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be good to add a few more examples for more test coverage:

  • with outputs omitted, e.g., 'ab,b'
  • with no output indices, e.g., `'ab,b->'
  • ... for broadcasting, e.g., '...a,a' (could raise an informative error for now)
  • with the alternative syntax einsum(op0, sublist0, op1, sublist1, ..., [sublistout]) (could raise an informative error for now)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I've add a couple more tests, the examples you suggested were good.

I raise exceptions on ellipses and the alternative syntax for now. However, I've thought a bit about the ellipses and they should be doable, but it may be better to support them in a separate PR, depending on your timelines

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a note I would also explicitly test broadcasting operations such as

a.shape = (4, 1)
b.shape = (4, 4)
np.einsum('ij,jk->ik', a, b)

A few more similar tests can be found here.

Einsums functionality is incredibly broad and I got caught on a few issues that were not tested in NumPy and as such NumPy 14.0 had a few regressions from my changes. A few other tricky cases I would recommend:

'aa->a`,
'ab,ab,c->c'   
'aab,bc->ac',
'aab,bcc->ac',
'fdf,cdd,ccd,afe->ae',
'fff,fae,bef,def->abd',

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dgasmith OK, I've added the test cases in your comment as well as the broadcasting test cases. They succeed locally for me and I've pushed them up.

I realise that the range of einsum's behaviour is broad, but my available time for working on this PR is running out.

With regard to the dask wrapper, as long as the full subscript specificaiton is present, dask will align each chunk correctly and defer to np.einsum's implementation

@sjperkins

Copy link
Copy Markdown
Member Author

Right, my only interest was in seeing that it does get passed on. This could be a very simple test IMHO.

Apologies and good catch, this revealed a mistake in how np.einsum_path was called. I've fixed it and added some permuted optimize test cases. Hope this brings the PR up to speed.

@sjperkins

Copy link
Copy Markdown
Member Author

Rats, just thought of something ... in order to produce an optimized path, np.einsum_path must be called (either in da.einsum or outside) with dask Arrays, which probably get converted to numpy arrays via internal asarray calls.

Any thoughts on how to work around this?

@jakirkham

Copy link
Copy Markdown
Member

Copy it too? Maybe someone else has a better idea.

@jakirkham

Copy link
Copy Markdown
Member

Thanks for the optimization tests. Looks good.

@shoyer

shoyer commented Apr 18, 2018 •

Copy link
Copy Markdown
Member

Any thoughts on how to work around this?

You can make dummy numpy arrays with the right shape with repeated values (with strides) by using np.broadcast_to, e.g., np.broadcast_to(0, shape=(1000, 2000, 3000)) actually only uses a few bytes to store its data, not many gigabytes.

@sjperkins

Copy link
Copy Markdown
Member Author

You can make dummy numpy arrays with the right shape with repeated values (with strides) by using np.broadcast_to, e.g., np.broadcast_to(0, shape=(1000, 2000, 3000)) actually only uses a few bytes to store its data, not many gigabytes.

Oh nice. I actually thought of [np.empty((1,)*o.ndim, o.dtype) for o in operands] but this should work well!

@shoyer

shoyer commented Apr 18, 2018

Copy link
Copy Markdown
Member

Yeah, it's important to give einsum_path the right shapes in order for the cost to be estimated correctly.

Pass `np.broadcast_to(scalar, shape=mchugelarge)` instead of
dask arrays which get computed into numpy arrays by np.einsum_path
@sjperkins

Copy link
Copy Markdown
Member Author

OK I hope thats it. tests and flake8 succeed locally for me.

@shoyer

shoyer commented Apr 19, 2018

Copy link
Copy Markdown
Member

Travis-CI is failing due to an ImportError for toolz in unrelated files:
https://travis-ci.org/dask/dask/jobs/368350028

This looks entirely unrelated, so I think we are good to merge here.

The process described in the second half of #3412 (comment), requires an extra da.sum (for einsum) or da.any (for isin) to remove the dummy singleton contraction dimensions. I think this introduces an extra layer of tasks into the graph that could probably be elided by additional logic in top or atop, by simply reducing the dimensionality of the appropriate key tuples.

I don't think this is possible. The extra summation is necessary for combining the chunks, whether they have size 1 or are scalars.

Suppose we want to sum an array with 1000 chunks of size 1000 each, e.g., da.arange(int(1e6), chunks=1000).sum() using einsum:

  1. We need to sum each chunk. Now we have 1000 intermediate results that are either size (1,) or scalars.
  2. We need to sum the intermediate results, by adding them all together.

There is no skipping step 2. The individual chunks need to be combined somehow.

@mrocklin

Copy link
Copy Markdown
Member

OK, merging. Thank you so much @sjperkins for the great work here. Thank you @shoyer, @jakirkham, and @dgasmith for the careful review

@mrocklin
mrocklin merged commit 60f7e5a into dask:master Apr 19, 2018
@sjperkins

Copy link
Copy Markdown
Member Author

Likewise, thanks for the reviews, assistance and accepting the PR.

Also thanks to @chrisbarber for providing the base implementation.

@sjperkins
sjperkins deleted the einsum-implementation branch April 19, 2018 09:52
@jakirkham

Copy link
Copy Markdown
Member

Thanks @sjperkins. Very nice contribution. :)

@jakirkham jakirkham mentioned this pull request Apr 19, 2018
@jakirkham

Copy link
Copy Markdown
Member

FYI from master on Python 3.4, NumPy 1.10.

Side note: Sorry for the junk in the snippet. Travis CI injects some term color junk in there that wasn't easy to strip.

�[1m�[31m_____________________ test_einsum_optimize[optimize_opts0] _____________________�[0m
[gw2] linux -- Python 3.4.5 /home/travis/miniconda/envs/test-environment/bin/python

optimize_opts = (True, False)

�[1m    @pytest.mark.parametrize('optimize_opts', [�[0m
�[1m        (True, False),�[0m
�[1m        ('greedy', False),�[0m
�[1m        ('optimal', False)�[0m
�[1m    ])�[0m
�[1m    def test_einsum_optimize(optimize_opts):�[0m
�[1m        sig = 'ea,fb,abcd,gc,hd->efgh'�[0m
�[1m        input_sigs = sig.split('->')[0].split(',')�[0m
�[1m        np_inputs, da_inputs = _numpy_and_dask_inputs(input_sigs)�[0m
�[1m    �[0m
�[1m        opt1, opt2 = optimize_opts�[0m
�[1m    �[0m
�[1m>       assert_eq(np.einsum(sig, *np_inputs, optimize=opt1),�[0m
�[1m                  da.einsum(sig, *np_inputs, optimize=opt2))�[0m
�[1m�[31mE       TypeError: 'optimize' is an invalid keyword for einsum�[0m

�[1m�[31mdask/array/tests/test_routines.py�[0m:1371: TypeError
�[1m�[31m_____________________ test_einsum_optimize[optimize_opts1] _____________________�[0m
[gw2] linux -- Python 3.4.5 /home/travis/miniconda/envs/test-environment/bin/python

optimize_opts = ('greedy', False)

�[1m    @pytest.mark.parametrize('optimize_opts', [�[0m
�[1m        (True, False),�[0m
�[1m        ('greedy', False),�[0m
�[1m        ('optimal', False)�[0m
�[1m    ])�[0m
�[1m    def test_einsum_optimize(optimize_opts):�[0m
�[1m        sig = 'ea,fb,abcd,gc,hd->efgh'�[0m
�[1m        input_sigs = sig.split('->')[0].split(',')�[0m
�[1m        np_inputs, da_inputs = _numpy_and_dask_inputs(input_sigs)�[0m
�[1m    �[0m
�[1m        opt1, opt2 = optimize_opts�[0m
�[1m    �[0m
�[1m>       assert_eq(np.einsum(sig, *np_inputs, optimize=opt1),�[0m
�[1m                  da.einsum(sig, *np_inputs, optimize=opt2))�[0m
�[1m�[31mE       TypeError: 'optimize' is an invalid keyword for einsum�[0m

�[1m�[31mdask/array/tests/test_routines.py�[0m:1371: TypeError
�[1m�[31m_____________________ test_einsum_optimize[optimize_opts2] _____________________�[0m
[gw2] linux -- Python 3.4.5 /home/travis/miniconda/envs/test-environment/bin/python

optimize_opts = ('optimal', False)

�[1m    @pytest.mark.parametrize('optimize_opts', [�[0m
�[1m        (True, False),�[0m
�[1m        ('greedy', False),�[0m
�[1m        ('optimal', False)�[0m
�[1m    ])�[0m
�[1m    def test_einsum_optimize(optimize_opts):�[0m
�[1m        sig = 'ea,fb,abcd,gc,hd->efgh'�[0m
�[1m        input_sigs = sig.split('->')[0].split(',')�[0m
�[1m        np_inputs, da_inputs = _numpy_and_dask_inputs(input_sigs)�[0m
�[1m    �[0m
�[1m        opt1, opt2 = optimize_opts�[0m
�[1m    �[0m
�[1m>       assert_eq(np.einsum(sig, *np_inputs, optimize=opt1),�[0m
�[1m                  da.einsum(sig, *np_inputs, optimize=opt2))�[0m
�[1m�[31mE       TypeError: 'optimize' is an invalid keyword for einsum�[0m

�[1m�[31mdask/array/tests/test_routines.py�[0m:1371: TypeError

ref: https://travis-ci.org/dask/dask/jobs/369157407
ref: https://api.travis-ci.org/v3/job/369157407/log.txt

@shoyer

shoyer commented Apr 20, 2018 via email

Copy link
Copy Markdown
Member

@jakirkham jakirkham mentioned this pull request Apr 20, 2018
2 of 3 tasks
@jakirkham

Copy link
Copy Markdown
Member

Resolved with PR ( #3428 ).

mattjj added a commit to jax-ml/jax that referenced this pull request Dec 19, 2018
The new cases are based on these test cases from dask:
dask/dask#3412
mattjj added a commit to jax-ml/jax that referenced this pull request Dec 19, 2018
The new cases are based on these test cases from dask:
dask/dask#3412
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants