File: conftest.py

package info (click to toggle)
python-einx 0.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,112 kB
  • sloc: python: 11,619; makefile: 13
file content (272 lines) | stat: -rw-r--r-- 7,359 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import importlib
import numpy as np
import types
import einx
import threading
import multiprocessing
import os

tests = []


class WrappedEinx:
    def __init__(self, wrap, name, inline_args):
        import einx

        self.einx = einx
        self.in_func = False
        self.wrap = wrap
        self.name = name
        self.inline_args = inline_args

    def __enter__(self):
        assert not self.in_func
        self.in_func = True

    def __exit__(self, *args):
        assert self.in_func
        self.in_func = False

    def __getattr__(self, attr):
        op = getattr(self.einx, attr)
        if self.in_func or attr in {"matches", "solve", "check", "trace"}:
            return op

        if self.inline_args:

            def op3(*args, **kwargs):
                with self:

                    def op2():
                        return op(*args, **kwargs)

                    op2 = self.wrap(op2)
                    op2()
                    return op2()

            return op3
        else:

            def op3(*args, **kwargs):
                with self:
                    op2 = self.wrap(op)
                    op2(*args, **kwargs)
                    return op2(*args, **kwargs)

            return op3


def in_new_thread(op):
    def inner(*args, **kwargs):
        result = [None, None]

        def run(result):
            try:
                result[0] = op(*args, **kwargs)
            except Exception as e:
                result[1] = e

        thread = threading.Thread(target=run, args=(result,))
        thread.start()
        thread.join()
        if result[1] is not None:
            raise result[1]
        else:
            return result[0]

    return inner


einx_multithread = WrappedEinx(in_new_thread, "multithreading", inline_args=True)


def in_new_process(op):
    def inner(*args, **kwargs):
        result = multiprocessing.Queue()
        exception = multiprocessing.Queue()

        def run(result, exception):
            try:
                result.put(op(*args, **kwargs))
            except Exception as e:
                exception.put(e)

        process = multiprocessing.Process(target=run, args=(result, exception))
        process.start()
        process.join()
        if not exception.empty():
            raise exception.get()
        else:
            return result.get()

    return inner


einx_multiprocess = WrappedEinx(in_new_process, "multiprocessing", inline_args=True)


# numpy is always available
import numpy as np

backend = einx.backend.numpy.create()

test = types.SimpleNamespace(
    full=lambda shape, value=0.0, dtype="float32": np.full(shape, value, dtype=dtype),
    to_tensor=np.asarray,
    to_numpy=np.asarray,
)

tests.append((einx, backend, test))
tests.append((einx_multithread, backend, test))
# tests.append((einx_multiprocess, backend, test)) # too slow


if importlib.util.find_spec("jax"):
    os.environ["XLA_FLAGS"] = (
        os.environ.get("XLA_FLAGS", "") + " --xla_force_host_platform_device_count=8"
    )

    import jax
    import jax.numpy as jnp

    einx_jit = WrappedEinx(jax.jit, "jax.jit", inline_args=True)

    backend = einx.backend.jax.create()

    test_cpu = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32": jax.device_put(
            jnp.full(shape, value, dtype=dtype), device=jax.devices("cpu")[0]
        ),
        to_tensor=lambda x: jax.device_put(jnp.asarray(x), device=jax.devices("cpu")[0]),
        to_numpy=np.asarray,
    )

    tests.append((einx, backend, test_cpu))
    tests.append((einx_jit, backend, test_cpu))

    try:
        jax.devices("gpu")
        has_gpu = True
    except:
        has_gpu = False

    if has_gpu:
        test_gpu = types.SimpleNamespace(
            full=lambda shape, value=0.0, dtype="float32": jax.device_put(
                jnp.full(shape, value, dtype=dtype), device=jax.devices("gpu")[0]
            ),
            to_tensor=lambda x: jax.device_put(jnp.asarray(x), device=jax.devices("gpu")[0]),
            to_numpy=np.asarray,
        )

        tests.append((einx, backend, test_gpu))
        tests.append((einx_jit, backend, test_gpu))

if importlib.util.find_spec("torch"):
    import torch

    version = tuple(int(i) for i in torch.__version__.split(".")[:2])

    def wrap(op):
        torch.compiler.reset()
        return torch.compile(op)

    einx_torchcompile = WrappedEinx(wrap, "torch.compile", inline_args=False)

    backend = einx.backend.torch.create()

    dtypes = {
        "float32": torch.float32,
        "long": torch.long,
        "bool": torch.bool,
    }

    test_cpu = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32", backend=backend: torch.full(
            backend.to_tuple(shape), value, dtype=dtypes[dtype]
        ),
        to_tensor=lambda tensor: torch.asarray(tensor, device=torch.device("cpu")),
        to_numpy=lambda tensor: tensor.numpy(),
    )

    tests.append((einx, backend, test_cpu))
    if version >= (2, 1):
        tests.append((einx_torchcompile, backend, test_cpu))

    if torch.cuda.is_available():
        test_gpu = types.SimpleNamespace(
            full=lambda shape, value=1.0, dtype="float32", backend=backend: torch.full(
                backend.to_tuple(shape), value, dtype=dtypes[dtype], device=torch.device("cuda")
            ),
            to_tensor=lambda tensor: torch.asarray(tensor, device=torch.device("cuda")),
            to_numpy=lambda tensor: tensor.cpu().numpy(),
        )

        tests.append((einx, backend, test_gpu))
        if version >= (2, 1):
            tests.append((einx_torchcompile, backend, test_gpu))

if importlib.util.find_spec("tensorflow"):
    import os

    os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
    import tensorflow as tf
    import tensorflow.experimental.numpy as tnp

    tnp.experimental_enable_numpy_behavior()

    backend = einx.backend.tensorflow.create()

    test = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32": tnp.full(shape, value, dtype=dtype),
        to_tensor=tf.convert_to_tensor,
        to_numpy=lambda x: x.numpy(),
    )

    tests.append((einx, backend, test))

if importlib.util.find_spec("mlx"):
    import mlx.core as mx

    backend = einx.backend.mlx.create()

    test = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32", backend=backend: mx.full(
            shape, value, dtype=backend.to_dtype(dtype)
        ),
        to_tensor=mx.array,
        to_numpy=np.asarray,
    )

    tests.append((einx, backend, test))

if importlib.util.find_spec("dask"):
    import dask.array as da

    backend = einx.backend.dask.create()

    test = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32": da.full(shape, value, dtype=dtype),
        to_tensor=np.asarray,
        to_numpy=np.asarray,
    )

    tests.append((einx, backend, test))

if importlib.util.find_spec("tinygrad"):
    import os

    os.environ["PYTHON"] = "1"
    from tinygrad import Tensor

    backend = einx.backend.tinygrad.create()

    test = types.SimpleNamespace(
        full=lambda shape, value=0.0, dtype="float32": Tensor.full(
            shape, value, dtype=backend.to_dtype(dtype)
        ),
        to_tensor=Tensor,
        to_numpy=lambda x: x.numpy(),
    )

    tests.append((einx, backend, test))