Debian Codegraph @

ot/backend.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Multi-lib backend for POT
4
5 The goal is to write backend-agnostic code. Whether you're using Numpy, PyTorch,
6 Jax, Cupy, or Tensorflow, POT code should work nonetheless.
7 To achieve that, POT provides backend classes which implements functions in their respective backend
8 imitating Numpy API. As a convention, we use nx instead of np to refer to the backend.
9
10 Examples
11 --------
12
13 >>> from ot.utils import list_to_array
14 >>> from ot.backend import get_backend
15 >>> def f(a, b): # the function does not know which backend to use
16 ... a, b = list_to_array(a, b) # if a list in given, make it an array
17 ... nx = get_backend(a, b) # infer the backend from the arguments
18 ... c = nx.dot(a, b) # now use the backend to do any calculation
19 ... return c
20
21 .. warning::
22 Tensorflow only works with the Numpy API. To activate it, please run the following:
23
24 .. code-block::
25
26 from tensorflow.python.ops.numpy_ops import np_config
27 np_config.enable_numpy_behavior()
28
29 Performance
30 -----------
31
32 - CPU: Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz
33 - GPU: Tesla V100-SXM2-32GB
34 - Date of the benchmark: December 8th, 2021
35 - Commit of benchmark: PR #316, https://github.com/PythonOT/POT/pull/316
36
37 .. raw:: html
38
39 <style>
40 #perftable {
41 width: 100%;
42 margin-bottom: 1em;
43 }
44
45 #perftable table{
46 border-collapse: collapse;
47 table-layout: fixed;
48 width: 100%;
49 }
50
51 #perftable th, #perftable td {
52 border: 1px solid #ddd;
53 padding: 8px;
54 font-size: smaller;
55 }
56 </style>
57
58 <div id="perftable">
59 <table>
60 <tr><th align="center" colspan="8">Sinkhorn Knopp - Averaged on 100 runs</th></tr>
61 <tr><th align="center">Bitsize</th><th align="center" colspan="7">32 bits</th></tr>
62 <tr><th align="center">Device</th><th align="center" colspan="3.0"">CPU</th><th align="center" colspan="4.0">GPU</tr>
63 <tr><th align="center">Sample size</th><th align="center">Numpy</th><th align="center">Pytorch</th><th align="center">Tensorflow</th><th align="center">Cupy</th><th align="center">Jax</th><th align="center">Pytorch</th><th align="center">Tensorflow</th></tr>
64 <tr><td align="center">50</td><td align="center">0.0008</td><td align="center">0.0022</td><td align="center">0.0151</td><td align="center">0.0095</td><td align="center">0.0193</td><td align="center">0.0051</td><td align="center">0.0293</td></tr>
65 <tr><td align="center">100</td><td align="center">0.0005</td><td align="center">0.0013</td><td align="center">0.0097</td><td align="center">0.0057</td><td align="center">0.0115</td><td align="center">0.0029</td><td align="center">0.0173</td></tr>
66 <tr><td align="center">500</td><td align="center">0.0009</td><td align="center">0.0016</td><td align="center">0.0110</td><td align="center">0.0058</td><td align="center">0.0115</td><td align="center">0.0029</td><td align="center">0.0166</td></tr>
67 <tr><td align="center">1000</td><td align="center">0.0021</td><td align="center">0.0021</td><td align="center">0.0145</td><td align="center">0.0056</td><td align="center">0.0118</td><td align="center">0.0029</td><td align="center">0.0168</td></tr>
68 <tr><td align="center">2000</td><td align="center">0.0069</td><td align="center">0.0043</td><td align="center">0.0278</td><td align="center">0.0059</td><td align="center">0.0118</td><td align="center">0.0030</td><td align="center">0.0165</td></tr>
69 <tr><td align="center">5000</td><td align="center">0.0707</td><td align="center">0.0314</td><td align="center">0.1395</td><td align="center">0.0074</td><td align="center">0.0125</td><td align="center">0.0035</td><td align="center">0.0198</td></tr>
70 <tr><td colspan="8">&nbsp;</td></tr>
71 <tr><th align="center">Bitsize</th><th align="center" colspan="7">64 bits</th></tr>
72 <tr><th align="center">Device</th><th align="center" colspan="3.0"">CPU</th><th align="center" colspan="4.0">GPU</tr>
73 <tr><th align="center">Sample size</th><th align="center">Numpy</th><th align="center">Pytorch</th><th align="center">Tensorflow</th><th align="center">Cupy</th><th align="center">Jax</th><th align="center">Pytorch</th><th align="center">Tensorflow</th></tr>
74 <tr><td align="center">50</td><td align="center">0.0008</td><td align="center">0.0020</td><td align="center">0.0154</td><td align="center">0.0093</td><td align="center">0.0191</td><td align="center">0.0051</td><td align="center">0.0328</td></tr>
75 <tr><td align="center">100</td><td align="center">0.0005</td><td align="center">0.0013</td><td align="center">0.0094</td><td align="center">0.0056</td><td align="center">0.0114</td><td align="center">0.0029</td><td align="center">0.0169</td></tr>
76 <tr><td align="center">500</td><td align="center">0.0013</td><td align="center">0.0017</td><td align="center">0.0120</td><td align="center">0.0059</td><td align="center">0.0116</td><td align="center">0.0029</td><td align="center">0.0168</td></tr>
77 <tr><td align="center">1000</td><td align="center">0.0034</td><td align="center">0.0027</td><td align="center">0.0177</td><td align="center">0.0058</td><td align="center">0.0118</td><td align="center">0.0029</td><td align="center">0.0167</td></tr>
78 <tr><td align="center">2000</td><td align="center">0.0146</td><td align="center">0.0075</td><td align="center">0.0436</td><td align="center">0.0059</td><td align="center">0.0120</td><td align="center">0.0029</td><td align="center">0.0165</td></tr>
79 <tr><td align="center">5000</td><td align="center">0.1467</td><td align="center">0.0568</td><td align="center">0.2468</td><td align="center">0.0077</td><td align="center">0.0146</td><td align="center">0.0045</td><td align="center">0.0204</td></tr>
80 </table>
81 </div>
82 """
83
84 # Author: Remi Flamary <[email protected]>
85 # Nicolas Courty <[email protected]>
86 #
87 # License: MIT License
88
89 import os
90 import time
91 import warnings
92
93 import numpy as np
94 import scipy
95 import scipy.linalg
96 import scipy.special as special
97 from scipy.sparse import coo_matrix, csr_matrix, issparse
98
99 DISABLE_TORCH_KEY = "POT_BACKEND_DISABLE_PYTORCH"
100 DISABLE_JAX_KEY = "POT_BACKEND_DISABLE_JAX"
101 DISABLE_CUPY_KEY = "POT_BACKEND_DISABLE_CUPY"
102 DISABLE_TF_KEY = "POT_BACKEND_DISABLE_TENSORFLOW"
103
104
105 if not os.environ.get(DISABLE_TORCH_KEY, False):
106 try:
107 import torch
108
109 torch_type = torch.Tensor
110 except ImportError:
111 torch = False
112 torch_type = float
113 else:
114 torch = False
115 torch_type = float
116
117 if not os.environ.get(DISABLE_JAX_KEY, False):
118 try:
119 import jax
120 import jax.numpy as jnp
121 import jax.scipy.special as jspecial
122 from jax.lib import xla_bridge
123
124 jax_type = jax.numpy.ndarray
125 jax_new_version = float(".".join(jax.__version__.split(".")[1:])) > 4.24
126 except ImportError:
127 jax = False
128 jax_type = float
129 else:
130 jax = False
131 jax_type = float
132
133 if not os.environ.get(DISABLE_CUPY_KEY, False):
134 try:
135 import cupy as cp
136 import cupyx
137
138 cp_type = cp.ndarray
139 except ImportError:
140 cp = False
141 cp_type = float
142 else:
143 cp = False
144 cp_type = float
145
146 if not os.environ.get(DISABLE_TF_KEY, False):
147 try:
148 import tensorflow as tf
149 import tensorflow.experimental.numpy as tnp
150
151 tf_type = tf.Tensor
152 except ImportError:
153 tf = False
154 tf_type = float
155 else:
156 tf = False
157 tf_type = float
158
159
160 str_type_error = (
161 "All array should be from the same type/backend. Current types are : {}"
162 )
163
164
165 # Mapping between argument types and the existing backend
166 _BACKEND_IMPLEMENTATIONS = []
167 _BACKENDS = {}
168
169
170 def _register_backend_implementation(backend_impl):
171 _BACKEND_IMPLEMENTATIONS.append(backend_impl)
172
173
174 def _get_backend_instance(backend_impl):
175 if backend_impl.__name__ not in _BACKENDS:
176 _BACKENDS[backend_impl.__name__] = backend_impl()
177 return _BACKENDS[backend_impl.__name__]
178
179
180 def _check_args_backend(backend_impl, args):
181 is_instance = set(isinstance(arg, backend_impl.__type__) for arg in args)
182 # check that all arguments matched or not the type
183 if len(is_instance) == 1:
184 return is_instance.pop()
185
186 # Otherwise return an error
187 raise ValueError(str_type_error.format([type(arg) for arg in args]))
188
189
190 def get_backend_list():
191 """Returns instances of all available backends.
192
193 Note that the function forces all detected implementations
194 to be instantiated even if specific backend was not use before.
195 Be careful as instantiation of the backend might lead to side effects,
196 like GPU memory pre-allocation. See the documentation for more details.
197 If you only need to know which implementations are available,
198 use `:py:func:`ot.backend.get_available_backend_implementations`,
199 which does not force instance of the backend object to be created.
200 """
201 return [
202 _get_backend_instance(backend_impl)
203 for backend_impl in get_available_backend_implementations()
204 ]
205
206
207 def get_available_backend_implementations():
208 """Returns the list of available backend implementations."""
209 return _BACKEND_IMPLEMENTATIONS
210
211
212 def get_backend(*args):
213 """Returns the proper backend for a list of input arrays
214
215 Accepts None entries in the arguments, and ignores them
216
217 Also raises TypeError if all arrays are not from the same backend
218 """
219 args = [arg for arg in args if arg is not None] # exclude None entries
220
221 # check that some arrays given
222 if not len(args) > 0:
223 raise ValueError(" The function takes at least one (non-None) parameter")
224
225 for backend_impl in _BACKEND_IMPLEMENTATIONS:
226 if _check_args_backend(backend_impl, args):
227 return _get_backend_instance(backend_impl)
228
229 raise ValueError("Unknown type of non implemented backend.")
230
231
232 def to_numpy(*args):
233 """Returns numpy arrays from any compatible backend"""
234
235 if len(args) == 1:
236 return get_backend(args[0]).to_numpy(args[0])
237 else:
238 return [get_backend(a).to_numpy(a) for a in args]
239
240
241 class Backend:
242 """
243 Backend abstract class.
244 Implementations: :py:class:`JaxBackend`, :py:class:`NumpyBackend`, :py:class:`TorchBackend`,
245 :py:class:`CupyBackend`, :py:class:`TensorflowBackend`
246
247 - The `__name__` class attribute refers to the name of the backend.
248 - The `__type__` class attribute refers to the data structure used by the backend.
249 """
250
251 __name__ = None
252 __type__ = None
253 __type_list__ = None
254
255 rng_ = None
256
257 def __str__(self):
258 return self.__name__
259
260 # convert batch of tensors to numpy
261 def to_numpy(self, *arrays):
262 """Returns the numpy version of tensors"""
263 if len(arrays) == 1:
264 return self._to_numpy(arrays[0])
265 else:
266 return [self._to_numpy(array) for array in arrays]
267
268 # convert a tensor to numpy
269 def _to_numpy(self, a):
270 """Returns the numpy version of a tensor"""
271 raise NotImplementedError()
272
273 # convert batch of arrays from numpy
274 def from_numpy(self, *arrays, type_as=None):
275 """Creates tensors cloning a numpy array, with the given precision (defaulting to input's precision) and the given device (in case of GPUs)"""
276 if len(arrays) == 1:
277 return self._from_numpy(arrays[0], type_as=type_as)
278 else:
279 return [self._from_numpy(array, type_as=type_as) for array in arrays]
280
281 # convert an array from numpy
282 def _from_numpy(self, a, type_as=None):
283 """Creates a tensor cloning a numpy array, with the given precision (defaulting to input's precision) and the given device (in case of GPUs)"""
284 raise NotImplementedError()
285
286 def set_gradients(self, val, inputs, grads):
287 """Define the gradients for the value val wrt the inputs"""
288 raise NotImplementedError()
289
290 def detach(self, *arrays):
291 """Detach the tensors from the computation graph
292
293 See: https://pytorch.org/docs/stable/generated/torch.Tensor.detach.html"""
294 if len(arrays) == 1:
295 return self._detach(arrays[0])
296 else:
297 return [self._detach(array) for array in arrays]
298
299 def _detach(self, a):
300 """Detach the tensor from the computation graph"""
301 raise NotImplementedError()
302
303 def zeros(self, shape, type_as=None):
304 r"""
305 Creates a tensor full of zeros.
306
307 This function follows the api from :any:`numpy.zeros`
308
309 See: https://numpy.org/doc/stable/reference/generated/numpy.zeros.html
310 """
311 raise NotImplementedError()
312
313 def ones(self, shape, type_as=None):
314 r"""
315 Creates a tensor full of ones.
316
317 This function follows the api from :any:`numpy.ones`
318
319 See: https://numpy.org/doc/stable/reference/generated/numpy.ones.html
320 """
321 raise NotImplementedError()
322
323 def arange(self, stop, start=0, step=1, type_as=None):
324 r"""
325 Returns evenly spaced values within a given interval.
326
327 This function follows the api from :any:`numpy.arange`
328
329 See: https://numpy.org/doc/stable/reference/generated/numpy.arange.html
330 """
331 raise NotImplementedError()
332
333 def full(self, shape, fill_value, type_as=None):
334 r"""
335 Creates a tensor with given shape, filled with given value.
336
337 This function follows the api from :any:`numpy.full`
338
339 See: https://numpy.org/doc/stable/reference/generated/numpy.full.html
340 """
341 raise NotImplementedError()
342
343 def eye(self, N, M=None, type_as=None):
344 r"""
345 Creates the identity matrix of given size.
346
347 This function follows the api from :any:`numpy.eye`
348
349 See: https://numpy.org/doc/stable/reference/generated/numpy.eye.html
350 """
351 raise NotImplementedError()
352
353 def sum(self, a, axis=None, keepdims=False):
354 r"""
355 Sums tensor elements over given dimensions.
356
357 This function follows the api from :any:`numpy.sum`
358
359 See: https://numpy.org/doc/stable/reference/generated/numpy.sum.html
360 """
361 raise NotImplementedError()
362
363 def cumsum(self, a, axis=None):
364 r"""
365 Returns the cumulative sum of tensor elements over given dimensions.
366
367 This function follows the api from :any:`numpy.cumsum`
368
369 See: https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html
370 """
371 raise NotImplementedError()
372
373 def max(self, a, axis=None, keepdims=False):
374 r"""
375 Returns the maximum of an array or maximum along given dimensions.
376
377 This function follows the api from :any:`numpy.amax`
378
379 See: https://numpy.org/doc/stable/reference/generated/numpy.amax.html
380 """
381 raise NotImplementedError()
382
383 def min(self, a, axis=None, keepdims=False):
384 r"""
385 Returns the maximum of an array or maximum along given dimensions.
386
387 This function follows the api from :any:`numpy.amin`
388
389 See: https://numpy.org/doc/stable/reference/generated/numpy.amin.html
390 """
391 raise NotImplementedError()
392
393 def maximum(self, a, b):
394 r"""
395 Returns element-wise maximum of array elements.
396
397 This function follows the api from :any:`numpy.maximum`
398
399 See: https://numpy.org/doc/stable/reference/generated/numpy.maximum.html
400 """
401 raise NotImplementedError()
402
403 def minimum(self, a, b):
404 r"""
405 Returns element-wise minimum of array elements.
406
407 This function follows the api from :any:`numpy.minimum`
408
409 See: https://numpy.org/doc/stable/reference/generated/numpy.minimum.html
410 """
411 raise NotImplementedError()
412
413 def sign(self, a):
414 r"""Returns an element-wise indication of the sign of a number.
415
416 This function follows the api from :any:`numpy.sign`
417
418 See: https://numpy.org/doc/stable/reference/generated/numpy.sign.html
419 """
420 raise NotImplementedError()
421
422 def dot(self, a, b):
423 r"""
424 Returns the dot product of two tensors.
425
426 This function follows the api from :any:`numpy.dot`
427
428 See: https://numpy.org/doc/stable/reference/generated/numpy.dot.html
429 """
430 raise NotImplementedError()
431
432 def abs(self, a):
433 r"""
434 Computes the absolute value element-wise.
435
436 This function follows the api from :any:`numpy.absolute`
437
438 See: https://numpy.org/doc/stable/reference/generated/numpy.absolute.html
439 """
440 raise NotImplementedError()
441
442 def exp(self, a):
443 r"""
444 Computes the exponential value element-wise.
445
446 This function follows the api from :any:`numpy.exp`
447
448 See: https://numpy.org/doc/stable/reference/generated/numpy.exp.html
449 """
450 raise NotImplementedError()
451
452 def log(self, a):
453 r"""
454 Computes the natural logarithm, element-wise.
455
456 This function follows the api from :any:`numpy.log`
457
458 See: https://numpy.org/doc/stable/reference/generated/numpy.log.html
459 """
460 raise NotImplementedError()
461
462 def sqrt(self, a):
463 r"""
464 Returns the non-ngeative square root of a tensor, element-wise.
465
466 This function follows the api from :any:`numpy.sqrt`
467
468 See: https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html
469 """
470 raise NotImplementedError()
471
472 def power(self, a, exponents):
473 r"""
474 First tensor elements raised to powers from second tensor, element-wise.
475
476 This function follows the api from :any:`numpy.power`
477
478 See: https://numpy.org/doc/stable/reference/generated/numpy.power.html
479 """
480 raise NotImplementedError()
481
482 def norm(self, a, axis=None, keepdims=False):
483 r"""
484 Computes the matrix frobenius norm.
485
486 This function follows the api from :any:`numpy.linalg.norm`
487
488 See: https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html
489 """
490 raise NotImplementedError()
491
492 def any(self, a):
493 r"""
494 Tests whether any tensor element along given dimensions evaluates to True.
495
496 This function follows the api from :any:`numpy.any`
497
498 See: https://numpy.org/doc/stable/reference/generated/numpy.any.html
499 """
500 raise NotImplementedError()
501
502 def isnan(self, a):
503 r"""
504 Tests element-wise for NaN and returns result as a boolean tensor.
505
506 This function follows the api from :any:`numpy.isnan`
507
508 See: https://numpy.org/doc/stable/reference/generated/numpy.isnan.html
509 """
510 raise NotImplementedError()
511
512 def isinf(self, a):
513 r"""
514 Tests element-wise for positive or negative infinity and returns result as a boolean tensor.
515
516 This function follows the api from :any:`numpy.isinf`
517
518 See: https://numpy.org/doc/stable/reference/generated/numpy.isinf.html
519 """
520 raise NotImplementedError()
521
522 def einsum(self, subscripts, *operands):
523 r"""
524 Evaluates the Einstein summation convention on the operands.
525
526 This function follows the api from :any:`numpy.einsum`
527
528 See: https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
529 """
530 raise NotImplementedError()
531
532 def sort(self, a, axis=-1):
533 r"""
534 Returns a sorted copy of a tensor.
535
536 This function follows the api from :any:`numpy.sort`
537
538 See: https://numpy.org/doc/stable/reference/generated/numpy.sort.html
539 """
540 raise NotImplementedError()
541
542 def argsort(self, a, axis=None):
543 r"""
544 Returns the indices that would sort a tensor.
545
546 This function follows the api from :any:`numpy.argsort`
547
548 See: https://numpy.org/doc/stable/reference/generated/numpy.argsort.html
549 """
550 raise NotImplementedError()
551
552 def searchsorted(self, a, v, side="left"):
553 r"""
554 Finds indices where elements should be inserted to maintain order in given tensor.
555
556 This function follows the api from :any:`numpy.searchsorted`
557
558 See: https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html
559 """
560 raise NotImplementedError()
561
562 def flip(self, a, axis=None):
563 r"""
564 Reverses the order of elements in a tensor along given dimensions.
565
566 This function follows the api from :any:`numpy.flip`
567
568 See: https://numpy.org/doc/stable/reference/generated/numpy.flip.html
569 """
570 raise NotImplementedError()
571
572 def clip(self, a, a_min, a_max):
573 """
574 Limits the values in a tensor.
575
576 This function follows the api from :any:`numpy.clip`
577
578 See: https://numpy.org/doc/stable/reference/generated/numpy.clip.html
579 """
580 raise NotImplementedError()
581
582 def repeat(self, a, repeats, axis=None):
583 r"""
584 Repeats elements of a tensor.
585
586 This function follows the api from :any:`numpy.repeat`
587
588 See: https://numpy.org/doc/stable/reference/generated/numpy.repeat.html
589 """
590 raise NotImplementedError()
591
592 def take_along_axis(self, arr, indices, axis):
593 r"""
594 Gathers elements of a tensor along given dimensions.
595
596 This function follows the api from :any:`numpy.take_along_axis`
597
598 See: https://numpy.org/doc/stable/reference/generated/numpy.take_along_axis.html
599 """
600 raise NotImplementedError()
601
602 def concatenate(self, arrays, axis=0):
603 r"""
604 Joins a sequence of tensors along an existing dimension.
605
606 This function follows the api from :any:`numpy.concatenate`
607
608 See: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html
609 """
610 raise NotImplementedError()
611
612 def zero_pad(self, a, pad_width, value=0):
613 r"""
614 Pads a tensor with a given value (0 by default).
615
616 This function follows the api from :any:`numpy.pad`
617
618 See: https://numpy.org/doc/stable/reference/generated/numpy.pad.html
619 """
620 raise NotImplementedError()
621
622 def argmax(self, a, axis=None):
623 r"""
624 Returns the indices of the maximum values of a tensor along given dimensions.
625
626 This function follows the api from :any:`numpy.argmax`
627
628 See: https://numpy.org/doc/stable/reference/generated/numpy.argmax.html
629 """
630 raise NotImplementedError()
631
632 def argmin(self, a, axis=None):
633 r"""
634 Returns the indices of the minimum values of a tensor along given dimensions.
635
636 This function follows the api from :any:`numpy.argmin`
637
638 See: https://numpy.org/doc/stable/reference/generated/numpy.argmin.html
639 """
640 raise NotImplementedError()
641
642 def mean(self, a, axis=None):
643 r"""
644 Computes the arithmetic mean of a tensor along given dimensions.
645
646 This function follows the api from :any:`numpy.mean`
647
648 See: https://numpy.org/doc/stable/reference/generated/numpy.mean.html
649 """
650 raise NotImplementedError()
651
652 def median(self, a, axis=None):
653 r"""
654 Computes the median of a tensor along given dimensions.
655
656 This function follows the api from :any:`numpy.median`
657
658 See: https://numpy.org/doc/stable/reference/generated/numpy.median.html
659 """
660 raise NotImplementedError()
661
662 def std(self, a, axis=None):
663 r"""
664 Computes the standard deviation of a tensor along given dimensions.
665
666 This function follows the api from :any:`numpy.std`
667
668 See: https://numpy.org/doc/stable/reference/generated/numpy.std.html
669 """
670 raise NotImplementedError()
671
672 def linspace(self, start, stop, num, type_as=None):
673 r"""
674 Returns a specified number of evenly spaced values over a given interval.
675
676 This function follows the api from :any:`numpy.linspace`
677
678 See: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html
679 """
680 raise NotImplementedError()
681
682 def meshgrid(self, a, b):
683 r"""
684 Returns coordinate matrices from coordinate vectors (Numpy convention).
685
686 This function follows the api from :any:`numpy.meshgrid`
687
688 See: https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html
689 """
690 raise NotImplementedError()
691
692 def diag(self, a, k=0):
693 r"""
694 Extracts or constructs a diagonal tensor.
695
696 This function follows the api from :any:`numpy.diag`
697
698 See: https://numpy.org/doc/stable/reference/generated/numpy.diag.html
699 """
700 raise NotImplementedError()
701
702 def unique(self, a, return_inverse=False):
703 r"""
704 Finds unique elements of given tensor.
705
706 This function follows the api from :any:`numpy.unique`
707
708 See: https://numpy.org/doc/stable/reference/generated/numpy.unique.html
709 """
710 raise NotImplementedError()
711
712 def logsumexp(self, a, axis=None):
713 r"""
714 Computes the log of the sum of exponentials of input elements.
715
716 This function follows the api from :any:`scipy.special.logsumexp`
717
718 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.logsumexp.html
719 """
720 raise NotImplementedError()
721
722 def stack(self, arrays, axis=0):
723 r"""
724 Joins a sequence of tensors along a new dimension.
725
726 This function follows the api from :any:`numpy.stack`
727
728 See: https://numpy.org/doc/stable/reference/generated/numpy.stack.html
729 """
730 raise NotImplementedError()
731
732 def outer(self, a, b):
733 r"""
734 Computes the outer product between two vectors.
735
736 This function follows the api from :any:`numpy.outer`
737
738 See: https://numpy.org/doc/stable/reference/generated/numpy.outer.html
739 """
740 raise NotImplementedError()
741
742 def reshape(self, a, shape):
743 r"""
744 Gives a new shape to a tensor without changing its data.
745
746 This function follows the api from :any:`numpy.reshape`
747
748 See: https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
749 """
750 raise NotImplementedError()
751
752 def seed(self, seed=None):
753 r"""
754 Sets the seed for the random generator.
755
756 This function follows the api from :any:`numpy.random.seed`
757
758 See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.seed.html
759 """
760 raise NotImplementedError()
761
762 def rand(self, *size, type_as=None):
763 r"""
764 Generate uniform random numbers.
765
766 This function follows the api from :any:`numpy.random.rand`
767
768 See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html
769 """
770 raise NotImplementedError()
771
772 def randn(self, *size, type_as=None):
773 r"""
774 Generate normal Gaussian random numbers.
775
776 This function follows the api from :any:`numpy.random.rand`
777
778 See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html
779 """
780 raise NotImplementedError()
781
782 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
783 r"""
784 Creates a sparse tensor in COOrdinate format.
785
786 This function follows the api from :any:`scipy.sparse.coo_matrix`
787
788 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html
789 """
790 raise NotImplementedError()
791
792 def issparse(self, a):
793 r"""
794 Checks whether or not the input tensor is a sparse tensor.
795
796 This function follows the api from :any:`scipy.sparse.issparse`
797
798 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.issparse.html
799 """
800 raise NotImplementedError()
801
802 def tocsr(self, a):
803 r"""
804 Converts this matrix to Compressed Sparse Row format.
805
806 This function follows the api from :any:`scipy.sparse.coo_matrix.tocsr`
807
808 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.tocsr.html
809 """
810 raise NotImplementedError()
811
812 def eliminate_zeros(self, a, threshold=0.0):
813 r"""
814 Removes entries smaller than the given threshold from the sparse tensor.
815
816 This function follows the api from :any:`scipy.sparse.csr_matrix.eliminate_zeros`
817
818 See: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.eliminate_zeros.html
819 """
820 raise NotImplementedError()
821
822 def todense(self, a):
823 r"""
824 Converts a sparse tensor to a dense tensor.
825
826 This function follows the api from :any:`scipy.sparse.csr_matrix.toarray`
827
828 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.toarray.html
829 """
830 raise NotImplementedError()
831
832 def where(self, condition, x, y):
833 r"""
834 Returns elements chosen from x or y depending on condition.
835
836 This function follows the api from :any:`numpy.where`
837
838 See: https://numpy.org/doc/stable/reference/generated/numpy.where.html
839 """
840 raise NotImplementedError()
841
842 def copy(self, a):
843 r"""
844 Returns a copy of the given tensor.
845
846 This function follows the api from :any:`numpy.copy`
847
848 See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html
849 """
850 raise NotImplementedError()
851
852 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
853 r"""
854 Returns True if two arrays are element-wise equal within a tolerance.
855
856 This function follows the api from :any:`numpy.allclose`
857
858 See: https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
859 """
860 raise NotImplementedError()
861
862 def dtype_device(self, a):
863 r"""
864 Returns the dtype and the device of the given tensor.
865 """
866 raise NotImplementedError()
867
868 def assert_same_dtype_device(self, a, b):
869 r"""
870 Checks whether or not the two given inputs have the same dtype as well as the same device
871 """
872 raise NotImplementedError()
873
874 def squeeze(self, a, axis=None):
875 r"""
876 Remove axes of length one from a.
877
878 This function follows the api from :any:`numpy.squeeze`.
879
880 See: https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html
881 """
882 raise NotImplementedError()
883
884 def bitsize(self, type_as):
885 r"""
886 Gives the number of bits used by the data type of the given tensor.
887 """
888 raise NotImplementedError()
889
890 def device_type(self, type_as):
891 r"""
892 Returns CPU or GPU depending on the device where the given tensor is located.
893 """
894 raise NotImplementedError()
895
896 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
897 r"""
898 Executes a benchmark of the given callable with the given arguments.
899 """
900 raise NotImplementedError()
901
902 def solve(self, a, b):
903 r"""
904 Solves a linear matrix equation, or system of linear scalar equations.
905
906 This function follows the api from :any:`numpy.linalg.solve`.
907
908 See: https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
909 """
910 raise NotImplementedError()
911
912 def trace(self, a):
913 r"""
914 Returns the sum along diagonals of the array.
915
916 This function follows the api from :any:`numpy.trace`.
917
918 See: https://numpy.org/doc/stable/reference/generated/numpy.trace.html
919 """
920 raise NotImplementedError()
921
922 def inv(self, a):
923 r"""
924 Computes the inverse of a matrix.
925
926 This function follows the api from :any:`scipy.linalg.inv`.
927
928 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html
929 """
930 raise NotImplementedError()
931
932 def sqrtm(self, a):
933 r"""
934 Computes the matrix square root.
935 Requires input symmetric positive semi-definite.
936
937 This function follows the api from :any:`scipy.linalg.sqrtm`,
938 allowing batches.
939
940 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.sqrtm.html
941 """
942 raise NotImplementedError()
943
944 def eigh(self, a):
945 r"""
946 Computes the eigenvalues and eigenvectors of a symmetric tensor.
947
948 This function follows the api from :any:`scipy.linalg.eigh`.
949
950 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html
951 """
952 raise NotImplementedError()
953
954 def kl_div(self, p, q, mass=False, eps=1e-16):
955 r"""
956 Computes the (Generalized) Kullback-Leibler divergence.
957
958 This function follows the api from :any:`scipy.stats.entropy`.
959
960 Parameter eps is used to avoid numerical errors and is added in the log.
961
962 .. math::
963 KL(p,q) = \langle \mathbf{p}, log(\mathbf{p} / \mathbf{q} + eps \rangle
964 + \mathbb{1}_{mass=True} \langle \mathbf{q} - \mathbf{p}, \mathbf{1} \rangle
965
966 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html
967 """
968 raise NotImplementedError()
969
970 def isfinite(self, a):
971 r"""
972 Tests element-wise for finiteness (not infinity and not Not a Number).
973
974 This function follows the api from :any:`numpy.isfinite`.
975
976 See: https://numpy.org/doc/stable/reference/generated/numpy.isfinite.html
977 """
978 raise NotImplementedError()
979
980 def array_equal(self, a, b):
981 r"""
982 True if two arrays have the same shape and elements, False otherwise.
983
984 This function follows the api from :any:`numpy.array_equal`.
985
986 See: https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html
987 """
988 raise NotImplementedError()
989
990 def is_floating_point(self, a):
991 r"""
992 Returns whether or not the input consists of floats
993 """
994 raise NotImplementedError()
995
996 def tile(self, a, reps):
997 r"""
998 Construct an array by repeating a the number of times given by reps
999
1000 See: https://numpy.org/doc/stable/reference/generated/numpy.tile.html
1001 """
1002 raise NotImplementedError()
1003
1004 def floor(self, a):
1005 r"""
1006 Return the floor of the input element-wise
1007
1008 See: https://numpy.org/doc/stable/reference/generated/numpy.floor.html
1009 """
1010 raise NotImplementedError()
1011
1012 def prod(self, a, axis=None):
1013 r"""
1014 Return the product of all elements.
1015
1016 See: https://numpy.org/doc/stable/reference/generated/numpy.prod.html
1017 """
1018 raise NotImplementedError()
1019
1020 def sort2(self, a, axis=None):
1021 r"""
1022 Return the sorted array and the indices to sort the array
1023
1024 See: https://pytorch.org/docs/stable/generated/torch.sort.html
1025 """
1026 raise NotImplementedError()
1027
1028 def qr(self, a):
1029 r"""
1030 Return the QR factorization
1031
1032 See: https://numpy.org/doc/stable/reference/generated/numpy.linalg.qr.html
1033 """
1034 raise NotImplementedError()
1035
1036 def atan2(self, a, b):
1037 r"""
1038 Element wise arctangent
1039
1040 See: https://numpy.org/doc/stable/reference/generated/numpy.arctan2.html
1041 """
1042 raise NotImplementedError()
1043
1044 def transpose(self, a, axes=None):
1045 r"""
1046 Returns a tensor that is a transposed version of a. The given dimensions dim0 and dim1 are swapped.
1047
1048 See: https://numpy.org/doc/stable/reference/generated/numpy.transpose.html
1049 """
1050 raise NotImplementedError()
1051
1052 def matmul(self, a, b):
1053 r"""
1054 Matrix product of two arrays.
1055
1056 See: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html#numpy.matmul
1057 """
1058 raise NotImplementedError()
1059
1060 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
1061 r"""
1062 Replace NaN with zero and infinity with large finite numbers or with the numbers defined by the user.
1063
1064 See: https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html#numpy.nan_to_num
1065 """
1066 raise NotImplementedError()
1067
1068 def det(self, a):
1069 r"""
1070 Compute the determinant of an array.
1071
1072 See: https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html
1073 """
1074 raise NotImplementedError()
1075
1076
1077 class NumpyBackend(Backend):
1078 """
1079 NumPy implementation of the backend
1080
1081 - `__name__` is "numpy"
1082 - `__type__` is np.ndarray
1083 """
1084
1085 __name__ = "numpy"
1086 __type__ = np.ndarray
1087 __type_list__ = [np.array(1, dtype=np.float32), np.array(1, dtype=np.float64)]
1088
1089 rng_ = np.random.RandomState()
1090
1091 def _to_numpy(self, a):
1092 return a
1093
1094 def _from_numpy(self, a, type_as=None):
1095 if type_as is None:
1096 return a
1097 elif isinstance(a, float):
1098 return a
1099 else:
1100 return a.astype(type_as.dtype)
1101
1102 def set_gradients(self, val, inputs, grads):
1103 # No gradients for numpy
1104 return val
1105
1106 def _detach(self, a):
1107 # No gradients for numpy
1108 return a
1109
1110 def zeros(self, shape, type_as=None):
1111 if type_as is None:
1112 return np.zeros(shape)
1113 else:
1114 return np.zeros(shape, dtype=type_as.dtype)
1115
1116 def ones(self, shape, type_as=None):
1117 if type_as is None:
1118 return np.ones(shape)
1119 else:
1120 return np.ones(shape, dtype=type_as.dtype)
1121
1122 def arange(self, stop, start=0, step=1, type_as=None):
1123 return np.arange(start, stop, step)
1124
1125 def full(self, shape, fill_value, type_as=None):
1126 if type_as is None:
1127 return np.full(shape, fill_value)
1128 else:
1129 return np.full(shape, fill_value, dtype=type_as.dtype)
1130
1131 def eye(self, N, M=None, type_as=None):
1132 if type_as is None:
1133 return np.eye(N, M)
1134 else:
1135 return np.eye(N, M, dtype=type_as.dtype)
1136
1137 def sum(self, a, axis=None, keepdims=False):
1138 return np.sum(a, axis, keepdims=keepdims)
1139
1140 def cumsum(self, a, axis=None):
1141 return np.cumsum(a, axis)
1142
1143 def max(self, a, axis=None, keepdims=False):
1144 return np.max(a, axis, keepdims=keepdims)
1145
1146 def min(self, a, axis=None, keepdims=False):
1147 return np.min(a, axis, keepdims=keepdims)
1148
1149 def maximum(self, a, b):
1150 return np.maximum(a, b)
1151
1152 def minimum(self, a, b):
1153 return np.minimum(a, b)
1154
1155 def sign(self, a):
1156 return np.sign(a)
1157
1158 def dot(self, a, b):
1159 return np.dot(a, b)
1160
1161 def abs(self, a):
1162 return np.abs(a)
1163
1164 def exp(self, a):
1165 return np.exp(a)
1166
1167 def log(self, a):
1168 return np.log(a)
1169
1170 def sqrt(self, a):
1171 return np.sqrt(a)
1172
1173 def power(self, a, exponents):
1174 return np.power(a, exponents)
1175
1176 def norm(self, a, axis=None, keepdims=False):
1177 return np.linalg.norm(a, axis=axis, keepdims=keepdims)
1178
1179 def any(self, a):
1180 return np.any(a)
1181
1182 def isnan(self, a):
1183 return np.isnan(a)
1184
1185 def isinf(self, a):
1186 return np.isinf(a)
1187
1188 def einsum(self, subscripts, *operands):
1189 return np.einsum(subscripts, *operands)
1190
1191 def sort(self, a, axis=-1):
1192 return np.sort(a, axis)
1193
1194 def argsort(self, a, axis=-1):
1195 return np.argsort(a, axis)
1196
1197 def searchsorted(self, a, v, side="left"):
1198 if a.ndim == 1:
1199 return np.searchsorted(a, v, side)
1200 else:
1201 # this is a not very efficient way to make numpy
1202 # searchsorted work on 2d arrays
1203 ret = np.empty(v.shape, dtype=int)
1204 for i in range(a.shape[0]):
1205 ret[i, :] = np.searchsorted(a[i, :], v[i, :], side)
1206 return ret
1207
1208 def flip(self, a, axis=None):
1209 return np.flip(a, axis)
1210
1211 def outer(self, a, b):
1212 return np.outer(a, b)
1213
1214 def clip(self, a, a_min, a_max):
1215 return np.clip(a, a_min, a_max)
1216
1217 def repeat(self, a, repeats, axis=None):
1218 return np.repeat(a, repeats, axis)
1219
1220 def take_along_axis(self, arr, indices, axis):
1221 return np.take_along_axis(arr, indices, axis)
1222
1223 def concatenate(self, arrays, axis=0):
1224 return np.concatenate(arrays, axis)
1225
1226 def zero_pad(self, a, pad_width, value=0):
1227 return np.pad(a, pad_width, constant_values=value)
1228
1229 def argmax(self, a, axis=None):
1230 return np.argmax(a, axis=axis)
1231
1232 def argmin(self, a, axis=None):
1233 return np.argmin(a, axis=axis)
1234
1235 def mean(self, a, axis=None):
1236 return np.mean(a, axis=axis)
1237
1238 def median(self, a, axis=None):
1239 return np.median(a, axis=axis)
1240
1241 def std(self, a, axis=None):
1242 return np.std(a, axis=axis)
1243
1244 def linspace(self, start, stop, num, type_as=None):
1245 if type_as is None:
1246 return np.linspace(start, stop, num)
1247 else:
1248 return np.linspace(start, stop, num, dtype=type_as.dtype)
1249
1250 def meshgrid(self, a, b):
1251 return np.meshgrid(a, b)
1252
1253 def diag(self, a, k=0):
1254 return np.diag(a, k)
1255
1256 def unique(self, a, return_inverse=False):
1257 return np.unique(a, return_inverse=return_inverse)
1258
1259 def logsumexp(self, a, axis=None):
1260 return special.logsumexp(a, axis=axis)
1261
1262 def stack(self, arrays, axis=0):
1263 return np.stack(arrays, axis)
1264
1265 def reshape(self, a, shape):
1266 return np.reshape(a, shape)
1267
1268 def seed(self, seed=None):
1269 if seed is not None:
1270 self.rng_.seed(seed)
1271
1272 def rand(self, *size, type_as=None):
1273 return self.rng_.rand(*size)
1274
1275 def randn(self, *size, type_as=None):
1276 return self.rng_.randn(*size)
1277
1278 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
1279 if type_as is None:
1280 return coo_matrix((data, (rows, cols)), shape=shape)
1281 else:
1282 return coo_matrix((data, (rows, cols)), shape=shape, dtype=type_as.dtype)
1283
1284 def issparse(self, a):
1285 return issparse(a)
1286
1287 def tocsr(self, a):
1288 if self.issparse(a):
1289 return a.tocsr()
1290 else:
1291 return csr_matrix(a)
1292
1293 def eliminate_zeros(self, a, threshold=0.0):
1294 if threshold > 0:
1295 if self.issparse(a):
1296 a.data[self.abs(a.data) <= threshold] = 0
1297 else:
1298 a[self.abs(a) <= threshold] = 0
1299 if self.issparse(a):
1300 a.eliminate_zeros()
1301 return a
1302
1303 def todense(self, a):
1304 if self.issparse(a):
1305 return a.toarray()
1306 else:
1307 return a
1308
1309 def where(self, condition, x=None, y=None):
1310 if x is None and y is None:
1311 return np.where(condition)
1312 else:
1313 return np.where(condition, x, y)
1314
1315 def copy(self, a):
1316 return a.copy()
1317
1318 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
1319 return np.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
1320
1321 def dtype_device(self, a):
1322 if hasattr(a, "dtype"):
1323 return a.dtype, "cpu"
1324 else:
1325 return type(a), "cpu"
1326
1327 def assert_same_dtype_device(self, a, b):
1328 # numpy has implicit type conversion so we automatically validate the test
1329 pass
1330
1331 def squeeze(self, a, axis=None):
1332 return np.squeeze(a, axis=axis)
1333
1334 def bitsize(self, type_as):
1335 return type_as.itemsize * 8
1336
1337 def device_type(self, type_as):
1338 return "CPU"
1339
1340 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
1341 results = dict()
1342 for type_as in self.__type_list__:
1343 inputs = [self.from_numpy(arg, type_as=type_as) for arg in args]
1344 for _ in range(warmup_runs):
1345 callable(*inputs)
1346 t0 = time.perf_counter()
1347 for _ in range(n_runs):
1348 callable(*inputs)
1349 t1 = time.perf_counter()
1350 key = ("Numpy", self.device_type(type_as), self.bitsize(type_as))
1351 results[key] = (t1 - t0) / n_runs
1352 return results
1353
1354 def solve(self, a, b):
1355 return np.linalg.solve(a, b)
1356
1357 def trace(self, a):
1358 return np.trace(a)
1359
1360 def inv(self, a):
1361 return scipy.linalg.inv(a)
1362
1363 def sqrtm(self, a):
1364 L, V = np.linalg.eigh(a)
1365 L = np.sqrt(L)
1366 # Q[...] = V[...] @ diag(L[...])
1367 Q = np.einsum("...jk,...k->...jk", V, L)
1368 # R[...] = Q[...] @ V[...].T
1369 return np.einsum("...jk,...kl->...jl", Q, np.swapaxes(V, -1, -2))
1370
1371 def eigh(self, a):
1372 return np.linalg.eigh(a)
1373
1374 def kl_div(self, p, q, mass=False, eps=1e-16):
1375 value = np.sum(p * np.log(p / q + eps))
1376 if mass:
1377 value = value + np.sum(q - p)
1378 return value
1379
1380 def isfinite(self, a):
1381 return np.isfinite(a)
1382
1383 def array_equal(self, a, b):
1384 return np.array_equal(a, b)
1385
1386 def is_floating_point(self, a):
1387 return a.dtype.kind == "f"
1388
1389 def tile(self, a, reps):
1390 return np.tile(a, reps)
1391
1392 def floor(self, a):
1393 return np.floor(a)
1394
1395 def prod(self, a, axis=0):
1396 return np.prod(a, axis=axis)
1397
1398 def sort2(self, a, axis=-1):
1399 return self.sort(a, axis), self.argsort(a, axis)
1400
1401 def qr(self, a):
1402 np_version = tuple([int(k) for k in np.__version__.split(".")])
1403 if np_version < (1, 22, 0):
1404 M, N = a.shape[-2], a.shape[-1]
1405 K = min(M, N)
1406
1407 if len(a.shape) >= 3:
1408 n = a.shape[0]
1409
1410 qs, rs = np.zeros((n, M, K)), np.zeros((n, K, N))
1411
1412 for i in range(a.shape[0]):
1413 qs[i], rs[i] = np.linalg.qr(a[i])
1414
1415 else:
1416 return np.linalg.qr(a)
1417
1418 return qs, rs
1419 return np.linalg.qr(a)
1420
1421 def atan2(self, a, b):
1422 return np.arctan2(a, b)
1423
1424 def transpose(self, a, axes=None):
1425 return np.transpose(a, axes)
1426
1427 def matmul(self, a, b):
1428 return np.matmul(a, b)
1429
1430 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
1431 return np.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf)
1432
1433 def det(self, a):
1434 return np.linalg.det(a)
1435
1436
1437 _register_backend_implementation(NumpyBackend)
1438
1439
1440 class JaxBackend(Backend):
1441 """
1442 JAX implementation of the backend
1443
1444 - `__name__` is "jax"
1445 - `__type__` is jax.numpy.ndarray
1446 """
1447
1448 __name__ = "jax"
1449 __type__ = jax_type
1450 __type_list__ = None
1451
1452 rng_ = None
1453
1454 def __init__(self):
1455 self.rng_ = jax.random.PRNGKey(42)
1456
1457 self.__type_list__ = []
1458 # available_devices = jax.devices("cpu")
1459 available_devices = []
1460 if xla_bridge.get_backend().platform == "gpu":
1461 available_devices += jax.devices("gpu")
1462 for d in available_devices:
1463 self.__type_list__ += [
1464 jax.device_put(jnp.array(1, dtype=jnp.float32), d),
1465 jax.device_put(jnp.array(1, dtype=jnp.float64), d),
1466 ]
1467
1468 self.jax_new_version = jax_new_version
1469
1470 def _to_numpy(self, a):
1471 return np.array(a)
1472
1473 def _get_device(self, a):
1474 if self.jax_new_version:
1475 return list(a.devices())[0]
1476 else:
1477 return a.device_buffer.device()
1478
1479 def _change_device(self, a, type_as):
1480 return jax.device_put(a, self._get_device(type_as))
1481
1482 def _from_numpy(self, a, type_as=None):
1483 if isinstance(a, float):
1484 a = np.array(a)
1485 if type_as is None:
1486 return jnp.array(a)
1487 else:
1488 return self._change_device(jnp.array(a).astype(type_as.dtype), type_as)
1489
1490 def set_gradients(self, val, inputs, grads):
1491 from jax.flatten_util import ravel_pytree
1492
1493 (val,) = jax.lax.stop_gradient((val,))
1494
1495 ravelled_inputs, _ = ravel_pytree(inputs)
1496 ravelled_grads, _ = ravel_pytree(grads)
1497
1498 aux = jnp.sum(ravelled_inputs * ravelled_grads) / 2
1499 aux = aux - jax.lax.stop_gradient(aux)
1500
1501 (val,) = jax.tree_map(lambda z: z + aux, (val,))
1502 return val
1503
1504 def _detach(self, a):
1505 return jax.lax.stop_gradient(a)
1506
1507 def zeros(self, shape, type_as=None):
1508 if type_as is None:
1509 return jnp.zeros(shape)
1510 else:
1511 return self._change_device(jnp.zeros(shape, dtype=type_as.dtype), type_as)
1512
1513 def ones(self, shape, type_as=None):
1514 if type_as is None:
1515 return jnp.ones(shape)
1516 else:
1517 return self._change_device(jnp.ones(shape, dtype=type_as.dtype), type_as)
1518
1519 def arange(self, stop, start=0, step=1, type_as=None):
1520 return jnp.arange(start, stop, step)
1521
1522 def full(self, shape, fill_value, type_as=None):
1523 if type_as is None:
1524 return jnp.full(shape, fill_value)
1525 else:
1526 return self._change_device(
1527 jnp.full(shape, fill_value, dtype=type_as.dtype), type_as
1528 )
1529
1530 def eye(self, N, M=None, type_as=None):
1531 if type_as is None:
1532 return jnp.eye(N, M)
1533 else:
1534 return self._change_device(jnp.eye(N, M, dtype=type_as.dtype), type_as)
1535
1536 def sum(self, a, axis=None, keepdims=False):
1537 return jnp.sum(a, axis, keepdims=keepdims)
1538
1539 def cumsum(self, a, axis=None):
1540 return jnp.cumsum(a, axis)
1541
1542 def max(self, a, axis=None, keepdims=False):
1543 return jnp.max(a, axis, keepdims=keepdims)
1544
1545 def min(self, a, axis=None, keepdims=False):
1546 return jnp.min(a, axis, keepdims=keepdims)
1547
1548 def maximum(self, a, b):
1549 return jnp.maximum(a, b)
1550
1551 def minimum(self, a, b):
1552 return jnp.minimum(a, b)
1553
1554 def sign(self, a):
1555 return jnp.sign(a)
1556
1557 def dot(self, a, b):
1558 return jnp.dot(a, b)
1559
1560 def abs(self, a):
1561 return jnp.abs(a)
1562
1563 def exp(self, a):
1564 return jnp.exp(a)
1565
1566 def log(self, a):
1567 return jnp.log(a)
1568
1569 def sqrt(self, a):
1570 return jnp.sqrt(a)
1571
1572 def power(self, a, exponents):
1573 return jnp.power(a, exponents)
1574
1575 def norm(self, a, axis=None, keepdims=False):
1576 return jnp.linalg.norm(a, axis=axis, keepdims=keepdims)
1577
1578 def any(self, a):
1579 return jnp.any(a)
1580
1581 def isnan(self, a):
1582 return jnp.isnan(a)
1583
1584 def isinf(self, a):
1585 return jnp.isinf(a)
1586
1587 def einsum(self, subscripts, *operands):
1588 return jnp.einsum(subscripts, *operands)
1589
1590 def sort(self, a, axis=-1):
1591 return jnp.sort(a, axis)
1592
1593 def argsort(self, a, axis=-1):
1594 return jnp.argsort(a, axis)
1595
1596 def searchsorted(self, a, v, side="left"):
1597 if a.ndim == 1:
1598 return jnp.searchsorted(a, v, side)
1599 else:
1600 return jax.vmap(lambda b, u: jnp.searchsorted(b, u, side))(a, v)
1601
1602 def flip(self, a, axis=None):
1603 return jnp.flip(a, axis)
1604
1605 def outer(self, a, b):
1606 return jnp.outer(a, b)
1607
1608 def clip(self, a, a_min, a_max):
1609 return jnp.clip(a, a_min, a_max)
1610
1611 def repeat(self, a, repeats, axis=None):
1612 return jnp.repeat(a, repeats, axis)
1613
1614 def take_along_axis(self, arr, indices, axis):
1615 return jnp.take_along_axis(arr, indices, axis)
1616
1617 def concatenate(self, arrays, axis=0):
1618 return jnp.concatenate(arrays, axis)
1619
1620 def zero_pad(self, a, pad_width, value=0):
1621 return jnp.pad(a, pad_width, constant_values=value)
1622
1623 def argmax(self, a, axis=None):
1624 return jnp.argmax(a, axis=axis)
1625
1626 def argmin(self, a, axis=None):
1627 return jnp.argmin(a, axis=axis)
1628
1629 def mean(self, a, axis=None):
1630 return jnp.mean(a, axis=axis)
1631
1632 def median(self, a, axis=None):
1633 return jnp.median(a, axis=axis)
1634
1635 def std(self, a, axis=None):
1636 return jnp.std(a, axis=axis)
1637
1638 def linspace(self, start, stop, num, type_as=None):
1639 if type_as is None:
1640 return jnp.linspace(start, stop, num)
1641 else:
1642 return self._change_device(
1643 jnp.linspace(start, stop, num, dtype=type_as.dtype), type_as
1644 )
1645
1646 def meshgrid(self, a, b):
1647 return jnp.meshgrid(a, b)
1648
1649 def diag(self, a, k=0):
1650 return jnp.diag(a, k)
1651
1652 def unique(self, a, return_inverse=False):
1653 return jnp.unique(a, return_inverse=return_inverse)
1654
1655 def logsumexp(self, a, axis=None):
1656 return jspecial.logsumexp(a, axis=axis)
1657
1658 def stack(self, arrays, axis=0):
1659 return jnp.stack(arrays, axis)
1660
1661 def reshape(self, a, shape):
1662 return jnp.reshape(a, shape)
1663
1664 def seed(self, seed=None):
1665 if seed is not None:
1666 self.rng_ = jax.random.PRNGKey(seed)
1667
1668 def rand(self, *size, type_as=None):
1669 self.rng_, subkey = jax.random.split(self.rng_)
1670 if type_as is not None:
1671 return jax.random.uniform(subkey, shape=size, dtype=type_as.dtype)
1672 else:
1673 return jax.random.uniform(subkey, shape=size)
1674
1675 def randn(self, *size, type_as=None):
1676 self.rng_, subkey = jax.random.split(self.rng_)
1677 if type_as is not None:
1678 return jax.random.normal(subkey, shape=size, dtype=type_as.dtype)
1679 else:
1680 return jax.random.normal(subkey, shape=size)
1681
1682 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
1683 # Currently, JAX does not support sparse matrices
1684 data = self.to_numpy(data)
1685 rows = self.to_numpy(rows)
1686 cols = self.to_numpy(cols)
1687 nx = NumpyBackend()
1688 coo_matrix = nx.coo_matrix(data, rows, cols, shape=shape, type_as=type_as)
1689 matrix = nx.todense(coo_matrix)
1690 return self.from_numpy(matrix)
1691
1692 def issparse(self, a):
1693 # Currently, JAX does not support sparse matrices
1694 return False
1695
1696 def tocsr(self, a):
1697 # Currently, JAX does not support sparse matrices
1698 return a
1699
1700 def eliminate_zeros(self, a, threshold=0.0):
1701 # Currently, JAX does not support sparse matrices
1702 if threshold > 0:
1703 return self.where(self.abs(a) <= threshold, self.zeros((1,), type_as=a), a)
1704 return a
1705
1706 def todense(self, a):
1707 # Currently, JAX does not support sparse matrices
1708 return a
1709
1710 def where(self, condition, x=None, y=None):
1711 if x is None and y is None:
1712 return jnp.where(condition)
1713 else:
1714 return jnp.where(condition, x, y)
1715
1716 def copy(self, a):
1717 # No need to copy, JAX arrays are immutable
1718 return a
1719
1720 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
1721 return jnp.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
1722
1723 def dtype_device(self, a):
1724 if self.jax_new_version:
1725 return a.dtype, list(a.devices())[0]
1726 else:
1727 return a.dtype, a.device_buffer.device()
1728
1729 def assert_same_dtype_device(self, a, b):
1730 a_dtype, a_device = self.dtype_device(a)
1731 b_dtype, b_device = self.dtype_device(b)
1732
1733 assert a_dtype == b_dtype, "Dtype discrepancy"
1734 assert (
1735 a_device == b_device
1736 ), f"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}"
1737
1738 def squeeze(self, a, axis=None):
1739 return jnp.squeeze(a, axis=axis)
1740
1741 def bitsize(self, type_as):
1742 return type_as.dtype.itemsize * 8
1743
1744 def device_type(self, type_as):
1745 return self.dtype_device(type_as)[1].platform.upper()
1746
1747 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
1748 results = dict()
1749
1750 for type_as in self.__type_list__:
1751 inputs = [self.from_numpy(arg, type_as=type_as) for arg in args]
1752 for _ in range(warmup_runs):
1753 a = callable(*inputs)
1754 a.block_until_ready()
1755 t0 = time.perf_counter()
1756 for _ in range(n_runs):
1757 a = callable(*inputs)
1758 a.block_until_ready()
1759 t1 = time.perf_counter()
1760 key = ("Jax", self.device_type(type_as), self.bitsize(type_as))
1761 results[key] = (t1 - t0) / n_runs
1762 return results
1763
1764 def solve(self, a, b):
1765 return jnp.linalg.solve(a, b)
1766
1767 def trace(self, a):
1768 return jnp.trace(a)
1769
1770 def inv(self, a):
1771 return jnp.linalg.inv(a)
1772
1773 def sqrtm(self, a):
1774 L, V = jnp.linalg.eigh(a)
1775 L = jnp.sqrt(L)
1776 # Q[...] = V[...] @ diag(L[...])
1777 Q = jnp.einsum("...jk,...k->...jk", V, L)
1778 # R[...] = Q[...] @ V[...].T
1779 return jnp.einsum("...jk,...kl->...jl", Q, jnp.swapaxes(V, -1, -2))
1780
1781 def eigh(self, a):
1782 return jnp.linalg.eigh(a)
1783
1784 def kl_div(self, p, q, mass=False, eps=1e-16):
1785 value = jnp.sum(p * jnp.log(p / q + eps))
1786 if mass:
1787 value = value + jnp.sum(q - p)
1788 return value
1789
1790 def isfinite(self, a):
1791 return jnp.isfinite(a)
1792
1793 def array_equal(self, a, b):
1794 return jnp.array_equal(a, b)
1795
1796 def is_floating_point(self, a):
1797 return a.dtype.kind == "f"
1798
1799 def tile(self, a, reps):
1800 return jnp.tile(a, reps)
1801
1802 def floor(self, a):
1803 return jnp.floor(a)
1804
1805 def prod(self, a, axis=0):
1806 return jnp.prod(a, axis=axis)
1807
1808 def sort2(self, a, axis=-1):
1809 return self.sort(a, axis), self.argsort(a, axis)
1810
1811 def qr(self, a):
1812 return jnp.linalg.qr(a)
1813
1814 def atan2(self, a, b):
1815 return jnp.arctan2(a, b)
1816
1817 def transpose(self, a, axes=None):
1818 return jnp.transpose(a, axes)
1819
1820 def matmul(self, a, b):
1821 return jnp.matmul(a, b)
1822
1823 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
1824 return jnp.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf)
1825
1826 def det(self, x):
1827 return jnp.linalg.det(x)
1828
1829
1830 if jax:
1831 # Only register jax backend if it is installed
1832 _register_backend_implementation(JaxBackend)
1833
1834
1835 class TorchBackend(Backend):
1836 """
1837 PyTorch implementation of the backend
1838
1839 - `__name__` is "torch"
1840 - `__type__` is torch.Tensor
1841 """
1842
1843 __name__ = "torch"
1844 __type__ = torch_type
1845 __type_list__ = None
1846
1847 rng_ = None
1848
1849 def __init__(self):
1850 self.rng_ = torch.Generator("cpu")
1851 self.rng_.seed()
1852
1853 self.__type_list__ = [
1854 torch.tensor(1, dtype=torch.float32),
1855 torch.tensor(1, dtype=torch.float64),
1856 ]
1857
1858 if torch.cuda.is_available():
1859 self.rng_cuda_ = torch.Generator("cuda")
1860 self.rng_cuda_.seed()
1861 self.__type_list__.append(
1862 torch.tensor(1, dtype=torch.float32, device="cuda")
1863 )
1864 self.__type_list__.append(
1865 torch.tensor(1, dtype=torch.float64, device="cuda")
1866 )
1867 else:
1868 self.rng_cuda_ = torch.Generator("cpu")
1869
1870 from torch.autograd import Function
1871
1872 # define a function that takes inputs val and grads
1873 # ad returns a val tensor with proper gradients
1874 class ValFunction(Function):
1875 @staticmethod
1876 def forward(ctx, val, grads, *inputs):
1877 ctx.grads = grads
1878 return val
1879
1880 @staticmethod
1881 def backward(ctx, grad_output):
1882 # the gradients are grad
1883 return (None, None) + tuple(g * grad_output for g in ctx.grads)
1884
1885 self.ValFunction = ValFunction
1886
1887 def _to_numpy(self, a):
1888 if isinstance(a, float) or isinstance(a, int) or isinstance(a, np.ndarray):
1889 return np.array(a)
1890 return a.cpu().detach().numpy()
1891
1892 def _from_numpy(self, a, type_as=None):
1893 if (
1894 isinstance(a, float)
1895 or isinstance(a, int)
1896 or isinstance(a, np.float32)
1897 or isinstance(a, np.float64)
1898 ):
1899 a = np.array(a)
1900 if type_as is None:
1901 return torch.from_numpy(a)
1902 else:
1903 return torch.as_tensor(a, dtype=type_as.dtype, device=type_as.device)
1904
1905 def set_gradients(self, val, inputs, grads):
1906 Func = self.ValFunction
1907
1908 res = Func.apply(val, grads, *inputs)
1909
1910 return res
1911
1912 def _detach(self, a):
1913 return a.detach()
1914
1915 def zeros(self, shape, type_as=None):
1916 if isinstance(shape, int):
1917 shape = (shape,)
1918 if type_as is None:
1919 return torch.zeros(shape)
1920 else:
1921 return torch.zeros(shape, dtype=type_as.dtype, device=type_as.device)
1922
1923 def ones(self, shape, type_as=None):
1924 if isinstance(shape, int):
1925 shape = (shape,)
1926 if type_as is None:
1927 return torch.ones(shape)
1928 else:
1929 return torch.ones(shape, dtype=type_as.dtype, device=type_as.device)
1930
1931 def arange(self, stop, start=0, step=1, type_as=None):
1932 if type_as is None:
1933 return torch.arange(start, stop, step)
1934 else:
1935 return torch.arange(start, stop, step, device=type_as.device)
1936
1937 def full(self, shape, fill_value, type_as=None):
1938 if isinstance(shape, int):
1939 shape = (shape,)
1940 if type_as is None:
1941 return torch.full(shape, fill_value)
1942 else:
1943 return torch.full(
1944 shape, fill_value, dtype=type_as.dtype, device=type_as.device
1945 )
1946
1947 def eye(self, N, M=None, type_as=None):
1948 if M is None:
1949 M = N
1950 if type_as is None:
1951 return torch.eye(N, m=M)
1952 else:
1953 return torch.eye(N, m=M, dtype=type_as.dtype, device=type_as.device)
1954
1955 def sum(self, a, axis=None, keepdims=False):
1956 if axis is None:
1957 return torch.sum(a)
1958 else:
1959 return torch.sum(a, axis, keepdim=keepdims)
1960
1961 def cumsum(self, a, axis=None):
1962 if axis is None:
1963 return torch.cumsum(a.flatten(), 0)
1964 else:
1965 return torch.cumsum(a, axis)
1966
1967 def max(self, a, axis=None, keepdims=False):
1968 if axis is None:
1969 return torch.max(a)
1970 else:
1971 return torch.max(a, axis, keepdim=keepdims)[0]
1972
1973 def min(self, a, axis=None, keepdims=False):
1974 if axis is None:
1975 return torch.min(a)
1976 else:
1977 return torch.min(a, axis, keepdim=keepdims)[0]
1978
1979 def maximum(self, a, b):
1980 if isinstance(a, int) or isinstance(a, float):
1981 a = torch.tensor([float(a)], dtype=b.dtype, device=b.device)
1982 if isinstance(b, int) or isinstance(b, float):
1983 b = torch.tensor([float(b)], dtype=a.dtype, device=a.device)
1984 if hasattr(torch, "maximum"):
1985 return torch.maximum(a, b)
1986 else:
1987 return torch.max(torch.stack(torch.broadcast_tensors(a, b)), axis=0)[0]
1988
1989 def minimum(self, a, b):
1990 if isinstance(a, int) or isinstance(a, float):
1991 a = torch.tensor([float(a)], dtype=b.dtype, device=b.device)
1992 if isinstance(b, int) or isinstance(b, float):
1993 b = torch.tensor([float(b)], dtype=a.dtype, device=a.device)
1994 if hasattr(torch, "minimum"):
1995 return torch.minimum(a, b)
1996 else:
1997 return torch.min(torch.stack(torch.broadcast_tensors(a, b)), axis=0)[0]
1998
1999 def sign(self, a):
2000 return torch.sign(a)
2001
2002 def dot(self, a, b):
2003 return torch.matmul(a, b)
2004
2005 def abs(self, a):
2006 return torch.abs(a)
2007
2008 def exp(self, a):
2009 return torch.exp(a)
2010
2011 def log(self, a):
2012 return torch.log(a)
2013
2014 def sqrt(self, a):
2015 return torch.sqrt(a)
2016
2017 def power(self, a, exponents):
2018 return torch.pow(a, exponents)
2019
2020 def norm(self, a, axis=None, keepdims=False):
2021 return torch.linalg.norm(a, dim=axis, keepdims=keepdims)
2022
2023 def any(self, a):
2024 return torch.any(a)
2025
2026 def isnan(self, a):
2027 return torch.isnan(a)
2028
2029 def isinf(self, a):
2030 return torch.isinf(a)
2031
2032 def einsum(self, subscripts, *operands):
2033 return torch.einsum(subscripts, *operands)
2034
2035 def sort(self, a, axis=-1):
2036 sorted0, indices = torch.sort(a, dim=axis)
2037 return sorted0
2038
2039 def argsort(self, a, axis=-1):
2040 sorted, indices = torch.sort(a, dim=axis)
2041 return indices
2042
2043 def searchsorted(self, a, v, side="left"):
2044 right = side != "left"
2045 return torch.searchsorted(a, v, right=right)
2046
2047 def flip(self, a, axis=None):
2048 if axis is None:
2049 return torch.flip(a, tuple(i for i in range(len(a.shape))))
2050 if isinstance(axis, int):
2051 return torch.flip(a, (axis,))
2052 else:
2053 return torch.flip(a, dims=axis)
2054
2055 def outer(self, a, b):
2056 return torch.outer(a, b)
2057
2058 def clip(self, a, a_min, a_max):
2059 return torch.clamp(a, a_min, a_max)
2060
2061 def repeat(self, a, repeats, axis=None):
2062 return torch.repeat_interleave(a, repeats, dim=axis)
2063
2064 def take_along_axis(self, arr, indices, axis):
2065 return torch.gather(arr, axis, indices)
2066
2067 def concatenate(self, arrays, axis=0):
2068 return torch.cat(arrays, dim=axis)
2069
2070 def zero_pad(self, a, pad_width, value=0):
2071 from torch.nn.functional import pad
2072
2073 # pad_width is an array of ndim tuples indicating how many 0 before and after
2074 # we need to add. We first need to make it compliant with torch syntax, that
2075 # starts with the last dim, then second last, etc.
2076 how_pad = tuple(element for tupl in pad_width[::-1] for element in tupl)
2077 return pad(a, how_pad, value=value)
2078
2079 def argmax(self, a, axis=None):
2080 return torch.argmax(a, dim=axis)
2081
2082 def argmin(self, a, axis=None):
2083 return torch.argmin(a, dim=axis)
2084
2085 def mean(self, a, axis=None):
2086 if axis is not None:
2087 return torch.mean(a, dim=axis)
2088 else:
2089 return torch.mean(a)
2090
2091 def median(self, a, axis=None):
2092 from packaging import version
2093
2094 # Since version 1.11.0, interpolation is available
2095 if version.parse(torch.__version__) >= version.parse("1.11.0"):
2096 if axis is not None:
2097 return torch.quantile(a, 0.5, interpolation="midpoint", dim=axis)
2098 else:
2099 return torch.quantile(a, 0.5, interpolation="midpoint")
2100
2101 # Else, use numpy
2102 warnings.warn(
2103 "The median is being computed using numpy and the array has been detached "
2104 "in the Pytorch backend."
2105 )
2106 a_ = self.to_numpy(a)
2107 a_median = np.median(a_, axis=axis)
2108 return self.from_numpy(a_median, type_as=a)
2109
2110 def std(self, a, axis=None):
2111 if axis is not None:
2112 return torch.std(a, dim=axis, unbiased=False)
2113 else:
2114 return torch.std(a, unbiased=False)
2115
2116 def linspace(self, start, stop, num, type_as=None):
2117 if type_as is None:
2118 return torch.linspace(start, stop, num)
2119 else:
2120 return torch.linspace(
2121 start, stop, num, dtype=type_as.dtype, device=type_as.device
2122 )
2123
2124 def meshgrid(self, a, b):
2125 try:
2126 return torch.meshgrid(a, b, indexing="xy")
2127 except TypeError:
2128 X, Y = torch.meshgrid(a, b)
2129 return X.T, Y.T
2130
2131 def diag(self, a, k=0):
2132 return torch.diag(a, diagonal=k)
2133
2134 def unique(self, a, return_inverse=False):
2135 return torch.unique(a, return_inverse=return_inverse)
2136
2137 def logsumexp(self, a, axis=None):
2138 if axis is not None:
2139 return torch.logsumexp(a, dim=axis)
2140 else:
2141 return torch.logsumexp(a, dim=tuple(range(len(a.shape))))
2142
2143 def stack(self, arrays, axis=0):
2144 return torch.stack(arrays, dim=axis)
2145
2146 def reshape(self, a, shape):
2147 return torch.reshape(a, shape)
2148
2149 def seed(self, seed=None):
2150 if isinstance(seed, int):
2151 self.rng_.manual_seed(seed)
2152 self.rng_cuda_.manual_seed(seed)
2153 elif isinstance(seed, torch.Generator):
2154 if self.device_type(seed) == "GPU":
2155 self.rng_cuda_ = seed
2156 else:
2157 self.rng_ = seed
2158 else:
2159 raise ValueError("Non compatible seed : {}".format(seed))
2160
2161 def rand(self, *size, type_as=None):
2162 if type_as is not None:
2163 generator = (
2164 self.rng_cuda_ if self.device_type(type_as) == "GPU" else self.rng_
2165 )
2166 return torch.rand(
2167 size=size,
2168 generator=generator,
2169 dtype=type_as.dtype,
2170 device=type_as.device,
2171 )
2172 else:
2173 return torch.rand(size=size, generator=self.rng_)
2174
2175 def randn(self, *size, type_as=None):
2176 if type_as is not None:
2177 generator = (
2178 self.rng_cuda_ if self.device_type(type_as) == "GPU" else self.rng_
2179 )
2180 return torch.randn(
2181 size=size,
2182 dtype=type_as.dtype,
2183 generator=generator,
2184 device=type_as.device,
2185 )
2186 else:
2187 return torch.randn(size=size, generator=self.rng_)
2188
2189 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
2190 if type_as is None:
2191 return torch.sparse_coo_tensor(torch.stack([rows, cols]), data, size=shape)
2192 else:
2193 return torch.sparse_coo_tensor(
2194 torch.stack([rows, cols]),
2195 data,
2196 size=shape,
2197 dtype=type_as.dtype,
2198 device=type_as.device,
2199 )
2200
2201 def issparse(self, a):
2202 return getattr(a, "is_sparse", False) or getattr(a, "is_sparse_csr", False)
2203
2204 def tocsr(self, a):
2205 # Versions older than 1.9 do not support CSR tensors. PyTorch 1.9 and 1.10 offer a very limited support
2206 return self.todense(a)
2207
2208 def eliminate_zeros(self, a, threshold=0.0):
2209 if self.issparse(a):
2210 if threshold > 0:
2211 mask = self.abs(a) <= threshold
2212 mask = ~mask
2213 mask = mask.nonzero()
2214 else:
2215 mask = a._values().nonzero()
2216 nv = a._values().index_select(0, mask.view(-1))
2217 ni = a._indices().index_select(1, mask.view(-1))
2218 return self.coo_matrix(nv, ni[0], ni[1], shape=a.shape, type_as=a)
2219 else:
2220 if threshold > 0:
2221 a[self.abs(a) <= threshold] = 0
2222 return a
2223
2224 def todense(self, a):
2225 if self.issparse(a):
2226 return a.to_dense()
2227 else:
2228 return a
2229
2230 def where(self, condition, x=None, y=None):
2231 if x is None and y is None:
2232 return torch.where(condition)
2233 else:
2234 return torch.where(condition, x, y)
2235
2236 def copy(self, a):
2237 return torch.clone(a)
2238
2239 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
2240 return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
2241
2242 def dtype_device(self, a):
2243 return a.dtype, a.device
2244
2245 def assert_same_dtype_device(self, a, b):
2246 a_dtype, a_device = self.dtype_device(a)
2247 b_dtype, b_device = self.dtype_device(b)
2248
2249 assert a_dtype == b_dtype, "Dtype discrepancy"
2250 assert (
2251 a_device == b_device
2252 ), f"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}"
2253
2254 def squeeze(self, a, axis=None):
2255 if axis is None:
2256 return torch.squeeze(a)
2257 else:
2258 return torch.squeeze(a, dim=axis)
2259
2260 def bitsize(self, type_as):
2261 return torch.finfo(type_as.dtype).bits
2262
2263 def device_type(self, type_as):
2264 return type_as.device.type.replace("cuda", "gpu").upper()
2265
2266 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
2267 results = dict()
2268 for type_as in self.__type_list__:
2269 inputs = [self.from_numpy(arg, type_as=type_as) for arg in args]
2270 for _ in range(warmup_runs):
2271 callable(*inputs)
2272 if self.device_type(type_as) == "GPU": # pragma: no cover
2273 torch.cuda.synchronize()
2274 start = torch.cuda.Event(enable_timing=True)
2275 end = torch.cuda.Event(enable_timing=True)
2276 start.record()
2277 else:
2278 start = time.perf_counter()
2279 for _ in range(n_runs):
2280 callable(*inputs)
2281 if self.device_type(type_as) == "GPU": # pragma: no cover
2282 end.record()
2283 torch.cuda.synchronize()
2284 duration = start.elapsed_time(end) / 1000.0
2285 else:
2286 end = time.perf_counter()
2287 duration = end - start
2288 key = ("Pytorch", self.device_type(type_as), self.bitsize(type_as))
2289 results[key] = duration / n_runs
2290 if torch.cuda.is_available():
2291 torch.cuda.empty_cache()
2292 return results
2293
2294 def solve(self, a, b):
2295 return torch.linalg.solve(a, b)
2296
2297 def trace(self, a):
2298 return torch.trace(a)
2299
2300 def inv(self, a):
2301 return torch.linalg.inv(a)
2302
2303 def sqrtm(self, a):
2304 L, V = torch.linalg.eigh(a)
2305 L = torch.sqrt(L)
2306 # Q[...] = V[...] @ diag(L[...])
2307 Q = torch.einsum("...jk,...k->...jk", V, L)
2308 # R[...] = Q[...] @ V[...].T
2309 return torch.einsum("...jk,...kl->...jl", Q, torch.transpose(V, -1, -2))
2310
2311 def eigh(self, a):
2312 return torch.linalg.eigh(a)
2313
2314 def kl_div(self, p, q, mass=False, eps=1e-16):
2315 value = torch.sum(p * torch.log(p / q + eps))
2316 if mass:
2317 value = value + torch.sum(q - p)
2318 return value
2319
2320 def isfinite(self, a):
2321 return torch.isfinite(a)
2322
2323 def array_equal(self, a, b):
2324 return torch.equal(a, b)
2325
2326 def is_floating_point(self, a):
2327 return a.dtype.is_floating_point
2328
2329 def tile(self, a, reps):
2330 return a.repeat(reps)
2331
2332 def floor(self, a):
2333 return torch.floor(a)
2334
2335 def prod(self, a, axis=0):
2336 return torch.prod(a, dim=axis)
2337
2338 def sort2(self, a, axis=-1):
2339 return torch.sort(a, axis)
2340
2341 def qr(self, a):
2342 return torch.linalg.qr(a)
2343
2344 def atan2(self, a, b):
2345 return torch.atan2(a, b)
2346
2347 def transpose(self, a, axes=None):
2348 if axes is None:
2349 axes = tuple(range(a.ndim)[::-1])
2350 return a.permute(axes)
2351
2352 def matmul(self, a, b):
2353 return torch.matmul(a, b)
2354
2355 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
2356 out = None if copy else x
2357 return torch.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf, out=out)
2358
2359 def det(self, x):
2360 return torch.linalg.det(x)
2361
2362
2363 if torch:
2364 # Only register torch backend if it is installed
2365 _register_backend_implementation(TorchBackend)
2366
2367
2368 class CupyBackend(Backend): # pragma: no cover
2369 """
2370 CuPy implementation of the backend
2371
2372 - `__name__` is "cupy"
2373 - `__type__` is cp.ndarray
2374 """
2375
2376 __name__ = "cupy"
2377 __type__ = cp_type
2378 __type_list__ = None
2379
2380 rng_ = None
2381
2382 def __init__(self):
2383 self.rng_ = cp.random.RandomState()
2384
2385 self.__type_list__ = [
2386 cp.array(1, dtype=cp.float32),
2387 cp.array(1, dtype=cp.float64),
2388 ]
2389
2390 def _to_numpy(self, a):
2391 return cp.asnumpy(a)
2392
2393 def _from_numpy(self, a, type_as=None):
2394 if isinstance(a, float):
2395 a = np.array(a)
2396 if type_as is None:
2397 return cp.asarray(a)
2398 else:
2399 with cp.cuda.Device(type_as.device):
2400 return cp.asarray(a, dtype=type_as.dtype)
2401
2402 def set_gradients(self, val, inputs, grads):
2403 # No gradients for cupy
2404 return val
2405
2406 def _detach(self, a):
2407 return a
2408
2409 def zeros(self, shape, type_as=None):
2410 if isinstance(shape, (list, tuple)):
2411 shape = tuple(int(i) for i in shape)
2412 if type_as is None:
2413 return cp.zeros(shape)
2414 else:
2415 with cp.cuda.Device(type_as.device):
2416 return cp.zeros(shape, dtype=type_as.dtype)
2417
2418 def ones(self, shape, type_as=None):
2419 if isinstance(shape, (list, tuple)):
2420 shape = tuple(int(i) for i in shape)
2421 if type_as is None:
2422 return cp.ones(shape)
2423 else:
2424 with cp.cuda.Device(type_as.device):
2425 return cp.ones(shape, dtype=type_as.dtype)
2426
2427 def arange(self, stop, start=0, step=1, type_as=None):
2428 return cp.arange(start, stop, step)
2429
2430 def full(self, shape, fill_value, type_as=None):
2431 if isinstance(shape, (list, tuple)):
2432 shape = tuple(int(i) for i in shape)
2433 if type_as is None:
2434 return cp.full(shape, fill_value)
2435 else:
2436 with cp.cuda.Device(type_as.device):
2437 return cp.full(shape, fill_value, dtype=type_as.dtype)
2438
2439 def eye(self, N, M=None, type_as=None):
2440 if type_as is None:
2441 return cp.eye(N, M)
2442 else:
2443 with cp.cuda.Device(type_as.device):
2444 return cp.eye(N, M, dtype=type_as.dtype)
2445
2446 def sum(self, a, axis=None, keepdims=False):
2447 return cp.sum(a, axis, keepdims=keepdims)
2448
2449 def cumsum(self, a, axis=None):
2450 return cp.cumsum(a, axis)
2451
2452 def max(self, a, axis=None, keepdims=False):
2453 return cp.max(a, axis, keepdims=keepdims)
2454
2455 def min(self, a, axis=None, keepdims=False):
2456 return cp.min(a, axis, keepdims=keepdims)
2457
2458 def maximum(self, a, b):
2459 return cp.maximum(a, b)
2460
2461 def minimum(self, a, b):
2462 return cp.minimum(a, b)
2463
2464 def sign(self, a):
2465 return cp.sign(a)
2466
2467 def abs(self, a):
2468 return cp.abs(a)
2469
2470 def exp(self, a):
2471 return cp.exp(a)
2472
2473 def log(self, a):
2474 return cp.log(a)
2475
2476 def sqrt(self, a):
2477 return cp.sqrt(a)
2478
2479 def power(self, a, exponents):
2480 return cp.power(a, exponents)
2481
2482 def dot(self, a, b):
2483 return cp.dot(a, b)
2484
2485 def norm(self, a, axis=None, keepdims=False):
2486 return cp.linalg.norm(a, axis=axis, keepdims=keepdims)
2487
2488 def any(self, a):
2489 return cp.any(a)
2490
2491 def isnan(self, a):
2492 return cp.isnan(a)
2493
2494 def isinf(self, a):
2495 return cp.isinf(a)
2496
2497 def einsum(self, subscripts, *operands):
2498 return cp.einsum(subscripts, *operands)
2499
2500 def sort(self, a, axis=-1):
2501 return cp.sort(a, axis)
2502
2503 def argsort(self, a, axis=-1):
2504 return cp.argsort(a, axis)
2505
2506 def searchsorted(self, a, v, side="left"):
2507 if a.ndim == 1:
2508 return cp.searchsorted(a, v, side)
2509 else:
2510 # this is a not very efficient way to make numpy
2511 # searchsorted work on 2d arrays
2512 ret = cp.empty(v.shape, dtype=int)
2513 for i in range(a.shape[0]):
2514 ret[i, :] = cp.searchsorted(a[i, :], v[i, :], side)
2515 return ret
2516
2517 def flip(self, a, axis=None):
2518 return cp.flip(a, axis)
2519
2520 def outer(self, a, b):
2521 return cp.outer(a, b)
2522
2523 def clip(self, a, a_min, a_max):
2524 return cp.clip(a, a_min, a_max)
2525
2526 def repeat(self, a, repeats, axis=None):
2527 return cp.repeat(a, repeats, axis)
2528
2529 def take_along_axis(self, arr, indices, axis):
2530 return cp.take_along_axis(arr, indices, axis)
2531
2532 def concatenate(self, arrays, axis=0):
2533 return cp.concatenate(arrays, axis)
2534
2535 def zero_pad(self, a, pad_width, value=0):
2536 return cp.pad(a, pad_width, constant_values=value)
2537
2538 def argmax(self, a, axis=None):
2539 return cp.argmax(a, axis=axis)
2540
2541 def argmin(self, a, axis=None):
2542 return cp.argmin(a, axis=axis)
2543
2544 def mean(self, a, axis=None):
2545 return cp.mean(a, axis=axis)
2546
2547 def median(self, a, axis=None):
2548 return cp.median(a, axis=axis)
2549
2550 def std(self, a, axis=None):
2551 return cp.std(a, axis=axis)
2552
2553 def linspace(self, start, stop, num, type_as=None):
2554 if type_as is None:
2555 return cp.linspace(start, stop, num)
2556 else:
2557 with cp.cuda.Device(type_as.device):
2558 return cp.linspace(start, stop, num, dtype=type_as.dtype)
2559
2560 def meshgrid(self, a, b):
2561 return cp.meshgrid(a, b)
2562
2563 def diag(self, a, k=0):
2564 return cp.diag(a, k)
2565
2566 def unique(self, a, return_inverse=False):
2567 return cp.unique(a, return_inverse=return_inverse)
2568
2569 def logsumexp(self, a, axis=None):
2570 # Taken from
2571 # https://github.com/scipy/scipy/blob/v1.7.1/scipy/special/_logsumexp.py#L7-L127
2572 a_max = cp.amax(a, axis=axis, keepdims=True)
2573
2574 if a_max.ndim > 0:
2575 a_max[~cp.isfinite(a_max)] = 0
2576 elif not cp.isfinite(a_max):
2577 a_max = 0
2578
2579 tmp = cp.exp(a - a_max)
2580 s = cp.sum(tmp, axis=axis)
2581 out = cp.log(s)
2582 a_max = cp.squeeze(a_max, axis=axis)
2583 out += a_max
2584 return out
2585
2586 def stack(self, arrays, axis=0):
2587 return cp.stack(arrays, axis)
2588
2589 def reshape(self, a, shape):
2590 return cp.reshape(a, shape)
2591
2592 def seed(self, seed=None):
2593 if seed is not None:
2594 self.rng_.seed(seed)
2595
2596 def rand(self, *size, type_as=None):
2597 if type_as is None:
2598 return self.rng_.rand(*size)
2599 else:
2600 with cp.cuda.Device(type_as.device):
2601 return self.rng_.rand(*size, dtype=type_as.dtype)
2602
2603 def randn(self, *size, type_as=None):
2604 if type_as is None:
2605 return self.rng_.randn(*size)
2606 else:
2607 with cp.cuda.Device(type_as.device):
2608 return self.rng_.randn(*size, dtype=type_as.dtype)
2609
2610 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
2611 data = self.from_numpy(data)
2612 rows = self.from_numpy(rows)
2613 cols = self.from_numpy(cols)
2614 if type_as is None:
2615 return cupyx.scipy.sparse.coo_matrix((data, (rows, cols)), shape=shape)
2616 else:
2617 with cp.cuda.Device(type_as.device):
2618 return cupyx.scipy.sparse.coo_matrix(
2619 (data, (rows, cols)), shape=shape, dtype=type_as.dtype
2620 )
2621
2622 def issparse(self, a):
2623 return cupyx.scipy.sparse.issparse(a)
2624
2625 def tocsr(self, a):
2626 if self.issparse(a):
2627 return a.tocsr()
2628 else:
2629 return cupyx.scipy.sparse.csr_matrix(a)
2630
2631 def eliminate_zeros(self, a, threshold=0.0):
2632 if threshold > 0:
2633 if self.issparse(a):
2634 a.data[self.abs(a.data) <= threshold] = 0
2635 else:
2636 a[self.abs(a) <= threshold] = 0
2637 if self.issparse(a):
2638 a.eliminate_zeros()
2639 return a
2640
2641 def todense(self, a):
2642 if self.issparse(a):
2643 return a.toarray()
2644 else:
2645 return a
2646
2647 def where(self, condition, x=None, y=None):
2648 if x is None and y is None:
2649 return cp.where(condition)
2650 else:
2651 return cp.where(condition, x, y)
2652
2653 def copy(self, a):
2654 return a.copy()
2655
2656 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
2657 return cp.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
2658
2659 def dtype_device(self, a):
2660 return a.dtype, a.device
2661
2662 def assert_same_dtype_device(self, a, b):
2663 a_dtype, a_device = self.dtype_device(a)
2664 b_dtype, b_device = self.dtype_device(b)
2665
2666 # cupy has implicit type conversion so
2667 # we automatically validate the test for type
2668 assert (
2669 a_device == b_device
2670 ), f"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}"
2671
2672 def squeeze(self, a, axis=None):
2673 return cp.squeeze(a, axis=axis)
2674
2675 def bitsize(self, type_as):
2676 return type_as.itemsize * 8
2677
2678 def device_type(self, type_as):
2679 return "GPU"
2680
2681 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
2682 mempool = cp.get_default_memory_pool()
2683 pinned_mempool = cp.get_default_pinned_memory_pool()
2684
2685 results = dict()
2686 for type_as in self.__type_list__:
2687 inputs = [self.from_numpy(arg, type_as=type_as) for arg in args]
2688 start_gpu = cp.cuda.Event()
2689 end_gpu = cp.cuda.Event()
2690 for _ in range(warmup_runs):
2691 callable(*inputs)
2692 start_gpu.synchronize()
2693 start_gpu.record()
2694 for _ in range(n_runs):
2695 callable(*inputs)
2696 end_gpu.record()
2697 end_gpu.synchronize()
2698 key = ("Cupy", self.device_type(type_as), self.bitsize(type_as))
2699 t_gpu = cp.cuda.get_elapsed_time(start_gpu, end_gpu) / 1000.0
2700 results[key] = t_gpu / n_runs
2701 mempool.free_all_blocks()
2702 pinned_mempool.free_all_blocks()
2703 return results
2704
2705 def solve(self, a, b):
2706 return cp.linalg.solve(a, b)
2707
2708 def trace(self, a):
2709 return cp.trace(a)
2710
2711 def inv(self, a):
2712 return cp.linalg.inv(a)
2713
2714 def sqrtm(self, a):
2715 L, V = cp.linalg.eigh(a)
2716 L = cp.sqrt(L)
2717 # Q[...] = V[...] @ diag(L[...])
2718 Q = cp.einsum("...jk,...k->...jk", V, L)
2719 # R[...] = Q[...] @ V[...].T
2720 return cp.einsum("...jk,...kl->...jl", Q, cp.swapaxes(V, -1, -2))
2721
2722 def eigh(self, a):
2723 return cp.linalg.eigh(a)
2724
2725 def kl_div(self, p, q, mass=False, eps=1e-16):
2726 value = cp.sum(p * cp.log(p / q + eps))
2727 if mass:
2728 value = value + cp.sum(q - p)
2729 return value
2730
2731 def isfinite(self, a):
2732 return cp.isfinite(a)
2733
2734 def array_equal(self, a, b):
2735 return cp.array_equal(a, b)
2736
2737 def is_floating_point(self, a):
2738 return a.dtype.kind == "f"
2739
2740 def tile(self, a, reps):
2741 return cp.tile(a, reps)
2742
2743 def floor(self, a):
2744 return cp.floor(a)
2745
2746 def prod(self, a, axis=0):
2747 return cp.prod(a, axis=axis)
2748
2749 def sort2(self, a, axis=-1):
2750 return self.sort(a, axis), self.argsort(a, axis)
2751
2752 def qr(self, a):
2753 return cp.linalg.qr(a)
2754
2755 def atan2(self, a, b):
2756 return cp.arctan2(a, b)
2757
2758 def transpose(self, a, axes=None):
2759 return cp.transpose(a, axes)
2760
2761 def matmul(self, a, b):
2762 return cp.matmul(a, b)
2763
2764 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
2765 return cp.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf)
2766
2767 def det(self, x):
2768 return cp.linalg.det(x)
2769
2770
2771 if cp:
2772 # Only register cp backend if it is installed
2773 _register_backend_implementation(CupyBackend)
2774
2775
2776 class TensorflowBackend(Backend):
2777 __name__ = "tf"
2778 __type__ = tf_type
2779 __type_list__ = None
2780
2781 rng_ = None
2782
2783 def __init__(self):
2784 self.seed(None)
2785
2786 self.__type_list__ = [
2787 tf.convert_to_tensor([1], dtype=tf.float32),
2788 tf.convert_to_tensor([1], dtype=tf.float64),
2789 ]
2790
2791 tmp = self.randn(15, 10)
2792 try:
2793 tmp.reshape((150, 1))
2794 except AttributeError:
2795 warnings.warn(
2796 "To use TensorflowBackend, you need to activate the tensorflow "
2797 "numpy API. You can activate it by running: \n"
2798 "from tensorflow.python.ops.numpy_ops import np_config\n"
2799 "np_config.enable_numpy_behavior()",
2800 stacklevel=2,
2801 )
2802
2803 def _to_numpy(self, a):
2804 if isinstance(a, float) or isinstance(a, int) or isinstance(a, np.ndarray):
2805 return np.array(a)
2806 return a.numpy()
2807
2808 def _from_numpy(self, a, type_as=None):
2809 if isinstance(a, float):
2810 a = np.array(a)
2811 if not isinstance(a, self.__type__):
2812 if type_as is None:
2813 return tf.convert_to_tensor(a)
2814 else:
2815 return tf.convert_to_tensor(a, dtype=type_as.dtype)
2816 else:
2817 if type_as is None:
2818 return a
2819 else:
2820 return tf.cast(a, dtype=type_as.dtype)
2821
2822 def set_gradients(self, val, inputs, grads):
2823 @tf.custom_gradient
2824 def tmp(input):
2825 def grad(upstream):
2826 return grads
2827
2828 return val, grad
2829
2830 return tmp(inputs)
2831
2832 def _detach(self, a):
2833 return tf.stop_gradient(a)
2834
2835 def zeros(self, shape, type_as=None):
2836 if type_as is None:
2837 return tnp.zeros(shape)
2838 else:
2839 return tnp.zeros(shape, dtype=type_as.dtype)
2840
2841 def ones(self, shape, type_as=None):
2842 if type_as is None:
2843 return tnp.ones(shape)
2844 else:
2845 return tnp.ones(shape, dtype=type_as.dtype)
2846
2847 def arange(self, stop, start=0, step=1, type_as=None):
2848 return tnp.arange(start, stop, step)
2849
2850 def full(self, shape, fill_value, type_as=None):
2851 if type_as is None:
2852 return tnp.full(shape, fill_value)
2853 else:
2854 return tnp.full(shape, fill_value, dtype=type_as.dtype)
2855
2856 def eye(self, N, M=None, type_as=None):
2857 if type_as is None:
2858 return tnp.eye(N, M)
2859 else:
2860 return tnp.eye(N, M, dtype=type_as.dtype)
2861
2862 def sum(self, a, axis=None, keepdims=False):
2863 return tnp.sum(a, axis, keepdims=keepdims)
2864
2865 def cumsum(self, a, axis=None):
2866 return tnp.cumsum(a, axis)
2867
2868 def max(self, a, axis=None, keepdims=False):
2869 return tnp.max(a, axis, keepdims=keepdims)
2870
2871 def min(self, a, axis=None, keepdims=False):
2872 return tnp.min(a, axis, keepdims=keepdims)
2873
2874 def maximum(self, a, b):
2875 return tnp.maximum(a, b)
2876
2877 def minimum(self, a, b):
2878 return tnp.minimum(a, b)
2879
2880 def sign(self, a):
2881 return tnp.sign(a)
2882
2883 def dot(self, a, b):
2884 if len(b.shape) == 1:
2885 if len(a.shape) == 1:
2886 # inner product
2887 return tf.reduce_sum(tf.multiply(a, b))
2888 else:
2889 # matrix vector
2890 return tf.linalg.matvec(a, b)
2891 else:
2892 if len(a.shape) == 1:
2893 return tf.linalg.matvec(b.T, a.T).T
2894 else:
2895 return tf.matmul(a, b)
2896
2897 def abs(self, a):
2898 return tnp.abs(a)
2899
2900 def exp(self, a):
2901 return tnp.exp(a)
2902
2903 def log(self, a):
2904 return tnp.log(a)
2905
2906 def sqrt(self, a):
2907 return tnp.sqrt(a)
2908
2909 def power(self, a, exponents):
2910 return tnp.power(a, exponents)
2911
2912 def norm(self, a, axis=None, keepdims=False):
2913 return tf.math.reduce_euclidean_norm(a, axis=axis, keepdims=keepdims)
2914
2915 def any(self, a):
2916 return tnp.any(a)
2917
2918 def isnan(self, a):
2919 return tnp.isnan(a)
2920
2921 def isinf(self, a):
2922 return tnp.isinf(a)
2923
2924 def einsum(self, subscripts, *operands):
2925 return tnp.einsum(subscripts, *operands)
2926
2927 def sort(self, a, axis=-1):
2928 return tnp.sort(a, axis)
2929
2930 def argsort(self, a, axis=-1):
2931 return tnp.argsort(a, axis)
2932
2933 def searchsorted(self, a, v, side="left"):
2934 return tf.searchsorted(a, v, side=side)
2935
2936 def flip(self, a, axis=None):
2937 return tnp.flip(a, axis)
2938
2939 def outer(self, a, b):
2940 return tnp.outer(a, b)
2941
2942 def clip(self, a, a_min, a_max):
2943 return tnp.clip(a, a_min, a_max)
2944
2945 def repeat(self, a, repeats, axis=None):
2946 return tnp.repeat(a, repeats, axis)
2947
2948 def take_along_axis(self, arr, indices, axis):
2949 return tnp.take_along_axis(arr, indices, axis)
2950
2951 def concatenate(self, arrays, axis=0):
2952 return tnp.concatenate(arrays, axis)
2953
2954 def zero_pad(self, a, pad_width, value=0):
2955 return tnp.pad(a, pad_width, mode="constant", constant_values=value)
2956
2957 def argmax(self, a, axis=None):
2958 return tnp.argmax(a, axis=axis)
2959
2960 def argmin(self, a, axis=None):
2961 return tnp.argmin(a, axis=axis)
2962
2963 def mean(self, a, axis=None):
2964 return tnp.mean(a, axis=axis)
2965
2966 def median(self, a, axis=None):
2967 warnings.warn(
2968 "The median is being computed using numpy and the array has been detached "
2969 "in the Tensorflow backend."
2970 )
2971 a_ = self.to_numpy(a)
2972 a_median = np.median(a_, axis=axis)
2973 return self.from_numpy(a_median, type_as=a)
2974
2975 def std(self, a, axis=None):
2976 return tnp.std(a, axis=axis)
2977
2978 def linspace(self, start, stop, num, type_as=None):
2979 if type_as is None:
2980 return tnp.linspace(start, stop, num)
2981 else:
2982 return tnp.linspace(start, stop, num, dtype=type_as.dtype)
2983
2984 def meshgrid(self, a, b):
2985 return tnp.meshgrid(a, b)
2986
2987 def diag(self, a, k=0):
2988 return tnp.diag(a, k)
2989
2990 def unique(self, a, return_inverse=False):
2991 y, idx = tf.unique(tf.reshape(a, [-1]))
2992 sort_idx = tf.argsort(y)
2993 y_prime = tf.gather(y, sort_idx)
2994 if return_inverse:
2995 inv_sort_idx = tf.math.invert_permutation(sort_idx)
2996 return y_prime, tf.gather(inv_sort_idx, idx)
2997 else:
2998 return y_prime
2999
3000 def logsumexp(self, a, axis=None):
3001 return tf.math.reduce_logsumexp(a, axis=axis)
3002
3003 def stack(self, arrays, axis=0):
3004 return tnp.stack(arrays, axis)
3005
3006 def reshape(self, a, shape):
3007 return tnp.reshape(a, shape)
3008
3009 def seed(self, seed=None):
3010 if isinstance(seed, int):
3011 self.rng_ = tf.random.Generator.from_seed(seed)
3012 elif isinstance(seed, tf.random.Generator):
3013 self.rng_ = seed
3014 elif seed is None:
3015 self.rng_ = tf.random.Generator.from_non_deterministic_state()
3016 else:
3017 raise ValueError("Non compatible seed : {}".format(seed))
3018
3019 def rand(self, *size, type_as=None):
3020 if type_as is None:
3021 return self.rng_.uniform(size, minval=0.0, maxval=1.0)
3022 else:
3023 return self.rng_.uniform(size, minval=0.0, maxval=1.0, dtype=type_as.dtype)
3024
3025 def randn(self, *size, type_as=None):
3026 if type_as is None:
3027 return self.rng_.normal(size)
3028 else:
3029 return self.rng_.normal(size, dtype=type_as.dtype)
3030
3031 def _convert_to_index_for_coo(self, tensor):
3032 if isinstance(tensor, self.__type__):
3033 return int(self.max(tensor)) + 1
3034 else:
3035 return int(np.max(tensor)) + 1
3036
3037 def coo_matrix(self, data, rows, cols, shape=None, type_as=None):
3038 if shape is None:
3039 shape = (
3040 self._convert_to_index_for_coo(rows),
3041 self._convert_to_index_for_coo(cols),
3042 )
3043 if type_as is not None:
3044 data = self.from_numpy(data, type_as=type_as)
3045
3046 sparse_tensor = tf.sparse.SparseTensor(
3047 indices=tnp.stack([rows, cols]).T, values=data, dense_shape=shape
3048 )
3049 # if type_as is not None:
3050 # sparse_tensor = self.from_numpy(sparse_tensor, type_as=type_as)
3051 # SparseTensor are not subscriptable so we use dense tensors
3052 return self.todense(sparse_tensor)
3053
3054 def issparse(self, a):
3055 return isinstance(a, tf.sparse.SparseTensor)
3056
3057 def tocsr(self, a):
3058 return a
3059
3060 def eliminate_zeros(self, a, threshold=0.0):
3061 if self.issparse(a):
3062 values = a.values
3063 if threshold > 0:
3064 mask = self.abs(values) <= threshold
3065 else:
3066 mask = values == 0
3067 return tf.sparse.retain(a, ~mask)
3068 else:
3069 if threshold > 0:
3070 a = tnp.where(self.abs(a) > threshold, a, 0.0)
3071 return a
3072
3073 def todense(self, a):
3074 if self.issparse(a):
3075 return tf.sparse.to_dense(tf.sparse.reorder(a))
3076 else:
3077 return a
3078
3079 def where(self, condition, x=None, y=None):
3080 if x is None and y is None:
3081 return tnp.where(condition)
3082 else:
3083 return tnp.where(condition, x, y)
3084
3085 def copy(self, a):
3086 return tf.identity(a)
3087
3088 def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
3089 return tnp.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
3090
3091 def dtype_device(self, a):
3092 return a.dtype, a.device.split("device:")[1]
3093
3094 def assert_same_dtype_device(self, a, b):
3095 a_dtype, a_device = self.dtype_device(a)
3096 b_dtype, b_device = self.dtype_device(b)
3097
3098 assert a_dtype == b_dtype, "Dtype discrepancy"
3099 assert (
3100 a_device == b_device
3101 ), f"Device discrepancy. First input is on {str(a_device)}, whereas second input is on {str(b_device)}"
3102
3103 def squeeze(self, a, axis=None):
3104 return tnp.squeeze(a, axis=axis)
3105
3106 def bitsize(self, type_as):
3107 return type_as.dtype.size * 8
3108
3109 def device_type(self, type_as):
3110 return self.dtype_device(type_as)[1].split(":")[0]
3111
3112 def _bench(self, callable, *args, n_runs=1, warmup_runs=1):
3113 results = dict()
3114 device_contexts = [tf.device("/CPU:0")]
3115 if len(tf.config.list_physical_devices("GPU")) > 0: # pragma: no cover
3116 device_contexts.append(tf.device("/GPU:0"))
3117
3118 for device_context in device_contexts:
3119 with device_context:
3120 for type_as in self.__type_list__:
3121 inputs = [self.from_numpy(arg, type_as=type_as) for arg in args]
3122 for _ in range(warmup_runs):
3123 callable(*inputs)
3124 t0 = time.perf_counter()
3125 for _ in range(n_runs):
3126 res = callable(*inputs)
3127 _ = res.numpy()
3128 t1 = time.perf_counter()
3129 key = (
3130 "Tensorflow",
3131 self.device_type(inputs[0]),
3132 self.bitsize(type_as),
3133 )
3134 results[key] = (t1 - t0) / n_runs
3135
3136 return results
3137
3138 def solve(self, a, b):
3139 return tf.linalg.solve(a, b)
3140
3141 def trace(self, a):
3142 return tf.linalg.trace(a)
3143
3144 def inv(self, a):
3145 return tf.linalg.inv(a)
3146
3147 def sqrtm(self, a):
3148 L, V = tf.linalg.eigh(a)
3149 L = tf.sqrt(L)
3150 # Q[...] = V[...] @ diag(L[...])
3151 Q = tf.einsum("...jk,...k->...jk", V, L)
3152 # R[...] = Q[...] @ V[...].T
3153 return tf.einsum(
3154 "...jk,...kl->...jl", Q, tf.linalg.matrix_transpose(V, (0, 2, 1))
3155 )
3156
3157 def eigh(self, a):
3158 return tf.linalg.eigh(a)
3159
3160 def kl_div(self, p, q, mass=False, eps=1e-16):
3161 value = tnp.sum(p * tnp.log(p / q + eps))
3162 if mass:
3163 value = value + tnp.sum(q - p)
3164 return value
3165
3166 def isfinite(self, a):
3167 return tnp.isfinite(a)
3168
3169 def array_equal(self, a, b):
3170 return tnp.array_equal(a, b)
3171
3172 def is_floating_point(self, a):
3173 return a.dtype.is_floating
3174
3175 def tile(self, a, reps):
3176 return tnp.tile(a, reps)
3177
3178 def floor(self, a):
3179 return tf.floor(a)
3180
3181 def prod(self, a, axis=0):
3182 return tnp.prod(a, axis=axis)
3183
3184 def sort2(self, a, axis=-1):
3185 return self.sort(a, axis), self.argsort(a, axis)
3186
3187 def qr(self, a):
3188 return tf.linalg.qr(a)
3189
3190 def atan2(self, a, b):
3191 return tf.math.atan2(a, b)
3192
3193 def transpose(self, a, axes=None):
3194 return tf.transpose(a, perm=axes)
3195
3196 def matmul(self, a, b):
3197 return tnp.matmul(a, b)
3198
3199 # todo(okachaiev): replace this with a more reasonable implementation
3200 def nan_to_num(self, x, copy=True, nan=0.0, posinf=None, neginf=None):
3201 x = self.to_numpy(x)
3202 x = np.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf)
3203 return self.from_numpy(x)
3204
3205 def det(self, x):
3206 return tf.linalg.det(x)
3207
3208
3209 if tf:
3210 # Only register tensorflow backend if it is installed
3211 _register_backend_implementation(TensorflowBackend)