Debian Codegraph @

test/test_backend.py

raw symbols SCIP
1 """Tests for backend module"""
2
3 # Author: Remi Flamary <[email protected]>
4 # Nicolas Courty <[email protected]>
5 #
6 #
7 # License: MIT License
8
9 import numpy as np
10 import pytest
11 from numpy.testing import assert_array_almost_equal_nulp
12
13 import ot
14 import ot.backend
15 from ot.backend import get_backend, get_backend_list, jax, tf, to_numpy, torch
16
17
18 def test_get_backend_list():
19 lst = get_backend_list()
20
21 assert len(lst) > 0
22 assert isinstance(lst[0], ot.backend.NumpyBackend)
23
24
25 def test_to_numpy(nx):
26 v = nx.zeros(10)
27 M = nx.ones((10, 10))
28
29 v2 = to_numpy(v)
30 assert isinstance(v2, np.ndarray)
31
32 v2, M2 = to_numpy(v, M)
33 assert isinstance(M2, np.ndarray)
34
35
36 def test_get_backend_invalid():
37 # error if no parameters
38 with pytest.raises(ValueError):
39 get_backend()
40
41 # error if unknown types
42 with pytest.raises(ValueError):
43 get_backend(1, 2.0)
44
45
46 def test_get_backend(nx):
47 A = np.zeros((3, 2))
48 B = np.zeros((3, 1))
49
50 nx_np = get_backend(A)
51 assert nx_np.__name__ == "numpy"
52
53 A2, B2 = nx.from_numpy(A, B)
54
55 effective_nx = get_backend(A2)
56 assert effective_nx.__name__ == nx.__name__
57
58 effective_nx = get_backend(A2, B2)
59 assert effective_nx.__name__ == nx.__name__
60
61 if nx.__name__ != "numpy":
62 # test that types mathcing different backends in input raise an error
63 with pytest.raises(ValueError):
64 get_backend(A, B2)
65 else:
66 # Check that subclassing a numpy array does not break get_backend
67 # note: This is only tested for numpy as this is hard to be consistent
68 # with other backends
69 class nx_subclass(nx.__type__):
70 pass
71
72 A3 = nx_subclass(0)
73
74 effective_nx = get_backend(A3, B2)
75 assert effective_nx.__name__ == nx.__name__
76
77
78 def test_convert_between_backends(nx):
79 A = np.zeros((3, 2))
80 B = np.zeros((3, 1))
81
82 A2 = nx.from_numpy(A)
83 B2 = nx.from_numpy(B)
84
85 assert isinstance(A2, nx.__type__)
86 assert isinstance(B2, nx.__type__)
87
88 nx2 = get_backend(A2, B2)
89
90 assert nx2.__name__ == nx.__name__
91
92 assert_array_almost_equal_nulp(nx.to_numpy(A2), A)
93 assert_array_almost_equal_nulp(nx.to_numpy(B2), B)
94
95
96 def test_empty_backend():
97 rnd = np.random.RandomState(0)
98 M = rnd.randn(10, 3)
99 v = rnd.randn(3)
100
101 nx = ot.backend.Backend()
102
103 with pytest.raises(NotImplementedError):
104 nx.from_numpy(M)
105 with pytest.raises(NotImplementedError):
106 nx.to_numpy(M)
107 with pytest.raises(NotImplementedError):
108 nx.set_gradients(0, 0, 0)
109 with pytest.raises(NotImplementedError):
110 nx.zeros((10, 3))
111 with pytest.raises(NotImplementedError):
112 nx.ones((10, 3))
113 with pytest.raises(NotImplementedError):
114 nx.arange(10, 1, 2)
115 with pytest.raises(NotImplementedError):
116 nx.full((10, 3), 3.14)
117 with pytest.raises(NotImplementedError):
118 nx.eye((10, 3))
119 with pytest.raises(NotImplementedError):
120 nx.sum(M)
121 with pytest.raises(NotImplementedError):
122 nx.cumsum(M)
123 with pytest.raises(NotImplementedError):
124 nx.max(M)
125 with pytest.raises(NotImplementedError):
126 nx.min(M)
127 with pytest.raises(NotImplementedError):
128 nx.maximum(v, v)
129 with pytest.raises(NotImplementedError):
130 nx.minimum(v, v)
131 with pytest.raises(NotImplementedError):
132 nx.abs(M)
133 with pytest.raises(NotImplementedError):
134 nx.log(M)
135 with pytest.raises(NotImplementedError):
136 nx.exp(M)
137 with pytest.raises(NotImplementedError):
138 nx.sqrt(M)
139 with pytest.raises(NotImplementedError):
140 nx.power(v, 2)
141 with pytest.raises(NotImplementedError):
142 nx.dot(v, v)
143 with pytest.raises(NotImplementedError):
144 nx.norm(M)
145 with pytest.raises(NotImplementedError):
146 nx.exp(M)
147 with pytest.raises(NotImplementedError):
148 nx.any(M)
149 with pytest.raises(NotImplementedError):
150 nx.isnan(M)
151 with pytest.raises(NotImplementedError):
152 nx.isinf(M)
153 with pytest.raises(NotImplementedError):
154 nx.einsum("ij->i", M)
155 with pytest.raises(NotImplementedError):
156 nx.sort(M)
157 with pytest.raises(NotImplementedError):
158 nx.argsort(M)
159 with pytest.raises(NotImplementedError):
160 nx.searchsorted(v, v)
161 with pytest.raises(NotImplementedError):
162 nx.flip(M)
163 with pytest.raises(NotImplementedError):
164 nx.outer(v, v)
165 with pytest.raises(NotImplementedError):
166 nx.clip(M, -1, 1)
167 with pytest.raises(NotImplementedError):
168 nx.repeat(M, 0, 1)
169 with pytest.raises(NotImplementedError):
170 nx.take_along_axis(M, v, 0)
171 with pytest.raises(NotImplementedError):
172 nx.concatenate([v, v])
173 with pytest.raises(NotImplementedError):
174 nx.zero_pad(M, v)
175 with pytest.raises(NotImplementedError):
176 nx.argmax(M)
177 with pytest.raises(NotImplementedError):
178 nx.argmin(M)
179 with pytest.raises(NotImplementedError):
180 nx.mean(M)
181 with pytest.raises(NotImplementedError):
182 nx.median(M)
183 with pytest.raises(NotImplementedError):
184 nx.std(M)
185 with pytest.raises(NotImplementedError):
186 nx.linspace(0, 1, 50)
187 with pytest.raises(NotImplementedError):
188 nx.meshgrid(v, v)
189 with pytest.raises(NotImplementedError):
190 nx.diag(M)
191 with pytest.raises(NotImplementedError):
192 nx.unique([M, M])
193 with pytest.raises(NotImplementedError):
194 nx.logsumexp(M)
195 with pytest.raises(NotImplementedError):
196 nx.stack([M, M])
197 with pytest.raises(NotImplementedError):
198 nx.reshape(M, (5, 3, 2))
199 with pytest.raises(NotImplementedError):
200 nx.seed(42)
201 with pytest.raises(NotImplementedError):
202 nx.rand()
203 with pytest.raises(NotImplementedError):
204 nx.randn()
205 nx.coo_matrix(M, M, M)
206 with pytest.raises(NotImplementedError):
207 nx.issparse(M)
208 with pytest.raises(NotImplementedError):
209 nx.tocsr(M)
210 with pytest.raises(NotImplementedError):
211 nx.eliminate_zeros(M)
212 with pytest.raises(NotImplementedError):
213 nx.todense(M)
214 with pytest.raises(NotImplementedError):
215 nx.where(M, M, M)
216 with pytest.raises(NotImplementedError):
217 nx.copy(M)
218 with pytest.raises(NotImplementedError):
219 nx.allclose(M, M)
220 with pytest.raises(NotImplementedError):
221 nx.squeeze(M)
222 with pytest.raises(NotImplementedError):
223 nx.bitsize(M)
224 with pytest.raises(NotImplementedError):
225 nx.device_type(M)
226 with pytest.raises(NotImplementedError):
227 nx._bench(lambda x: x, M, n_runs=1)
228 with pytest.raises(NotImplementedError):
229 nx.solve(M, v)
230 with pytest.raises(NotImplementedError):
231 nx.trace(M)
232 with pytest.raises(NotImplementedError):
233 nx.inv(M)
234 with pytest.raises(NotImplementedError):
235 nx.sqrtm(M)
236 with pytest.raises(NotImplementedError):
237 nx.kl_div(M, M)
238 with pytest.raises(NotImplementedError):
239 nx.isfinite(M)
240 with pytest.raises(NotImplementedError):
241 nx.array_equal(M, M)
242 with pytest.raises(NotImplementedError):
243 nx.is_floating_point(M)
244 with pytest.raises(NotImplementedError):
245 nx.tile(M, (10, 1))
246 with pytest.raises(NotImplementedError):
247 nx.floor(M)
248 with pytest.raises(NotImplementedError):
249 nx.prod(M)
250 with pytest.raises(NotImplementedError):
251 nx.sort2(M)
252 with pytest.raises(NotImplementedError):
253 nx.qr(M)
254 with pytest.raises(NotImplementedError):
255 nx.atan2(v, v)
256 with pytest.raises(NotImplementedError):
257 nx.transpose(M)
258 with pytest.raises(NotImplementedError):
259 nx.detach(M)
260 with pytest.raises(NotImplementedError):
261 nx.matmul(M, M.T)
262 with pytest.raises(NotImplementedError):
263 nx.nan_to_num(M)
264 with pytest.raises(NotImplementedError):
265 nx.sign(M)
266 with pytest.raises(NotImplementedError):
267 nx.dtype_device(M)
268 with pytest.raises(NotImplementedError):
269 nx.assert_same_dtype_device(M, M)
270 with pytest.raises(NotImplementedError):
271 nx.eigh(M)
272 with pytest.raises(NotImplementedError):
273 nx.det(M)
274
275
276 def test_func_backends(nx):
277 rnd = np.random.RandomState(0)
278 M = rnd.randn(10, 3)
279 SquareM = rnd.randn(10, 10)
280 v = rnd.randn(3)
281 val = np.array([1.0])
282
283 M1 = rnd.randn(1, 2, 10, 10)
284 M2 = rnd.randn(3, 1, 10, 10)
285
286 # Sparse tensors test
287 sp_row = np.array([0, 3, 1, 0, 3])
288 sp_col = np.array([0, 3, 1, 2, 2])
289 sp_data = np.array([4, 5, 7, 9, 0], dtype=np.float64)
290
291 lst_tot = []
292
293 for nx in [ot.backend.NumpyBackend(), nx]:
294 print("Backend: ", nx.__name__)
295
296 lst_b = []
297 lst_name = []
298
299 Mb = nx.from_numpy(M)
300 SquareMb = nx.from_numpy(SquareM)
301 vb = nx.from_numpy(v)
302
303 M1b = nx.from_numpy(M1)
304 M2b = nx.from_numpy(M2)
305
306 val = nx.from_numpy(val)
307
308 sp_rowb = nx.from_numpy(sp_row)
309 sp_colb = nx.from_numpy(sp_col)
310 sp_datab = nx.from_numpy(sp_data)
311
312 A = nx.set_gradients(val, v, v)
313
314 lst_b.append(nx.to_numpy(A))
315 lst_name.append("set_gradients")
316
317 A = nx.detach(Mb)
318 A, B = nx.detach(Mb, Mb)
319 lst_b.append(nx.to_numpy(A))
320 lst_name.append("detach")
321
322 A = nx.zeros((10, 3))
323 A = nx.zeros((10, 3), type_as=Mb)
324 lst_b.append(nx.to_numpy(A))
325 lst_name.append("zeros")
326
327 A = nx.ones((10, 3))
328 A = nx.ones((10, 3), type_as=Mb)
329 lst_b.append(nx.to_numpy(A))
330 lst_name.append("ones")
331
332 A = nx.arange(10, 1, 2)
333 lst_b.append(nx.to_numpy(A))
334 lst_name.append("arange")
335
336 A = nx.full((10, 3), 3.14)
337 A = nx.full((10, 3), 3.14, type_as=Mb)
338 lst_b.append(nx.to_numpy(A))
339 lst_name.append("full")
340
341 A = nx.eye(10, 3)
342 A = nx.eye(10, 3, type_as=Mb)
343 lst_b.append(nx.to_numpy(A))
344 lst_name.append("eye")
345
346 A = nx.sum(Mb)
347 lst_b.append(nx.to_numpy(A))
348 lst_name.append("sum")
349
350 A = nx.sum(Mb, axis=1, keepdims=True)
351 lst_b.append(nx.to_numpy(A))
352 lst_name.append("sum(axis)")
353
354 A = nx.cumsum(Mb, 0)
355 lst_b.append(nx.to_numpy(A))
356 lst_name.append("cumsum(axis)")
357
358 A = nx.max(Mb)
359 lst_b.append(nx.to_numpy(A))
360 lst_name.append("max")
361
362 A = nx.max(Mb, axis=1, keepdims=True)
363 lst_b.append(nx.to_numpy(A))
364 lst_name.append("max(axis)")
365
366 A = nx.min(Mb)
367 lst_b.append(nx.to_numpy(A))
368 lst_name.append("min")
369
370 A = nx.min(Mb, axis=1, keepdims=True)
371 lst_b.append(nx.to_numpy(A))
372 lst_name.append("min(axis)")
373
374 A = nx.maximum(vb, 0)
375 lst_b.append(nx.to_numpy(A))
376 lst_name.append("maximum")
377
378 A = nx.minimum(vb, 0)
379 lst_b.append(nx.to_numpy(A))
380 lst_name.append("minimum")
381
382 A = nx.sign(vb)
383 lst_b.append(nx.to_numpy(A))
384 lst_name.append("sign")
385
386 A = nx.abs(Mb)
387 lst_b.append(nx.to_numpy(A))
388 lst_name.append("abs")
389
390 A = nx.log(A)
391 lst_b.append(nx.to_numpy(A))
392 lst_name.append("log")
393
394 A = nx.exp(Mb)
395 lst_b.append(nx.to_numpy(A))
396 lst_name.append("exp")
397
398 A = nx.sqrt(nx.abs(Mb))
399 lst_b.append(nx.to_numpy(A))
400 lst_name.append("sqrt")
401
402 A = nx.power(Mb, 2)
403 lst_b.append(nx.to_numpy(A))
404 lst_name.append("power")
405
406 A = nx.dot(vb, vb)
407 lst_b.append(nx.to_numpy(A))
408 lst_name.append("dot(v,v)")
409
410 A = nx.dot(Mb, vb)
411 lst_b.append(nx.to_numpy(A))
412 lst_name.append("dot(M,v)")
413
414 A = nx.dot(Mb, Mb.T)
415 lst_b.append(nx.to_numpy(A))
416 lst_name.append("dot(M,M)")
417
418 A = nx.norm(vb)
419 lst_b.append(nx.to_numpy(A))
420 lst_name.append("norm")
421
422 A = nx.norm(Mb, axis=1)
423 lst_b.append(nx.to_numpy(A))
424 lst_name.append("norm(M,axis=1)")
425
426 A = nx.norm(Mb, axis=1, keepdims=True)
427 lst_b.append(nx.to_numpy(A))
428 lst_name.append("norm(M,axis=1,keepdims=True)")
429
430 A = nx.any(vb > 0)
431 lst_b.append(nx.to_numpy(A))
432 lst_name.append("any")
433
434 A = nx.isnan(vb)
435 lst_b.append(nx.to_numpy(A))
436 lst_name.append("isnan")
437
438 A = nx.isinf(vb)
439 lst_b.append(nx.to_numpy(A))
440 lst_name.append("isinf")
441
442 A = nx.einsum("ij->i", Mb)
443 lst_b.append(nx.to_numpy(A))
444 lst_name.append("einsum(ij->i)")
445
446 A = nx.einsum("ij,j->i", Mb, vb)
447 lst_b.append(nx.to_numpy(A))
448 lst_name.append("nx.einsum(ij,j->i)")
449
450 A = nx.einsum("ij->i", Mb)
451 lst_b.append(nx.to_numpy(A))
452 lst_name.append("nx.einsum(ij->i)")
453
454 A = nx.sort(Mb)
455 lst_b.append(nx.to_numpy(A))
456 lst_name.append("sort")
457
458 A = nx.argsort(Mb)
459 lst_b.append(nx.to_numpy(A))
460 lst_name.append("argsort")
461
462 tmp = nx.sort(Mb)
463 A = nx.searchsorted(tmp, tmp, "right")
464 lst_b.append(nx.to_numpy(A))
465 lst_name.append("searchsorted")
466
467 A = nx.flip(Mb)
468 lst_b.append(nx.to_numpy(A))
469 lst_name.append("flip")
470
471 A = nx.outer(vb, vb)
472 lst_b.append(nx.to_numpy(A))
473 lst_name.append("outer")
474
475 A = nx.clip(vb, 0, 1)
476 lst_b.append(nx.to_numpy(A))
477 lst_name.append("clip")
478
479 A = nx.repeat(Mb, 0)
480 A = nx.repeat(Mb, 2, -1)
481 lst_b.append(nx.to_numpy(A))
482 lst_name.append("repeat")
483
484 A = nx.take_along_axis(vb, nx.arange(3), -1)
485 lst_b.append(nx.to_numpy(A))
486 lst_name.append("take_along_axis")
487
488 A = nx.concatenate((Mb, Mb), -1)
489 lst_b.append(nx.to_numpy(A))
490 lst_name.append("concatenate")
491
492 A = nx.zero_pad(Mb, len(Mb.shape) * [(3, 3)])
493 lst_b.append(nx.to_numpy(A))
494 lst_name.append("zero_pad")
495
496 A = nx.argmax(Mb)
497 lst_b.append(nx.to_numpy(A))
498 lst_name.append("argmax")
499
500 A = nx.argmin(Mb)
501 lst_b.append(nx.to_numpy(A))
502 lst_name.append("argmin")
503
504 A = nx.mean(Mb)
505 lst_b.append(nx.to_numpy(A))
506 lst_name.append("mean")
507
508 A = nx.median(Mb)
509 lst_b.append(nx.to_numpy(A))
510 lst_name.append("median")
511
512 A = nx.std(Mb)
513 lst_b.append(nx.to_numpy(A))
514 lst_name.append("std")
515
516 A = nx.linspace(0, 1, 50)
517 A = nx.linspace(0, 1, 50, type_as=Mb)
518 lst_b.append(nx.to_numpy(A))
519 lst_name.append("linspace")
520
521 X, Y = nx.meshgrid(vb, vb)
522 lst_b.append(np.stack([nx.to_numpy(X), nx.to_numpy(Y)]))
523 lst_name.append("meshgrid")
524
525 A = nx.diag(Mb)
526 lst_b.append(nx.to_numpy(A))
527 lst_name.append("diag2D")
528
529 A = nx.diag(vb, 1)
530 lst_b.append(nx.to_numpy(A))
531 lst_name.append("diag1D")
532
533 A = nx.unique(nx.from_numpy(np.stack([M, M])))
534 lst_b.append(nx.to_numpy(A))
535 lst_name.append("unique")
536
537 A, A2 = nx.unique(
538 nx.from_numpy(np.stack([M, M]).reshape(-1)), return_inverse=True
539 )
540 lst_b.append(nx.to_numpy(A))
541 lst_name.append("unique(M,return_inverse=True)[0]")
542 lst_b.append(nx.to_numpy(A2))
543 lst_name.append("unique(M,return_inverse=True)[1]")
544
545 A = nx.logsumexp(Mb)
546 lst_b.append(nx.to_numpy(A))
547 lst_name.append("logsumexp")
548
549 A = nx.stack([Mb, Mb])
550 lst_b.append(nx.to_numpy(A))
551 lst_name.append("stack")
552
553 A = nx.reshape(Mb, (5, 3, 2))
554 lst_b.append(nx.to_numpy(A))
555 lst_name.append("reshape")
556
557 sp_Mb = nx.coo_matrix(sp_datab, sp_rowb, sp_colb, shape=(4, 4))
558 nx.todense(Mb)
559 lst_b.append(nx.to_numpy(nx.todense(sp_Mb)))
560 lst_name.append("coo_matrix")
561
562 assert not nx.issparse(Mb), "Assert fail on: issparse (expected False)"
563 assert nx.issparse(sp_Mb) or nx.__name__ in (
564 "jax",
565 "tf",
566 ), "Assert fail on: issparse (expected True)"
567
568 A = nx.tocsr(sp_Mb)
569 lst_b.append(nx.to_numpy(nx.todense(A)))
570 lst_name.append("tocsr")
571
572 A = nx.eliminate_zeros(nx.copy(sp_datab), threshold=5.0)
573 lst_b.append(nx.to_numpy(A))
574 lst_name.append("eliminate_zeros (dense)")
575
576 A = nx.eliminate_zeros(sp_Mb)
577 lst_b.append(nx.to_numpy(nx.todense(A)))
578 lst_name.append("eliminate_zeros (sparse)")
579
580 A = nx.where(Mb >= nx.stack([nx.linspace(0, 1, 10)] * 3, axis=1), Mb, 0.0)
581 lst_b.append(nx.to_numpy(A))
582 lst_name.append("where (cond, x, y)")
583
584 A = nx.where(nx.from_numpy(np.array([True, False])))
585 lst_b.append(nx.to_numpy(nx.stack(A)))
586 lst_name.append("where (cond)")
587
588 A = nx.copy(Mb)
589 lst_b.append(nx.to_numpy(A))
590 lst_name.append("copy")
591
592 assert nx.allclose(Mb, Mb), "Assert fail on: allclose (expected True)"
593 assert not nx.allclose(2 * Mb, Mb), "Assert fail on: allclose (expected False)"
594
595 A = nx.squeeze(nx.zeros((3, 1, 4, 1)))
596 assert tuple(A.shape) == (3, 4), "Assert fail on: squeeze"
597
598 A = nx.bitsize(Mb)
599 lst_b.append(float(A))
600 lst_name.append("bitsize")
601
602 A = nx.device_type(Mb)
603 assert A in ("CPU", "GPU")
604
605 nx._bench(lambda x: x, M, n_runs=1)
606
607 A = nx.solve(SquareMb, Mb)
608 lst_b.append(nx.to_numpy(A))
609 lst_name.append("solve")
610
611 A = nx.trace(SquareMb)
612 lst_b.append(nx.to_numpy(A))
613 lst_name.append("trace")
614
615 A = nx.inv(SquareMb)
616 lst_b.append(nx.to_numpy(A))
617 lst_name.append("matrix inverse")
618
619 A = nx.sqrtm(SquareMb.T @ SquareMb)
620 lst_b.append(nx.to_numpy(A))
621 lst_name.append("matrix square root")
622
623 A = nx.sqrtm(nx.stack([SquareMb.T @ SquareMb] * 2, axis=0))[None, :]
624 lst_b.append(nx.to_numpy(A))
625 lst_name.append("broadcast matrix square root")
626
627 D, U = nx.eigh(SquareMb.T @ SquareMb)
628 lst_b.append(nx.to_numpy(nx.dot(U, nx.dot(nx.diag(D), U.T))))
629 lst_name.append("eigh ")
630
631 A = nx.kl_div(nx.abs(Mb), nx.abs(Mb) + 1)
632 lst_b.append(nx.to_numpy(A))
633 lst_name.append("Kullback-Leibler divergence")
634
635 A = nx.concatenate([vb, nx.from_numpy(np.array([np.inf, np.nan]))], axis=0)
636 A = nx.isfinite(A)
637 lst_b.append(nx.to_numpy(A))
638 lst_name.append("isfinite")
639
640 A = nx.tile(vb, (10, 1))
641 lst_b.append(nx.to_numpy(A))
642 lst_name.append("tile")
643
644 A = nx.floor(Mb)
645 lst_b.append(nx.to_numpy(A))
646 lst_name.append("floor")
647
648 A = nx.prod(Mb)
649 lst_b.append(nx.to_numpy(A))
650 lst_name.append("prod")
651
652 A, B = nx.sort2(Mb)
653 lst_b.append(nx.to_numpy(A))
654 lst_name.append("sort2 sort")
655 lst_b.append(nx.to_numpy(B))
656 lst_name.append("sort2 argsort")
657
658 A, B = nx.qr(Mb)
659 lst_b.append(nx.to_numpy(A))
660 lst_name.append("QR Q")
661 lst_b.append(nx.to_numpy(B))
662 lst_name.append("QR R")
663
664 A = nx.atan2(vb, vb)
665 lst_b.append(nx.to_numpy(A))
666 lst_name.append("atan2")
667
668 A = nx.transpose(Mb)
669 lst_b.append(nx.to_numpy(A))
670 lst_name.append("transpose")
671
672 A, B = nx.detach(Mb, Mb)
673 lst_b.append(nx.to_numpy(A))
674 lst_name.append("detach A")
675 lst_b.append(nx.to_numpy(B))
676 lst_name.append("detach B")
677
678 A = nx.matmul(Mb, Mb.T)
679 lst_b.append(nx.to_numpy(A))
680 lst_name.append("matmul")
681 A = nx.matmul(M1b, M2b)
682 lst_b.append(nx.to_numpy(A))
683 lst_name.append("matmul broadcast")
684
685 vec = nx.from_numpy(np.array([1, np.nan, -1]))
686 vec = nx.nan_to_num(vec, nan=0)
687 lst_b.append(nx.to_numpy(vec))
688 lst_name.append("nan_to_num")
689
690 d = nx.det(M1b)
691 lst_b.append(nx.to_numpy(d))
692 lst_name.append("det")
693
694 assert not nx.array_equal(Mb, vb), "array_equal (shape)"
695 assert nx.array_equal(Mb, Mb), "array_equal (elements) - expected true"
696 assert not nx.array_equal(
697 Mb, Mb + nx.eye(*list(Mb.shape))
698 ), "array_equal (elements) - expected false"
699
700 assert nx.is_floating_point(Mb), "is_floating_point - expected true"
701 assert not nx.is_floating_point(
702 nx.from_numpy(np.array([0, 1, 2], dtype=int))
703 ), "is_floating_point - expected false"
704
705 lst_tot.append(lst_b)
706
707 lst_np = lst_tot[0]
708 lst_b = lst_tot[1]
709
710 for a1, a2, name in zip(lst_np, lst_b, lst_name):
711 np.testing.assert_allclose(
712 a2, a1, atol=1e-7, err_msg=f"ASSERT FAILED ON: {name}"
713 )
714
715
716 def test_random_backends(nx):
717 tmp_u = nx.rand()
718
719 assert tmp_u < 1
720
721 tmp_n = nx.randn()
722
723 nx.seed(0)
724 M1 = nx.to_numpy(nx.rand(5, 2))
725 nx.seed(0)
726 M2 = nx.to_numpy(nx.rand(5, 2, type_as=tmp_n))
727
728 assert np.all(M1 >= 0)
729 assert np.all(M1 < 1)
730 assert M1.shape == (5, 2)
731 assert np.allclose(M1, M2)
732
733 nx.seed(0)
734 M1 = nx.to_numpy(nx.randn(5, 2))
735 nx.seed(0)
736 M2 = nx.to_numpy(nx.randn(5, 2, type_as=tmp_u))
737
738 nx.seed(42)
739 v1 = nx.randn()
740 v2 = nx.randn()
741 assert v1 != v2
742
743
744 def test_gradients_backends():
745 rnd = np.random.RandomState(0)
746 v = rnd.randn(10)
747 c = rnd.randn()
748 e = rnd.randn()
749
750 if torch:
751 nx = ot.backend.TorchBackend()
752
753 v2 = torch.tensor(v, requires_grad=True)
754 c2 = torch.tensor(c, requires_grad=True)
755
756 val = c2 * torch.sum(v2 * v2)
757
758 val2 = nx.set_gradients(val, (v2, c2), (v2, c2))
759
760 val2.backward()
761
762 assert torch.equal(v2.grad, v2)
763 assert torch.equal(c2.grad, c2)
764
765 if jax:
766 nx = ot.backend.JaxBackend()
767 with jax.checking_leaks():
768
769 def fun(a, b, d):
770 val = b * nx.sum(a**4) + d
771 return nx.set_gradients(val, (a, b, d), (a, b, 2 * d))
772
773 grad_val = jax.grad(fun, argnums=(0, 1, 2))(v, c, e)
774
775 np.testing.assert_almost_equal(fun(v, c, e), c * np.sum(v**4) + e, decimal=4)
776 np.testing.assert_allclose(grad_val[0], v, atol=1e-4)
777 np.testing.assert_allclose(grad_val[2], 2 * e, atol=1e-4)
778
779 if tf:
780 nx = ot.backend.TensorflowBackend()
781 w = tf.Variable(tf.random.normal((3, 2)), name="w")
782 b = tf.Variable(tf.random.normal((2,), dtype=tf.float32), name="b")
783 x = tf.random.normal((1, 3), dtype=tf.float32)
784
785 with tf.GradientTape() as tape:
786 y = x @ w + b
787 loss = tf.reduce_mean(y**2)
788 manipulated_loss = nx.set_gradients(loss, (w, b), (w, b))
789 [dl_dw, dl_db] = tape.gradient(manipulated_loss, [w, b])
790 assert nx.allclose(dl_dw, w)
791 assert nx.allclose(dl_db, b)
792
793
794 def test_get_backend_none():
795 a, b = np.zeros((2, 3)), None
796 nx = get_backend(a, b)
797 assert str(nx) == "numpy"
798 with pytest.raises(ValueError):
799 get_backend(None, None)