forked from dgasmith/opt_einsum
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
77 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
""" | ||
Required functions for optimized contractions of numpy arrays using tensorflow. | ||
""" | ||
import numpy as np | ||
|
||
from ..sharing import to_backend_cache_wrap | ||
|
||
__all__ = ["build_expression", "evaluate_constants"] | ||
|
||
|
||
_tensorflow = None | ||
|
||
|
||
def _get_tensorflow_and_to_tensorflow(): | ||
global _tensorflow | ||
if _tensorflow is None: | ||
import tensorflow | ||
|
||
@to_backend_cache_wrap | ||
def to_tensorflow(array): | ||
if isinstance(array, np.ndarray): | ||
return tensorflow.convert_to_tensor(array) | ||
return array | ||
|
||
_tensorflow = tensorflow, to_tensorflow | ||
|
||
return _tensorflow | ||
|
||
|
||
def build_expression(_, expr): # pragma: no cover | ||
"""Build a tensorflow function based on ``arrays`` and ``expr``. | ||
""" | ||
tensorflow, to_tensorflow = _get_tensorflow_and_to_tensorflow() | ||
tensorflow_expr = tensorflow.function( | ||
expr._contract, | ||
autograph=False, | ||
experimental_compile=True, | ||
) | ||
|
||
def tensorflow_contract(*arrays): | ||
tf_arrays = tuple(map(to_tensorflow, arrays)) | ||
return tensorflow_expr(tf_arrays).numpy() | ||
|
||
return tensorflow_contract | ||
|
||
|
||
def evaluate_constants(const_arrays, expr): # pragma: no cover | ||
"""Convert constant arguments to tensorflow arrays, and perform any possible | ||
constant contractions. | ||
""" | ||
_, to_tensorflow = _get_tensorflow_and_to_tensorflow() | ||
return expr(*[to_tensorflow(x) for x in const_arrays], backend='tensorflow', evaluate_constants=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters