Repository navigation
einsum implementation - #3412
Conversation
|
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! |
|
Hmmmm, relaxing the comparison in the third test from |
|
Cool, starts to use the new internal 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 |
|
cc @shoyer @jakirkham you may want to see this |
| assert da.result_type(a, c) == np.float64 | ||
|
|
||
|
|
||
| def test_einsum(): |
There was a problem hiding this comment.
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))|
I think it would be straightforward to only support A comment on the implementation: it would be best to avoid using Instead, we should keep all contracted dimensions as size 1 in each chunk with |
|
Actually, it looks like @chrisbarber's latest version of |
The optimize keyword can be bool or str
|
I'll take a look at implementing your review comments over the next couple of days. |
|
Changes seemed fairly easy to make. Would you mind taking a look? |
| casting=kwargs['casting'], | ||
| dtype=kwargs['kernel_dtype'], | ||
| order=kwargs['order'], | ||
| optimize=kwargs['optimize']) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
+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)
...
| casting=kwargs['casting'], | ||
| dtype=kwargs['kernel_dtype'], | ||
| order=kwargs['order'], | ||
| optimize=kwargs['optimize']) |
There was a problem hiding this comment.
+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)
...
| def einsum(subscripts, *operands, **kwargs): | ||
| casting = kwargs.get('casting', 'safe') | ||
| dtype = kwargs.get('dtype') | ||
| optimize = kwargs.get('optimize', True) |
There was a problem hiding this comment.
I was thinking something like:
optimize = kwargs.get('optimize')
...
if optimize is None:
optimize = can_optimize
There was a problem hiding this comment.
optimize can be {True, False, 'greedy', 'optimal'}, so it would be best not to be destructive of the user's input.
| # 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)) |
There was a problem hiding this comment.
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', |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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',
There was a problem hiding this comment.
@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
First alphabetical index
Apologies and good catch, this revealed a mistake in how |
|
Rats, just thought of something ... in order to produce an optimized path, Any thoughts on how to work around this? |
|
Copy it too? Maybe someone else has a better idea. |
|
Thanks for the optimization tests. Looks good. |
You can make dummy numpy arrays with the right shape with repeated values (with strides) by using |
Oh nice. I actually thought of [np.empty((1,)*o.ndim, o.dtype) for o in operands] but this should work well! |
|
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
|
OK I hope thats it. tests and flake8 succeed locally for me. |
|
Travis-CI is failing due to an ImportError for toolz in unrelated files: This looks entirely unrelated, so I think we are good to merge here.
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.,
There is no skipping step 2. The individual chunks need to be combined somehow. |
|
OK, merging. Thank you so much @sjperkins for the great work here. Thank you @shoyer, @jakirkham, and @dgasmith for the careful review |
|
Likewise, thanks for the reviews, assistance and accepting the PR. Also thanks to @chrisbarber for providing the base implementation. |
|
Thanks @sjperkins. Very nice contribution. :) |
|
FYI from 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: TypeErrorref: https://travis-ci.org/dask/dask/jobs/369157407 |
|
Oops, I guess we need to add a skipif.
…On Fri, Apr 20, 2018 at 7:53 AM jakirkham ***@***.***> wrote:
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
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#3412 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/ABKS1iAv5pRQtIvl1Jo4Mspor5uD4v42ks5tqfZqgaJpZM4TXLC8>
.
|
|
Resolved with PR ( #3428 ). |
The new cases are based on these test cases from dask: dask/dask#3412
The new cases are based on these test cases from dask: dask/dask#3412
flake8 daskdocs/source/changelog.rstfor all changesand one of the
docs/source/*-api.rstfiles for new API