In [1]:
import tensorflow as tf

In [2]:
from pycalphad import Database, Model, variables as v
from pycalphad.codegen.sympydiff_utils import build_functions
from sympy import lambdify
import numpy as np

dbf = Database('Al-Cu-Zr_Zhou.tdb')
mod = Model(dbf, ['AL', 'CU', 'ZR'], 'LIQUID')

In [3]:
mod.variables


Out[3]:
[T, LIQUID0AL, LIQUID0CU, LIQUID0ZR]

Expression Building


In [4]:
%time bfr = build_functions(mod.GM, mod.variables, include_grad=True)


Wall time: 377 ms

In [5]:
%%timeit
tf_func = lambdify(mod.variables, mod.GM, modules='tensorflow')
tf_grads = lambdify(mod.variables, [mod.GM.diff(x) for x in mod.variables], modules='tensorflow')


632 ms ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [6]:
tf_func = lambdify(mod.variables, mod.GM, modules='tensorflow')
tf_grads = lambdify(mod.variables, [mod.GM.diff(x) for x in mod.variables], modules='tensorflow')

In [7]:
%%timeit
func_xla = tf.function(experimental_compile=True)(tf_func)
grad_xla = tf.function(experimental_compile=True)(tf_grads)


93 µs ± 3.83 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [8]:
func_xla = tf.function(experimental_compile=True)(tf_func)
grad_xla = tf.function(experimental_compile=True)(tf_grads)

Function Evaluation


In [9]:
out = np.array([0.])
%timeit bfr.func.unsafe_real(np.array([300., 0.3, 0.3, 0.4]), out)
print(out)


3.94 µs ± 189 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
[-41178.9428136]

In [10]:
out = np.zeros(4)
%timeit bfr.grad.unsafe_real(np.array([300., 0.3, 0.3, 0.4]), out)
print(out)


4.27 µs ± 84.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
[-3.39000632e+01 -6.67993032e+04 -2.12186404e+04 -3.12432907e+04]

In [11]:
%timeit func_xla(300.0, 0.3, 0.3, 0.4)


202 µs ± 76.5 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [12]:
%timeit grad_xla(300.0, 0.3, 0.3, 0.4)


299 µs ± 71.8 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [13]:
temps = tf.constant(np.linspace(300., 2000., num=1000, dtype=np.float32))
%timeit grad_xla(temps, 0.3, 0.3, 0.4)


480 µs ± 76.4 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [ ]: