Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make JAX backend import lazy. #135

Merged
merged 2 commits into from
Apr 15, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Make JAX backend import lazy.
We observed the following surprising behavior: importing tensorflow also imports jax, if installed. This happens because tensorflow has an opt_einsum dependency that is imported eagerly, and the opt_einsum jax backend eagerly imports jax. To avoid this, make the jax import from opt_einsum lazy.
  • Loading branch information
hawkinsp committed Apr 15, 2020
commit 970568e87da1e19a47629e74a3c7520c3d6d952f
17 changes: 13 additions & 4 deletions opt_einsum/backends/jax.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,29 @@

__all__ = ["build_expression", "evaluate_constants"]

try:

_JAX = None


def _get_jax_and_to_jax():
global _JAX
if _JAX is None:
import jax

@to_backend_cache_wrap
@jax.jit
def to_jax(x):
return x

except ImportError:
pass
_JAX = jax, to_jax

return _JAX


def build_expression(_, expr): # pragma: no cover
"""Build a jax function based on ``arrays`` and ``expr``.
"""
import jax
jax, _ = _get_jax_and_to_jax()

jax_expr = jax.jit(expr._contract)

Expand All @@ -37,4 +44,6 @@ def evaluate_constants(const_arrays, expr): # pragma: no cover
"""Convert constant arguments to jax arrays, and perform any possible
constant contractions.
"""
jax, to_jax = _get_jax_and_to_jax()

return expr(*[to_jax(x) for x in const_arrays], backend='jax', evaluate_constants=True)