dgasmith / opt_einsum

⚡️Optimizing einsum functions in NumPy, Tensorflow, Dask, and more with contraction order optimization.
https://dgasmith.github.io/opt_einsum/
MIT License
822 stars 67 forks source link

Reuse path including a scalar constant in the contraction #186

Closed Geositta2000 closed 2 years ago

Geositta2000 commented 2 years ago

Hi,

I am thinking about including a scalar constant into the opt_einsum contraction, which may utilize the alpha/beta coefficient in DGEMM as in https://stackoverflow.com/questions/72356384/how-to-utilize-scalar-multiplication-in-einsum

The following code works

import opt_einsum as oe

dim = 30
I = np.random.rand(dim, dim, dim, dim)
C = np.random.rand(dim, dim)
path_info = oe.contract_path(',pi,qj,ijkl,rk,sl->pqrs', 3.0, C, C, I, C, C)

Then I think about reuse path, similar to https://optimized-einsum.readthedocs.io/en/stable/reusing_paths.html

path_info = oe.contract_expression(', pi,qj,ijkl,rk,sl->pqrs', (1), (dim, dim), (dim, dim), (dim, dim, dim, dim), (dim, dim), (dim, dim))

I got if len(sh) != len(term): TypeError: object of type 'int' has no len()

How to solve this issue? Which dimension should I use for the constant scalar part?

jcmgray commented 2 years ago

Hi @Geositta2000, scalars have no dimensions, so the correct way to specify their shape is an empty tuple like:

shape = ()
len(shape)
# 0

N.B. (1) actually expands to just the integer 1, whereas (1,) would be the shape of vector of length 1.

Geositta2000 commented 2 years ago

Thank you! path_info = oe.contract_expression(', pi,qj,ijkl,rk,sl->pqrs', (), (dim, dim), (dim, dim), (dim, dim, dim, dim), (dim, dim), (dim, dim)) works!