In [1]:
import tf_einsum_opt
import tensorflow as tf
import numpy as np
In [2]:
sess = tf.Session()
In [3]:
def func(a, b, c):
res = tf.einsum('ijk,ja,kb->iab', a, b, c) + 1
res = tf.einsum('iab,kb->iak', res, c)
return res
a = tf.random_normal((10, 11, 12))
b = tf.random_normal((11, 13))
c = tf.random_normal((12, 14))
# res = func(a, b, c)
orders, optimized_func = tf_einsum_opt.optimizer(func, sess, a, b, c)
In [8]:
res1 = func(a, b, c)
%timeit sess.run(res1)
In [9]:
res2 = optimized_func(a, b, c)
%timeit sess.run(res2)
In [12]:
# Check that the results of optimized and the original function are the same.
np.testing.assert_allclose(*sess.run([res1, res2]), rtol=1e-5, atol=1e-5)
In [13]:
def func(a, b, c, d):
res = tf.einsum('si,sj,sk,ij->s', a, b, d, c)
res += tf.einsum('s,si->s', res, a)
return res
a = tf.random_normal((100, 101))
b = tf.random_normal((100, 102))
c = tf.random_normal((101, 102))
d = tf.random_normal((100, 30))
orders, optimized_func = tf_einsum_opt.optimizer(func, sess, a, b, c, d)
In [5]:
res1 = func(a, b, c, d)
%timeit sess.run(res1)
In [6]:
res2 = optimized_func(a, b, c, d)
%timeit sess.run(res2)
In [14]:
orders
Out[14]:
It means "in file <ipython-input-13-1748bfc6b08e> line 2 change the order of arguments of einsum using permutation [0, 3, 1, 2]", i.e. from tf.einsum('si,sj,sk,ij->s', a, b, d, c) to tf.einsum('si,ij,sj,sk->s', a, c, b, d)