This repository was archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
Expand file tree
/
Copy pathtest_numpy_op.py
More file actions
11803 lines (10433 loc) · 472 KB
/
test_numpy_op.py
File metadata and controls
11803 lines (10433 loc) · 472 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
from __future__ import absolute_import
from distutils.version import StrictVersion
import sys
import copy
import itertools
from mxnet.gluon.parameter import Parameter
import numpy as onp
import platform
import mxnet as mx
import scipy.stats as ss
import scipy.special as scipy_special
import pytest
import mxnet.ndarray.numpy._internal as _npi
from functools import reduce
from packaging.version import parse
from mxnet import np, npx
from mxnet.gluon import HybridBlock
from mxnet.base import MXNetError
from mxnet.test_utils import same, assert_almost_equal, rand_shape_nd, rand_ndarray
from mxnet.test_utils import check_numeric_gradient, use_np, collapse_sum_like, effective_dtype
from mxnet.test_utils import new_matrix_with_real_eigvals_nd
from mxnet.test_utils import new_sym_matrix_with_real_eigvals_nd
from common import assertRaises, retry, xfail_when_nonstandard_decimal_separator
import random
from mxnet.test_utils import verify_generator, gen_buckets_probs_with_ppf
from mxnet.numpy_op_signature import _get_builtin_op
from mxnet.test_utils import is_op_runnable, has_tvm_ops, rand_shape_2d
from mxnet.operator import get_all_registered_operators
from common import assert_raises_cuda_not_satisfied
from numpy.testing import assert_allclose
@use_np
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
@pytest.mark.parametrize('a_shape,b_shape,axes', [
((3, 5), (5, 4), 1),
((3,), (3,), 1),
((3, 4, 5, 3, 2), (5, 3, 2, 1, 2), 3),
((3, 5, 4, 3, 2), (2, 3, 5, 1, 2), [[1, 3, 4], [2, 1, 0]]),
((3, 5, 4), (5, 4, 3), [[1, 0, 2], [0, 2, 1]]),
((3, 5, 4), (5, 3, 4), [[2, 0], [-1, -2]]),
((2, 2), (2, 2), 2),
((3, 5, 4), (5, ), [[-2], [0]]),
((3, 5, 4), (5, ), [[1], [0]]),
((2,), (2, 3), 1),
((3,), (3,), 0),
((2,), (2, 3), 0),
((3, 5, 4), (5, ), 0),
((2, 3, 4), (4, 3, 2), [[], []]),
((3, 0), (0, 5), 1),
((3, 0), (0, 4), [[1], [0]]),
((0, 3), (3, 5), 1),
((0, 3), (5, 0), [[0], [1]])
])
def test_np_tensordot(a_shape, b_shape, axes, hybridize, dtype):
class TestTensordot(HybridBlock):
def __init__(self, axes):
super(TestTensordot, self).__init__()
self._axes = axes
def forward(self, a, b):
return np.tensordot(a, b, self._axes)
def tensordot_backward(out_grad, a, b, axes=2):
if (a.ndim < 1) or (b.ndim < 1):
raise ValueError('An input is zero-dim')
if onp.isscalar(axes):
a_axes_summed = [i + a.ndim - axes for i in range(axes)]
b_axes_summed = [i for i in range(axes)]
else:
if len(axes) != 2:
raise ValueError('Axes must consist of two arrays.')
a_axes_summed, b_axes_summed = axes
if onp.isscalar(a_axes_summed):
a_axes_summed = a_axes_summed,
if onp.isscalar(b_axes_summed):
b_axes_summed = b_axes_summed,
for i in range(len(a_axes_summed)):
a_axes_summed[i] = (a_axes_summed[i] + a.ndim) % a.ndim
for i in range(len(b_axes_summed)):
b_axes_summed[i] = (b_axes_summed[i] + b.ndim) % b.ndim
if len(a_axes_summed) != len(b_axes_summed):
raise ValueError('Axes length mismatch')
a_axes_remained = []
for i in range(a.ndim):
if not (i in a_axes_summed):
a_axes_remained.append(i)
a_axes = a_axes_remained[:] + a_axes_summed[:]
b_axes_remained = []
for i in range(b.ndim):
if not (i in b_axes_summed):
b_axes_remained.append(i)
b_axes = b_axes_summed[:] + b_axes_remained[:]
ad1 = onp.prod([a.shape[i] for i in a_axes_remained]) if len(a_axes_remained) > 0 else 1
ad2 = onp.prod([a.shape[i] for i in a_axes_summed]) if len(a_axes_summed) > 0 else 1
bd1 = onp.prod([b.shape[i] for i in b_axes_summed]) if len(b_axes_summed) > 0 else 1
bd2 = onp.prod([b.shape[i] for i in b_axes_remained]) if len(b_axes_remained) > 0 else 1
out_grad = out_grad.reshape((ad1, bd2))
new_a = onp.transpose(a, a_axes)
new_a_shape = new_a.shape[:]
new_a = new_a.reshape((ad1, ad2))
new_b = onp.transpose(b, b_axes)
new_b_shape = new_b.shape[:]
new_b = new_b.reshape((bd1, bd2))
reverse_a_axes = [0 for i in a_axes]
for i in range(len(a_axes)):
reverse_a_axes[a_axes[i]] = i
reverse_b_axes = [0 for i in b_axes]
for i in range(len(b_axes)):
reverse_b_axes[b_axes[i]] = i
grad_b = onp.dot(new_a.T, out_grad).reshape(new_b_shape)
grad_b = onp.transpose(grad_b, reverse_b_axes)
grad_a = onp.dot(out_grad, new_b.T).reshape(new_a_shape)
grad_a = onp.transpose(grad_a, reverse_a_axes)
return [grad_a, grad_b]
test_tensordot = TestTensordot(axes)
if hybridize:
test_tensordot.hybridize()
a = rand_ndarray(shape = a_shape, dtype = dtype).as_np_ndarray()
b = rand_ndarray(shape = b_shape, dtype = dtype).as_np_ndarray()
a.attach_grad()
b.attach_grad()
np_out = onp.tensordot(a.asnumpy(), b.asnumpy(), axes)
with mx.autograd.record():
mx_out = test_tensordot(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol = 1e-3, atol = 1e-5)
mx_out.backward()
np_backward = tensordot_backward(onp.ones(np_out.shape), a.asnumpy(), b.asnumpy(), axes)
assert_almost_equal(a.grad.asnumpy(), np_backward[0], rtol = 1e-3, atol=1e-5)
assert_almost_equal(b.grad.asnumpy(), np_backward[1], rtol = 1e-3, atol=1e-5)
# Test imperative once again
mx_out = np.tensordot(a, b, axes)
np_out = onp.tensordot(a.asnumpy(), b.asnumpy(), axes)
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
# test numeric gradient
if (onp.prod(a_shape) > 0 and onp.prod(b_shape) > 0):
a_sym = mx.sym.Variable("a").as_np_ndarray()
b_sym = mx.sym.Variable("b").as_np_ndarray()
mx_sym = mx.sym.np.tensordot(a_sym, b_sym, axes).as_nd_ndarray()
check_numeric_gradient(mx_sym, [a.as_nd_ndarray(), b.as_nd_ndarray()],
rtol=1e-1, atol=1e-1, dtype = dtype)
# General Gradient Test
for a_grad_status in ['add', 'write']:
for b_grad_status in ['add', 'write']:
a = mx.np.random.normal(0, 1, a_shape)
b = mx.np.random.normal(0, 1, b_shape)
a.attach_grad(a_grad_status)
b.attach_grad(b_grad_status)
if a_grad_status == 'add':
ori_a_grad = mx.np.random.normal(0, 1, a_shape)
if a.ndim == 0:
a.grad[()] = ori_a_grad
else:
a.grad[:] = ori_a_grad
if b_grad_status == 'add':
ori_b_grad = mx.np.random.normal(0, 1, b_shape)
if b.ndim == 0:
b.grad[()] = ori_b_grad
else:
b.grad[:] = ori_b_grad
with mx.autograd.record():
mx_out = mx.np.tensordot(a, b, axes)
out_grad = mx.np.random.normal(0, 1, mx_out.shape)
loss = (mx_out * out_grad).sum()
loss.backward()
gt_in_grad = tensordot_backward(out_grad.asnumpy(), a.asnumpy(), b.asnumpy(), axes)
if(a_grad_status == 'add'):
gt_in_grad[0] += ori_a_grad
if(b_grad_status == 'add'):
gt_in_grad[1] += ori_b_grad
assert_almost_equal(a.grad.asnumpy(), gt_in_grad[0], rtol=1e-2, atol=1e-2)
assert_almost_equal(b.grad.asnumpy(), gt_in_grad[1], rtol=1e-2, atol=1e-2)
@use_np
@pytest.mark.parametrize('shape_a,shape_b', [
((3, 0), (0, 4)),
((3,), (3,)),
((3, 4), (4, 5)),
((), ()),
((3, 4, 5), ()),
((), (3, 4, 5)),
((3, 4, 5), (5, )),
((3, 4, 5), (5, 2)),
((5,), (5, 2)),
((3, 5, 4), (5, 4, 3)),
((3, 4), (5, 4, 3)),
((4,), (5, 4, 3))
])
def test_np_dot(shape_a, shape_b):
eps = 1e-3
np_a = onp.random.uniform(-1.0, 1.0, shape_a)
np_a[abs(np_a) < eps] = 2 * eps
np_b = onp.random.uniform(-1.0, 1.0, shape_b)
np_b[abs(np_b) < eps] = 2 * eps
a = mx.nd.array(np_a)
b = mx.nd.array(np_b)
np_res = onp.dot(np_a, np_b)
mx_res = np.dot(a.as_np_ndarray(), b.as_np_ndarray())
assert mx_res.shape == np_res.shape
assert_almost_equal(np_res, mx_res.asnumpy(), rtol=1e-5, atol=1e-5)
mx_a = mx.sym.Variable("a")
mx_b = mx.sym.Variable("b")
mx_sym = mx.sym.np.dot(mx_a.as_np_ndarray(), mx_b.as_np_ndarray()).as_nd_ndarray()
if (len(shape_a) > 0 and len(shape_b) > 0 and onp.prod(shape_a) > 0 and onp.prod(shape_b) > 0):
check_numeric_gradient(mx_sym, {"a": a, "b": b}, numeric_eps=eps, rtol=1e-2, atol=1e-3)
@use_np
@pytest.mark.parametrize('shape_a,shape_b', [
((4, 5), (2, 3)),
((3, 4, 5), (6, ))
])
def test_np_dot_error(shape_a, shape_b):
a = mx.nd.array(random.random()) if len(shape_a) == 0 else rand_ndarray(shape_a)
b = mx.nd.array(random.random()) if len(shape_b) == 0 else rand_ndarray(shape_b)
with pytest.raises(mx.base.MXNetError):
mx_res = np.dot(a.as_np_ndarray(), b.as_np_ndarray())
@use_np
@pytest.mark.parametrize('shape', [(), (5,), (3, 3)])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
def test_np_vdot(shape, dtype, hybridize):
class TestVdot(HybridBlock):
def __init__(self):
super(TestVdot, self).__init__()
def forward(self, a, b):
return np.vdot(a, b)
def vdot_backward(a, b):
return [b, a]
test_vdot = TestVdot()
if hybridize:
test_vdot.hybridize()
a = rand_ndarray(shape=shape, dtype=dtype).as_np_ndarray()
b = rand_ndarray(shape=shape, dtype=dtype).as_np_ndarray()
a.attach_grad()
b.attach_grad()
np_out = onp.vdot(a.asnumpy(), b.asnumpy())
with mx.autograd.record():
mx_out = test_vdot(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol = 1e-3, atol = 1e-5)
mx_out.backward()
np_backward = vdot_backward(a.asnumpy(), b.asnumpy())
assert_almost_equal(a.grad.asnumpy(), np_backward[0], rtol = 1e-2, atol=1e-2)
assert_almost_equal(b.grad.asnumpy(), np_backward[1], rtol = 1e-2, atol=1e-2)
# Test imperative once again
mx_out = np.vdot(a, b)
np_out = onp.vdot(a.asnumpy(), b.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
# test numeric gradient
if len(shape) > 0 and onp.prod(shape) > 0:
a_sym = mx.sym.Variable("a").as_np_ndarray()
b_sym = mx.sym.Variable("b").as_np_ndarray()
mx_sym = mx.sym.np.vdot(a_sym, b_sym).as_nd_ndarray()
check_numeric_gradient(mx_sym, [a.as_nd_ndarray(), b.as_nd_ndarray()],
rtol=1e-1, atol=1e-1, dtype=dtype)
@use_np
@pytest.mark.parametrize('a_shape,b_shape', [
((3,), (3,)),
((2, 3), (3,)),
((3,), (2, 3))
])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
def test_np_inner(a_shape, b_shape, dtype, hybridize):
class TestInner(HybridBlock):
def __init__(self):
super(TestInner, self).__init__()
def forward(self, a, b):
return np.inner(a, b)
def inner_backward(a, b):
a_axes_summed = [a.ndim - 1]
b_axes_summed = [b.ndim - 1]
a_axes_remained = []
for i in range(a.ndim):
if not (i in a_axes_summed):
a_axes_remained.append(i)
a_axes = a_axes_remained[:] + a_axes_summed[:]
b_axes_remained = []
for i in range(b.ndim):
if not (i in b_axes_summed):
b_axes_remained.append(i)
b_axes = b_axes_summed[:] + b_axes_remained[:]
ad1 = onp.prod([a.shape[i] for i in a_axes_remained]) if len(a_axes_remained) > 0 else 1
ad2 = onp.prod([a.shape[i] for i in a_axes_summed]) if len(a_axes_summed) > 0 else 1
bd1 = onp.prod([b.shape[i] for i in b_axes_summed]) if len(b_axes_summed) > 0 else 1
bd2 = onp.prod([b.shape[i] for i in b_axes_remained]) if len(b_axes_remained) > 0 else 1
out_grad = onp.ones((ad1, bd2))
new_a = onp.transpose(a, a_axes)
new_a_shape = new_a.shape[:]
new_a = new_a.reshape((ad1, ad2))
new_b = onp.transpose(b, b_axes)
new_b_shape = new_b.shape[:]
new_b = new_b.reshape((bd1, bd2))
reverse_a_axes = [0 for i in a_axes]
for i in range(len(a_axes)):
reverse_a_axes[a_axes[i]] = i
reverse_b_axes = [0 for i in b_axes]
for i in range(len(b_axes)):
reverse_b_axes[b_axes[i]] = i
grad_b = onp.dot(new_a.T, out_grad).reshape(new_b_shape)
grad_b = onp.transpose(grad_b, reverse_b_axes)
grad_a = onp.dot(out_grad, new_b.T).reshape(new_a_shape)
grad_a = onp.transpose(grad_a, reverse_a_axes)
return [grad_a, grad_b]
test_inner = TestInner()
if hybridize:
test_inner.hybridize()
a = rand_ndarray(shape=a_shape, dtype=dtype).as_np_ndarray()
b = rand_ndarray(shape=b_shape, dtype=dtype).as_np_ndarray()
a.attach_grad()
b.attach_grad()
np_out = onp.inner(a.asnumpy(), b.asnumpy())
with mx.autograd.record():
mx_out = test_inner(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol = 1e-3, atol = 1e-5)
mx_out.backward()
np_backward = inner_backward(a.asnumpy(), b.asnumpy())
assert_almost_equal(a.grad.asnumpy(), np_backward[0], rtol = 1e-2, atol=1e-2)
assert_almost_equal(b.grad.asnumpy(), np_backward[1], rtol = 1e-2, atol=1e-2)
# Test imperative once again
mx_out = np.inner(a, b)
np_out = onp.inner(a.asnumpy(), b.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
# test numeric gradient
a_sym = mx.sym.Variable("a").as_np_ndarray()
b_sym = mx.sym.Variable("b").as_np_ndarray()
mx_sym = mx.sym.np.inner(a_sym, b_sym).as_nd_ndarray()
check_numeric_gradient(mx_sym, [a.as_nd_ndarray(), b.as_nd_ndarray()],
rtol=1e-1, atol=1e-1, dtype=dtype)
@use_np
@pytest.mark.parametrize('a_shape,b_shape', [
((3,), (3,)),
((2, 3), (6,)),
((6,), (2, 3))
])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
def test_np_outer(a_shape, b_shape, dtype, hybridize):
class TestOuter(HybridBlock):
def __init__(self):
super(TestOuter, self).__init__()
def forward(self, a, b):
return np.outer(a, b)
test_outer = TestOuter()
if hybridize:
test_outer.hybridize()
a = rand_ndarray(shape=a_shape, dtype=dtype).as_np_ndarray()
b = rand_ndarray(shape=b_shape, dtype=dtype).as_np_ndarray()
a.attach_grad()
b.attach_grad()
np_out = onp.outer(a.asnumpy(), b.asnumpy())
with mx.autograd.record():
mx_out = test_outer(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
mx_out.backward()
# Test imperative once again
mx_out = np.outer(a, b)
np_out = onp.outer(a.asnumpy(), b.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
# test numeric gradient
a_sym = mx.sym.Variable("a").as_np_ndarray()
b_sym = mx.sym.Variable("b").as_np_ndarray()
mx_sym = mx.sym.np.outer(a_sym, b_sym).as_nd_ndarray()
check_numeric_gradient(mx_sym, [a.as_nd_ndarray(), b.as_nd_ndarray()],
rtol=1e-1, atol=1e-1, dtype=dtype)
@use_np
@pytest.mark.parametrize('shape_a,shape_b', [
((3,), (3,)),
((3, 4), (4, 5)),
((3, 0), (0, 4)),
((4, 5), (5,)),
((3, 4, 5), (5,)),
((5,), (5, 2)),
((2,), (4, 2, 3)),
((2, 1, 3, 4, 5), (5, 2)),
((1, 3, 5, 4), (1, 4, 3)),
((3, 5, 4), (2, 1, 4, 3)),
((3, 4), (1, 5, 4, 3))
])
@pytest.mark.parametrize('grad_req_a', ['write', 'add', 'null'])
@pytest.mark.parametrize('grad_req_b', ['write', 'add', 'null'])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
def test_np_matmul(shape_a, shape_b, grad_req_a, grad_req_b,
dtype, hybridize):
class TestMatmul(HybridBlock):
def __init__(self):
super(TestMatmul, self).__init__()
def forward(self, a, b):
return np.matmul(a, b)
def matmul_backward(a, b):
def ShapeInfer(mat_a, mat_b):
if mat_a.ndim == 1:
mat_a = mat_a.reshape((1, mat_a.size))
if mat_b.ndim == 1:
mat_b = mat_b.reshape((mat_b.size, 1))
ndim = max(mat_a.ndim, mat_b.ndim)
newshape_a = list(onp.array(mat_a, ndmin=ndim).shape)
newshape_b = list(onp.array(mat_b, ndmin=ndim).shape)
if ndim >= 3:
pre_shape = onp.fmax(newshape_a[ndim - 3::-1], newshape_b[ndim - 3::-1])
newshape_a[ndim - 3::-1] = pre_shape
newshape_b[ndim - 3::-1] = pre_shape
else:
pre_shape = onp.array([])
out_shape = onp.append(pre_shape[::-1].astype(onp.int64), [newshape_a[ndim - 2], newshape_b[ndim - 1]])
return [ndim, newshape_a, newshape_b, out_shape]
def ShapeReduce(mat, shape, is_b=False):
ndim = mat.ndim
if is_b and len(shape) == 1:
rng = onp.arange(ndim - 2)
else:
pre_len = ndim - len(shape)
in_pre = onp.array(mat.shape[pre_len : ndim - 2])
out_pre = onp.array(shape[:len(shape) - 2])
diff = onp.nonzero(in_pre != out_pre)[0] + pre_len
rng = onp.append(onp.arange(ndim - len(shape)), diff)
mat = onp.sum(mat, axis=tuple(rng))
return mat.reshape(shape)
a_shape = a.shape
b_shape = b.shape
[ndim, newshape_a, newshape_b, out_shape] = ShapeInfer(a, b)
new_a = onp.broadcast_to(a, newshape_a)
if len(b_shape) == 1:
new_b = onp.broadcast_to(b.reshape((b.size, 1)), newshape_b)
else:
new_b = onp.broadcast_to(b, newshape_b)
ad1 = new_a.shape[ndim - 2]
ad2 = new_a.shape[ndim - 1]
bd1 = new_b.shape[ndim - 2]
bd2 = new_b.shape[ndim - 1]
a_T = onp.moveaxis(new_a, [ndim - 2, ndim - 1], [ndim - 1, ndim - 2])
b_T = onp.moveaxis(new_b, [ndim - 2, ndim - 1], [ndim - 1, ndim - 2])
out_grad = onp.ones(out_shape)
grad_b = onp.matmul(a_T, out_grad)
grad_b = ShapeReduce(grad_b, b_shape, is_b=True)
grad_a = onp.matmul(out_grad, b_T)
grad_a = ShapeReduce(grad_a, a_shape)
return [grad_a, grad_b]
eps = 1E-4
test_matmul = TestMatmul()
if hybridize:
test_matmul.hybridize()
np_a = onp.random.uniform(-1.0, 1.0, shape_a).astype(dtype)
np_a[abs(np_a) < eps] = 2 * eps
np_b = onp.random.uniform(-1.0, 1.0, shape_b).astype(dtype)
np_b[abs(np_b) < eps] = 2 * eps
a = mx.np.array(np_a, dtype=dtype)
a.attach_grad(grad_req=grad_req_a)
b = mx.np.array(np_b, dtype=dtype)
b.attach_grad(grad_req=grad_req_b)
np_out = onp.matmul(np_a, np_b)
with mx.autograd.record():
mx_out = test_matmul(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(np_out, mx_out.asnumpy(), rtol=eps, atol=eps)
if grad_req_a != 'null' or grad_req_b != 'null':
mx_out.backward()
np_backward = matmul_backward(np_a, np_b)
if grad_req_a == 'null':
assert a.grad is None
else:
assert_almost_equal(a.grad.asnumpy(), np_backward[0], rtol = eps, atol=eps)
if grad_req_b == 'null':
assert b.grad is None
else:
assert_almost_equal(b.grad.asnumpy(), np_backward[1], rtol = eps, atol=eps)
mx_out = np.matmul(a, b)
np_out = onp.matmul(np_a, np_b)
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=eps, atol=eps)
@pytest.mark.parametrize('shape_a,shape_b', [
((1,), (2,)), # mismatched vector vector
((2, 1,), (2,)), # mismatched matrix vector
((2,), (1, 2)), # mismatched vector matrix
((1, 2), (3, 1)), # mismatched matrix matrix
((1,), ()), # vector scalar
((), (1,)), # scalar vector
((1, 1), ()), # matrix scalar
((), (1, 1)), # scalar matrix
((2, 2, 1), (3, 1, 2)), # cannot broadcast
])
def test_np_matmul_error(shape_a, shape_b):
a = np.random.uniform(size=shape_a)
b = np.random.uniform(size=shape_b)
with pytest.raises(MXNetError):
np.matmul(a, b)
@use_np
@pytest.mark.parametrize('a_shape,b_shape', [
((3,), (3,)),
((2, 3), (3,)),
((2, 3, 4), (2,)),
((3, 2), ())
])
@pytest.mark.parametrize('dtype', [onp.float32, onp.float64])
@pytest.mark.parametrize('hybridize', [True, False])
def test_np_kron(a_shape, b_shape, dtype, hybridize):
def np_kron_backward(ograd, a, b):
ndim = ograd.ndim
# Make ndim equal
if ndim > a.ndim:
a = a.reshape((1,)*(ndim - a.ndim) + a.shape)
else:
b = b.reshape((1,)*(ndim - b.ndim) + b.shape)
assert(a.ndim == b.ndim)
# Compute agrad
agrad = onp.zeros(a.shape)
for i in range(a.size):
ia = onp.asarray(onp.unravel_index(i, a.shape))
for j in range(b.size):
jb = onp.asarray(onp.unravel_index(j, b.shape))
k = ia * onp.asarray(b.shape) + jb
agrad[tuple(ia)] += ograd[tuple(k)] * b[tuple(jb)]
# Compute bgrad
bgrad = onp.zeros(b.shape)
for j in range(b.size):
jb = onp.asarray(onp.unravel_index(j, b.shape))
for i in range(a.size):
ia = onp.asarray(onp.unravel_index(i, a.shape))
k = ia * onp.asarray(b.shape) + jb
bgrad[tuple(jb)] += ograd[tuple(k)] * a[tuple(ia)]
return [agrad, bgrad]
class TestKron(HybridBlock):
def __init__(self):
super(TestKron, self).__init__()
def forward(self, a, b):
return np.kron(a, b)
test_kron = TestKron()
if hybridize:
test_kron.hybridize()
a = rand_ndarray(shape=a_shape, dtype=dtype).as_np_ndarray()
b = rand_ndarray(shape=b_shape, dtype=dtype).as_np_ndarray()
a.attach_grad()
b.attach_grad()
np_out = onp.kron(a.asnumpy(), b.asnumpy())
with mx.autograd.record():
mx_out = test_kron(a, b)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5, use_broadcast=False)
mx_out.backward()
# Test imperative once again
mx_out = np.kron(a, b)
np_out = onp.kron(a.asnumpy(), b.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5, use_broadcast=False)
# test numeric gradient
a_sym = mx.sym.Variable("a").as_np_ndarray()
b_sym = mx.sym.Variable("b").as_np_ndarray()
mx_sym = mx.sym.np.kron(a_sym, b_sym).as_nd_ndarray()
check_numeric_gradient(mx_sym, [a.as_nd_ndarray(), b.as_nd_ndarray()],
rtol=1e-2, atol=1e-2, dtype=dtype)
# test gradient via backward implemented by numpy
np_backward = np_kron_backward(onp.ones(np_out.shape, dtype = dtype), a.asnumpy(), b.asnumpy())
assert_almost_equal(a.grad.asnumpy(), np_backward[0], rtol=1e-2, atol=1e-2)
assert_almost_equal(b.grad.asnumpy(), np_backward[1], rtol=1e-2, atol=1e-2)
@use_np
@pytest.mark.parametrize('shape', [rand_shape_nd(4, dim=4), (4, 0, 4, 0)])
@pytest.mark.parametrize('axis', [0, 1, 2, 3, (), None])
@pytest.mark.parametrize('keepdims', [True, False])
@pytest.mark.parametrize('dtype', ['float16', 'float32', 'float64', 'int8', 'int32', 'int64'])
@pytest.mark.parametrize('itype,acc_type', [
('float16', 'float32'),
('float32', 'float64'),
('float64', 'float64'),
('int8', 'int32'),
('int32', 'int64'),
('int64', 'int64'),
('bool', 'int64')
])
@pytest.mark.parametrize('hybridize', [True, False])
def test_np_sum(shape, axis, keepdims, itype, acc_type, dtype, hybridize):
class TestSum(HybridBlock):
def __init__(self, axis=None, dtype=None, keepdims=False):
super(TestSum, self).__init__()
self._axis = axis
self._dtype = dtype
self._keepdims = keepdims
def forward(self, a, *args, **kwargs):
return np.sum(a, axis=self._axis, dtype=self._dtype, keepdims=self._keepdims)
class TestSumConv(HybridBlock):
def __init__(self, axis=None, dtype=None, keepdims=False):
super(TestSumConv, self).__init__()
self._axis = axis
self._dtype = dtype
self._keepdims = keepdims
def forward(self, a, *args, **kwargs):
return a.sum(axis=self._axis, dtype=self._dtype, keepdims=self._keepdims)
def is_int(dtype):
return 'int' in dtype
is_windows = sys.platform.startswith('win')
if (is_int(dtype) and not is_int(itype)) or (is_windows and is_int(itype))\
or (itype == 'bool' and\
(dtype not in ('float32', 'float64', 'int32', 'int64') or is_windows)):
return
# test gluon
test_sum = TestSum(axis=axis, dtype=dtype, keepdims=keepdims)
test_sum_conv = TestSumConv(axis=axis, dtype=dtype, keepdims=keepdims)
if hybridize:
test_sum.hybridize()
test_sum_conv.hybridize()
if is_int(itype):
x = onp.random.randint(-128, 128, shape, dtype=itype)
x = np.array(x)
elif itype == 'bool':
x = onp.random.randint(0, 2, shape) < 1
x = np.array(x, dtype='bool')
else:
x = np.random.uniform(-1.0, 1.0, size=shape, dtype=itype)
expected_ret = onp.sum(x.asnumpy(), axis=axis, dtype=acc_type, keepdims=keepdims)
expected_ret = expected_ret.astype(dtype)
if itype == 'bool':
if is_op_runnable() and (not is_windows): # special handling of boolean ndarray
y = test_sum(x)
y_conv = test_sum_conv(x)
assert y.dtype == expected_ret.dtype
assert_almost_equal(y.asnumpy(), expected_ret, rtol=1e-4, atol=1e-5,
use_broadcast=False)
assert y_conv.dtype == expected_ret.dtype
assert_almost_equal(y_conv.asnumpy(), expected_ret, rtol=1e-4, atol=1e-5,
use_broadcast=False)
return
x.attach_grad()
with mx.autograd.record():
y = test_sum(x)
y_conv = test_sum_conv(x)
assert y.shape == expected_ret.shape
assert_almost_equal(y.asnumpy(), expected_ret, rtol=1e-3 if dtype == 'float16' else 1e-3,
atol=1e-5 if dtype == 'float16' else 1e-5, use_broadcast=False)
assert y_conv.shape == expected_ret.shape
assert_almost_equal(y_conv.asnumpy(), expected_ret, rtol=1e-3 if dtype == 'float16' else 1e-3,
atol=1e-5 if dtype == 'float16' else 1e-5, use_broadcast=False)
y.backward()
assert same(x.grad.asnumpy(), onp.ones(shape=x.shape, dtype=x.dtype))
# test numeric
if itype == 'float32' and dtype == 'float32' and shape != (4, 0, 4, 0):
x_sym = mx.sym.Variable("x").as_np_ndarray()
mx_sym = mx.sym.np.sum(x_sym, axis=axis, dtype=dtype, keepdims=keepdims).as_nd_ndarray()
check_numeric_gradient(mx_sym, [x.as_nd_ndarray()],
numeric_eps=1e-3, rtol=1e-2, atol=1e-3, dtype=onp.float32)
# test imperative
mx_out = np.sum(x, axis=axis, dtype=dtype, keepdims=keepdims)
np_out = onp.sum(x.asnumpy(), axis=axis, dtype=acc_type, keepdims=keepdims).astype(dtype)
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5, use_broadcast=False)
@use_np
@pytest.mark.parametrize('bool_agg', ['all', 'any'])
@pytest.mark.parametrize('shape', [
(), (5, ), (10, ), (2, 5), (5, 5), (10, 10),
(4, 4, 4), (4, 6, 9), (6, 6, 6), (6, 0, 5),
(7, 8, 9, 10), (7, 9, 11, 13), (0, 7, 7, 5)
])
@pytest.mark.parametrize('axis', [True, False])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('keepdim', [True, False])
@pytest.mark.parametrize('dtype', [np.int8, np.uint8, np.int32, np.int64, np.float16, np.float32, np.float64, np.bool])
def test_np_bool_agg(bool_agg, shape, axis, keepdim, dtype, hybridize):
class TestOp(HybridBlock):
def __init__(self, axis=None, keepdims=False) :
super(TestOp, self).__init__()
self._axis = axis
self._keepdims = keepdims
def forward(self, a):
return getattr(np, bool_agg)(a, axis=self._axis, keepdims=self._keepdims)
ndim = len(shape)
samples = random.randint(0, ndim)
axis = None if not axis else tuple(random.sample([i for i in range(0, ndim)], samples))
x = np.random.normal(0, 5.0, size=shape).astype(dtype)
test_op = TestOp(axis=axis, keepdims=keepdim)
if hybridize:
test_op.hybridize()
y = test_op(x)
expected_ret = getattr(onp, bool_agg)(x.asnumpy(), axis=axis, keepdims=keepdim)
assert_almost_equal(y.asnumpy(), expected_ret)
# test imperative
mx_outs = getattr(np, bool_agg)(x, axis=axis, keepdims=keepdim)
np_outs = getattr(onp, bool_agg)(x.asnumpy(), axis=axis, keepdims=keepdim)
assert_almost_equal(mx_outs.asnumpy(), np_outs)
@use_np
@pytest.mark.parametrize('func', ['max', 'min'])
@pytest.mark.parametrize('in_data_dim', [2, 3, 4])
@pytest.mark.parametrize('itype', ['float16', 'float32', 'float64', 'int'])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('keepdims', [True, False])
def test_np_max_min(func, in_data_dim, itype, keepdims, hybridize):
class TestOp(HybridBlock):
def __init__(self, axis=None, keepdims=False):
super(TestOp, self).__init__()
self._axis = axis
self._keepdims = keepdims
def forward(self, a, *args, **kwargs):
return getattr(a, func)(axis=self._axis, keepdims=self._keepdims)
def is_int(dtype):
return 'int' == dtype
def get_grad(axis, func_name):
index = -1 if func_name == 'max' else 0
if axis == ():
return onp.ones((2,3,4,5))
else:
temp = onp.zeros((2,3,4,5))
if axis == 0:
temp[index,:,:,:] = 1
return temp
elif axis == 1:
temp[:,index,:,:] = 1
return temp
elif axis == 2:
temp[:,:,index,:] = 1
return temp
elif (axis == 3 or axis == -1):
temp[:,:,:,index] = 1
return temp
elif not axis:
temp[index,index,index,index] = 1
return temp
raise ValueError('axis should be int or None or ()')
shape = rand_shape_nd(in_data_dim, dim=3)
for axis in ([i for i in range(in_data_dim)] + [(), None] + [-1]):
test_gluon = TestOp(axis=axis, keepdims=keepdims)
if hybridize:
test_gluon.hybridize()
if is_int(itype):
x = np.arange(120).reshape((2, 3, 4, 5))
else:
x = np.random.uniform(-1.0, 1.0, size=shape, dtype=itype)
x.attach_grad()
ref_op = getattr(onp, 'a'+func)
expected_ret = ref_op(x.asnumpy(), axis=axis, keepdims=keepdims)
with mx.autograd.record():
y = test_gluon(x)
assert y.shape == expected_ret.shape
assert_almost_equal(y.asnumpy(), expected_ret, rtol=1e-3 if itype == 'float16' else 1e-3,
atol=1e-5 if itype == 'float16' else 1e-5)
y.backward()
# only check the gradient with hardcoded input
if is_int(itype):
assert same(x.grad.asnumpy(), get_grad(axis, func)), \
'x={}\ny={}\nx.grad={}\nnumpy={}'.format(x.asnumpy(), y.asnumpy(), x.grad.asnumpy(), get_grad(axis))
# test imperative
mx_out = getattr(np, func)(x, axis=axis, keepdims=keepdims)
np_out = ref_op(x.asnumpy(), axis=axis, keepdims=keepdims)
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
@use_np
@pytest.mark.parametrize('func', ['max', 'min'])
@pytest.mark.parametrize('shape,exception', [
((), False),
((0), True),
((2, 0), True),
((0, 2, 1), True)
])
def test_np_max_min_error(func, shape, exception):
# test zero and zero dim
def _test_np_exception(func, shape, dim):
x = np.random.uniform(-1.0, 1.0, shape)
out = getattr(x, func)()
assert out.ndim == dim, 'dimension mismatch, output.ndim={}, dim={}'.format(output.ndim, dim)
dim = 0
if exception:
assertRaises(MXNetError, _test_np_exception, func, shape, dim)
else:
_test_np_exception(func, shape, dim)
@use_np
@pytest.mark.parametrize('a_shape,w_shape,axes', [
((3, 5), (3, 5), None),
((4, 5, 6), (4, 5, 6), (0, 2)),
((3,), (3,), 0),
((2, 3), (3,), 1),
((2, 3, 4), (2,), 0),
((2, 3, 4), (3,), 1),
((2, 3, 4), (4,), -1),
((2, 3, 4, 5), (5,), 3)
])
@pytest.mark.parametrize('dtype', ['float32', 'float64'])
@pytest.mark.parametrize('hybridize', [True, False])
@pytest.mark.parametrize('is_weighted', [True, False])
@pytest.mark.parametrize('returned', [True, False])
@pytest.mark.parametrize('req_a', ['null', 'add', 'write'])
@pytest.mark.flaky
def test_np_average(a_shape, w_shape, axes, is_weighted, req_a,
hybridize, returned, dtype):
class TestAverage(HybridBlock):
def __init__(self, axis=None, returned=False):
super(TestAverage, self).__init__()
# necessary initializations
self._axis = axis
self._returned = returned
def forward(self, a, weights):
return np.average(a, weights=weights, axis=self._axis, returned=self._returned)
def avg_backward(a, w, avg, axes, init_a_grad=None, init_w_grad=None):
# avg = sum(a * w) / sum(w)
if axes is not None and not isinstance(axes, tuple) and axes < 0:
axes += a.ndim
if w is None:
a_grad = onp.ones(shape=a.shape, dtype=a.dtype)/(a.size/avg.size)
if init_a_grad is not None:
a_grad += init_a_grad.asnumpy()
return [a_grad, None]
onedim = a.ndim != w.ndim
if onedim:
new_shape = [a.shape[i] if i == axes else 1 for i in range(a.ndim)]
w = w.reshape(new_shape)
w = onp.broadcast_to(w, a.shape)
# partial a = w / sum(w)
# partial w = (a*sum(w) - sum(a*w)) / (sum(w) * sum(w))
scl = onp.sum(w, axis=axes, keepdims=True)
a_grad = onp.divide(w, scl)
w_grad = onp.divide(a*scl-onp.sum(a*w, axis=axes, keepdims=True), scl*scl)
if onedim:
axis = list(range(a.ndim))
axis.remove(axes)
w_grad = onp.sum(w_grad, axis=tuple(axis))
if init_a_grad is not None:
a_grad += init_a_grad.asnumpy()
if init_w_grad is not None:
w_grad += init_w_grad.asnumpy()
return [a_grad, w_grad]
if req_a == 'null' and not is_weighted:
return
rtol, atol = 1e-3, 1e-4
test_average = TestAverage(axes, returned)
if hybridize:
test_average.hybridize()
a = np.random.uniform(-1.0, 1.0, size=a_shape, dtype=dtype)
a.attach_grad(req_a)
init_a_grad = np.random.uniform(-1.0, 1.0, size=a_shape, dtype=dtype) if req_a == 'add' else None
init_w_grad = None
req_w = req_a
w, np_w = None, None
if is_weighted:
w = np.random.uniform(-1.0, 1.0, size=w_shape, dtype=dtype)
if req_a == 'null':
req_w = random.choice(['add', 'write'])
w.attach_grad(req_w)
if req_w == 'add':
init_w_grad = np.random.uniform(-1.0, 1.0, size=w_shape, dtype=dtype)
np_w = w.asnumpy()
np_out = onp.average(a.asnumpy(), axis=axes, weights=np_w, returned=returned)
with mx.autograd.record():
mx_out = test_average(a, w)
if returned:
np_out, np_sum_of_weights = np_out
mx_out, mx_sum_of_weights = mx_out
assert_almost_equal(mx_sum_of_weights.asnumpy(), np_sum_of_weights, rtol=rtol, atol=atol)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=rtol, atol=atol)
if req_a == 'add':
a.grad[:] = init_a_grad
if is_weighted and req_w == 'add':
w.grad[:] = init_w_grad
mx_out.backward()
# Code to get reference backward value
a_grad, w_grad = avg_backward(a.asnumpy(), np_w, np_out, axes, init_a_grad, init_w_grad)
if is_weighted:
assert_almost_equal(w.grad.asnumpy(), w_grad, rtol=rtol*10, atol=atol*10)
if req_a == 'null':
assert a.grad is None
else:
assert_almost_equal(a.grad.asnumpy(), a_grad, rtol=rtol, atol=atol)
# Test imperative once again
np_out = onp.average(a.asnumpy(), weights=np_w, axis=axes, returned=returned)
mx_out = np.average(a, weights=w, axis=axes, returned=returned)
if returned:
np_out, np_sum_of_weights = np_out
mx_out, mx_sum_of_weights = mx_out
assert_almost_equal(mx_sum_of_weights.asnumpy(), np_sum_of_weights, rtol=rtol, atol=atol)
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=rtol, atol=atol)
@use_np
def test_np_mean():
class TestMean(HybridBlock):