|
| 1 | +from contextlib import contextmanager |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +_BACKEND_ENGINE = "numpy" |
| 5 | + |
| 6 | + |
| 7 | +def backend(): |
| 8 | + return _BACKEND_ENGINE |
| 9 | + |
| 10 | + |
| 11 | +def set_backend(library_name): |
| 12 | + """ |
| 13 | + Set backend engine. |
| 14 | +
|
| 15 | + The function sets the backend engine in global level. |
| 16 | +
|
| 17 | + Parameters |
| 18 | + ---------- |
| 19 | + library_name : str |
| 20 | + Library name. Default is `numpy`. Options are `numpy`, `tensorflow`, |
| 21 | + `cupy` and `jax`. |
| 22 | + """ |
| 23 | + assert library_name.lower() in ["numpy", "tensorflow", "cupy", "jax"], ( |
| 24 | + "Only `numpy`, `tensorflow`, `cupy` and `jax` are supported, but not " |
| 25 | + f"{library_name}" |
| 26 | + ) |
| 27 | + global _BACKEND_ENGINE |
| 28 | + _BACKEND_ENGINE = library_name |
| 29 | + |
| 30 | + |
| 31 | +@contextmanager |
| 32 | +def use_backend(library_name="numpy"): |
| 33 | + """ |
| 34 | + NumPy engine selection. |
| 35 | +
|
| 36 | + The function is a context manager to enable users to switch to a |
| 37 | + specific library as a replacement of NumPy in CPU. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + library_name : str |
| 42 | + Library name. Default is `numpy`. Options are `numpy`, `tensorflow`, |
| 43 | + `cupy` and `jax`. |
| 44 | + """ |
| 45 | + assert library_name.lower() in ["numpy", "tensorflow", "cupy", "jax"], ( |
| 46 | + "Only `numpy`, `tensorflow`, `cupy` and `jax` are supported, but not " |
| 47 | + f"{library_name}" |
| 48 | + ) |
| 49 | + global _BACKEND_ENGINE |
| 50 | + _original = _BACKEND_ENGINE |
| 51 | + try: |
| 52 | + _BACKEND_ENGINE = library_name |
| 53 | + if _BACKEND_ENGINE == "tensorflow": |
| 54 | + import tensorflow.experimental.numpy as np |
| 55 | + |
| 56 | + np.experimental_enable_numpy_behavior() |
| 57 | + yield |
| 58 | + finally: |
| 59 | + _BACKEND_ENGINE = _original |
| 60 | + |
| 61 | + |
| 62 | +class NumpyEngine: |
| 63 | + """ |
| 64 | + NumPy engine. |
| 65 | + """ |
| 66 | + |
| 67 | + @property |
| 68 | + def name(self): |
| 69 | + """ |
| 70 | + Get engine name. |
| 71 | + """ |
| 72 | + global _BACKEND_ENGINE |
| 73 | + return _BACKEND_ENGINE |
| 74 | + |
| 75 | + def __getattribute__(self, __name: str) -> Any: |
| 76 | + global _BACKEND_ENGINE |
| 77 | + try: |
| 78 | + if _BACKEND_ENGINE == "numpy": |
| 79 | + import numpy as anp |
| 80 | + elif _BACKEND_ENGINE == "tensorflow": |
| 81 | + import tensorflow.experimental.numpy as anp |
| 82 | + elif _BACKEND_ENGINE == "cupy": |
| 83 | + import cupy as anp |
| 84 | + elif _BACKEND_ENGINE == "jax": |
| 85 | + import jax.numpy as anp |
| 86 | + else: |
| 87 | + raise ValueError(f"Cannot recognize backend {_BACKEND_ENGINE}") |
| 88 | + except ImportError: |
| 89 | + raise ImportError( |
| 90 | + "Library `numpy` cannot be imported from backend engine " |
| 91 | + f"{_BACKEND_ENGINE}. Please make sure to install the library " |
| 92 | + f"via `pip install {_BACKEND_ENGINE}`." |
| 93 | + ) |
| 94 | + |
| 95 | + try: |
| 96 | + return getattr(anp, __name) |
| 97 | + except AttributeError: |
| 98 | + raise AttributeError( |
| 99 | + "Cannot get attribute / function from numpy library in " |
| 100 | + f"backend engine {_BACKEND_ENGINE}" |
| 101 | + ) |
| 102 | + |
| 103 | + |
| 104 | +class LinAlgEngine: |
| 105 | + """ |
| 106 | + Linear algebra engine. |
| 107 | + """ |
| 108 | + |
| 109 | + @property |
| 110 | + def name(self): |
| 111 | + """ |
| 112 | + Get engine name. |
| 113 | + """ |
| 114 | + global _BACKEND_ENGINE |
| 115 | + return _BACKEND_ENGINE |
| 116 | + |
| 117 | + def __getattribute__(self, __name: str) -> Any: |
| 118 | + global _BACKEND_ENGINE |
| 119 | + try: |
| 120 | + if _BACKEND_ENGINE == "numpy": |
| 121 | + import numpy.linalg as alinalg |
| 122 | + elif _BACKEND_ENGINE == "tensorflow": |
| 123 | + import tensorflow.linalg as alinalg |
| 124 | + elif _BACKEND_ENGINE == "cupy": |
| 125 | + import cupy.linalg as alinalg |
| 126 | + elif _BACKEND_ENGINE == "jax": |
| 127 | + import jax.numpy.linalg as alinalg |
| 128 | + else: |
| 129 | + raise ValueError(f"Cannot recognize backend {_BACKEND_ENGINE}") |
| 130 | + except ImportError: |
| 131 | + raise ImportError( |
| 132 | + "Library `linalg` cannot be imported from backend engine " |
| 133 | + f"{_BACKEND_ENGINE}. Please make sure to install the library " |
| 134 | + f"via `pip install {_BACKEND_ENGINE}`." |
| 135 | + ) |
| 136 | + |
| 137 | + try: |
| 138 | + return getattr(alinalg, __name) |
| 139 | + except AttributeError: |
| 140 | + raise AttributeError( |
| 141 | + "Cannot get attribute / function from linalg library in " |
| 142 | + f"backend engine {_BACKEND_ENGINE}" |
| 143 | + ) |
| 144 | + |
| 145 | + |
| 146 | +def fori_loop(lower, upper, body_fun, init_val=None): |
| 147 | + global _BACKEND_ENGINE |
| 148 | + if _BACKEND_ENGINE in ["numpy", "cupy"]: |
| 149 | + val = init_val |
| 150 | + for i in range(lower, upper): |
| 151 | + val = body_fun(i, val) |
| 152 | + return val |
| 153 | + elif _BACKEND_ENGINE == "jax": |
| 154 | + import jax.lax |
| 155 | + |
| 156 | + return jax.lax.fori_loop(lower, upper, body_fun, init_val) |
| 157 | + elif _BACKEND_ENGINE == "tensorflow": |
| 158 | + import tensorflow as tf |
| 159 | + |
| 160 | + i = tf.constant(lower) |
| 161 | + while_condition = lambda i: tf.less(i, upper) |
| 162 | + |
| 163 | + def body(i, val): |
| 164 | + return [tf.add(i, 1), body_fun(val)] |
| 165 | + |
| 166 | + return tf.while_loop(while_condition, body, [i, init_val]) |
| 167 | + |
| 168 | + raise ImportError(f"Cannot recognize backend {_BACKEND_ENGINE}") |
| 169 | + |
| 170 | + |
| 171 | +numpy = NumpyEngine() |
| 172 | +linalg = LinAlgEngine() |
0 commit comments