-
Notifications
You must be signed in to change notification settings - Fork 299
Expand file tree
/
Copy pathtest_node.py
More file actions
4284 lines (3879 loc) · 180 KB
/
test_node.py
File metadata and controls
4284 lines (3879 loc) · 180 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import unittest
from onnx import defs
from onnx import helper
from onnx import TensorProto
from onnx.backend.test.case.node import hardmax
from onnx.backend.test.case.node.onehot import one_hot
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from onnx_tf.backend import onnx_graph_to_tensorflow_rep
from onnx_tf.backend import run_node
from onnx_tf.common import supports_device
from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver
from onnx_tf.common.pooling_helper import py_pool
class TestNode(unittest.TestCase):
""" Tests for nodes
"""
def _get_device_list(self):
# Check does the environment support CUDA.
return ['CPU', 'CUDA'] if supports_device("CUDA") else ['CPU']
def _get_rnd_float32(self, low=-1.0, high=1.0, shape=None):
output = np.random.uniform(low, high, shape)
if shape is None:
return np.float32(output)
else:
return output.astype(np.float32)
def _get_rnd_float16(self, low=-1.0, high=1.0, shape=None):
output = np.random.uniform(low, high, shape)
if shape is None:
return np.float16(output)
else:
return output.astype(np.float16)
def _get_rnd_int(self, low, high=None, shape=None, dtype=np.int32):
return np.random.randint(low, high, size=shape, dtype=dtype)
def _elu(self, x):
# f(x) = alpha * (exp(x) - 1.) for x < 0,
# f(x) = x for x >= 0
if x < 0.:
return np.expm1(x)
return x
def _leaky_relu(self, x, alpha):
# f(x) = alpha * x for x < 0,
# f(x) = x for x >= 0
if x < 0.:
return alpha * x
return x
def test_abs(self):
node_def = helper.make_node("Abs", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[1000])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.abs(x))
def test_acosh(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support Acosh.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("Acosh", ["X"], ["Y"])
x = self._get_rnd_float32(low=1.0,
high=np.finfo(np.float32).max,
shape=[3, 4, 5])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.arccosh(x), decimal=5)
def test_add(self):
node_def = helper.make_node("Add", ["X", "Y"], ["Z"])
x = self._get_rnd_float32(shape=[5, 10, 5, 5])
y = self._get_rnd_float32(shape=[10, 1, 1])
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"],
np.add(x, y.reshape([1, 10, 1, 1])))
# node_def = helper.make_node("Add", ["A", "B"], ["C"], broadcast=1)
# a = self._get_rnd([10, 10])
# b = self._get_rnd([10, 10])
# output = run_node(node_def, [a, b])
# np.testing.assert_almost_equal(output["C"], np.add(a, b))
# node_def = helper.make_node("Add", ["A", "B"], ["C"], broadcast=1)
# a = self._get_rnd([10, 10])
# b = self._get_rnd([10,])
# output = run_node(node_def, [a, b])
# np.testing.assert_almost_equal(output["C"], np.add(a, b))
def test_arg_max(self):
for axis in [0, 1]:
node_def = helper.make_node("ArgMax", ["data"], ["reduced"],
axis=axis,
keepdims=0)
data = self._get_rnd_float32(shape=[10, 10])
output = run_node(node_def, [data])
np.testing.assert_almost_equal(output["reduced"],
np.argmax(data, axis=axis))
# test select_last_index
if not legacy_opset_pre_ver(12):
# select_last_index = 0
node_def = helper.make_node("ArgMax", ["data"], ["reduced"],
axis=axis,
keepdims=0,
select_last_index=0)
data = self._get_rnd_float32(shape=[10, 10])
output = run_node(node_def, [data])
np.testing.assert_almost_equal(output["reduced"],
np.argmax(data, axis=axis))
# select_last_index = 1
node_def = helper.make_node("ArgMax", ["data"], ["reduced"],
axis=axis,
keepdims=0,
select_last_index=1)
data = np.array([[1, 2, 3, 5, 3, 4, 5, 1], [2, 9, 3, 5, 9, 4, 5, 1]])
output = run_node(node_def, [data])
data = np.flip(data, axis)
result = np.argmax(data, axis=axis)
result = data.shape[axis] - result - 1
np.testing.assert_almost_equal(output["reduced"], result)
def test_arg_min(self):
for axis in [0, 1]:
node_def = helper.make_node("ArgMin", ["data"], ["reduced"],
axis=axis,
keepdims=0)
data = self._get_rnd_float32(shape=[10, 10])
output = run_node(node_def, [data])
np.testing.assert_almost_equal(output["reduced"],
np.argmin(data, axis=axis))
# test select_last_index
if not legacy_opset_pre_ver(12):
# select_last_index = 0
node_def = helper.make_node("ArgMin", ["data"], ["reduced"],
axis=axis,
keepdims=0,
select_last_index=0)
data = self._get_rnd_float32(shape=[10, 10])
output = run_node(node_def, [data])
np.testing.assert_almost_equal(output["reduced"],
np.argmin(data, axis=axis))
# select_last_index = 1
node_def = helper.make_node("ArgMin", ["data"], ["reduced"],
axis=axis,
keepdims=0,
select_last_index=1)
data = np.array([[1, 2, 3, 5, 3, 4, 5, 1], [2, 7, 3, 5, 2, 4, 5, 6]])
output = run_node(node_def, [data])
data = np.flip(data, axis)
result = np.argmin(data, axis=axis)
result = data.shape[axis] - result - 1
np.testing.assert_almost_equal(output["reduced"], result)
def test_asinh(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support Asinh.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("Asinh", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[3, 4, 5])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.arcsinh(x))
def test_atanh(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support Atanh.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("Atanh", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[3, 4, 5])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.arctanh(x), decimal=6)
def _batch_normalization(self, x, mean, variance, bias, scale,
variance_epsilon):
inv = np.reciprocal(np.sqrt(variance + variance_epsilon))
if scale is not None:
inv *= scale
return x * inv + (bias - mean * inv if bias is not None else -mean * inv)
def test_batch_normalization(self):
if legacy_opset_pre_ver(6):
raise unittest.SkipTest("Backend doesn't support consumed flag")
node_def = helper.make_node("BatchNormalization",
["X", "scale", "bias", "mean", "var"], ["Y"],
epsilon=0.001)
x_shape = [3, 5, 4, 2]
param_shape = [5]
_param_shape = [1, 5, 1, 1]
x = self._get_rnd_float32(0, 1, shape=x_shape)
m = self._get_rnd_float32(0, 1, shape=param_shape)
_m = m.reshape(_param_shape)
v = self._get_rnd_float32(0, 1, shape=param_shape)
_v = v.reshape(_param_shape)
scale = self._get_rnd_float32(0, 1, shape=param_shape)
_scale = scale.reshape(_param_shape)
bias = self._get_rnd_float32(0, 1, shape=param_shape)
_bias = bias.reshape(_param_shape)
golden = self._batch_normalization(x, _m, _v, _bias, _scale, 0.001)
output = run_node(node_def, [x, scale, bias, m, v])
np.testing.assert_almost_equal(output["Y"], golden, decimal=5)
def _batch_normalization_15(self, x, mean, variance, bias, scale,
variance_epsilon):
inv = np.reciprocal(np.sqrt(variance + variance_epsilon))
if scale is not None:
inv *= scale
return (x * inv + (bias - mean * inv if bias is not None else -mean * inv)).astype(x.dtype)
def test_batch_normalization_15(self):
if legacy_opset_pre_ver(15):
raise unittest.SkipTest("ONNX version {} doesn't support BatchNormalization with different type.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("BatchNormalization",
["X", "scale", "bias", "mean", "var"], ["Y"],
epsilon=0.001)
x_shape = [3, 5, 4, 2]
param_shape = [5]
_param_shape = [1, 5, 1, 1]
x = self._get_rnd_float16(0, 1, shape=x_shape)
m = self._get_rnd_float32(0, 1, shape=param_shape)
_m = m.reshape(_param_shape)
v = self._get_rnd_float32(0, 1, shape=param_shape)
_v = v.reshape(_param_shape)
scale = self._get_rnd_float32(0, 1, shape=param_shape)
_scale = scale.reshape(_param_shape)
bias = self._get_rnd_float32(0, 1, shape=param_shape)
_bias = bias.reshape(_param_shape)
golden = self._batch_normalization_15(x, _m, _v, _bias, _scale, 0.001)
output = run_node(node_def, [x, scale, bias, m, v])
np.testing.assert_almost_equal(output["Y"], golden, decimal=1)
def test_cast(self):
if legacy_onnx_pre_ver(1, 2) or legacy_opset_pre_ver(6):
test_cases = [("FLOAT", tf.float32), ("UINT8", tf.uint8),
("INT8", tf.int8),
("UINT16", tf.uint16), ("INT16", tf.int16),
("INT32", tf.int32), ("INT64", tf.int64), ("BOOL", tf.bool),
("FLOAT16", tf.float16), ("DOUBLE", tf.float64),
("COMPLEX64", tf.complex64), ("COMPLEX128", tf.complex128)]
else:
test_cases = [(TensorProto.FLOAT, tf.float32),
(TensorProto.UINT8, tf.uint8), (TensorProto.INT8, tf.int8),
(TensorProto.UINT16, tf.uint16),
(TensorProto.INT16, tf.int16),
(TensorProto.INT32, tf.int32),
(TensorProto.INT64, tf.int64), (TensorProto.BOOL, tf.bool),
(TensorProto.FLOAT16, tf.float16),
(TensorProto.DOUBLE, tf.float64),
(TensorProto.COMPLEX64, tf.complex64),
(TensorProto.COMPLEX128, tf.complex128)]
if not legacy_opset_pre_ver(9):
test_cases.append((TensorProto.STRING, tf.string))
# added casting to bfloat16 from number in opset 13
if not legacy_opset_pre_ver(13):
test_cases.append((TensorProto.BFLOAT16, tf.bfloat16))
for ty, tf_type in test_cases:
node_def = helper.make_node("Cast", ["input"], ["output"], to=ty)
vector = np.array([2, 3])
output = run_node(node_def, [vector])
np.testing.assert_equal(output["output"].dtype, tf_type)
if not legacy_opset_pre_ver(9):
# test_cases2 is focused on Strings to Numbers
# Note: casting from string to bfloat16 is not allowed by tf.strings.to_number
# so no BFLOAT16 in test_cases2.
test_cases2 = [(TensorProto.FLOAT, tf.float32),
(TensorProto.INT32, tf.int32),
(TensorProto.INT64, tf.int64),
(TensorProto.DOUBLE, tf.float64)]
for ty, tf_type in test_cases2:
node_def = helper.make_node("Cast", ["input"], ["output"], to=ty)
vector = np.array(['2', '3'])
output = run_node(node_def, [vector])
np.testing.assert_equal(output["output"].dtype, tf_type)
if not legacy_opset_pre_ver(9):
# test_case3 is focused on Strings to float and the special floating-point values.
test_cases3 = [(TensorProto.FLOAT, tf.float32),
(TensorProto.DOUBLE, tf.float64)]
for ty, tf_type in test_cases3:
node_def = helper.make_node("Cast", ["input"], ["output"], to=ty)
vector = np.array(['3.14159', '1e-5', '1E8', 'NaN', '-INF', '+INF'])
output = run_node(node_def, [vector])
np.testing.assert_equal(output["output"].dtype, tf_type)
def test_ceil(self):
node_def = helper.make_node("Ceil", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[1000])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.ceil(x))
def test_celu(self):
if legacy_opset_pre_ver(12):
raise unittest.SkipTest("ONNX version {} doesn't support Celu.".format(
defs.onnx_opset_version()))
alpha = 2.0
node_def = helper.make_node("Celu", ["X"], ["Y"], alpha=alpha)
x = np.array([[[-1.0763247, 0.98948643, 0.22292195],
[0.1751388, -1.39814249, 1.44396422]]],
dtype=np.float32)
output = run_node(node_def, [x])
positive_input = np.maximum(0, x)
negative_input = np.minimum(0, alpha * (np.exp(x / alpha) - 1))
expected_output = positive_input + negative_input
np.testing.assert_almost_equal(output["Y"], expected_output)
def test_compress(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest(
"ONNX version {} doesn't support Compress.".format(
defs.onnx_opset_version()))
axis = 1
node_def = helper.make_node("Compress",
inputs=['X', 'condition'],
outputs=['Y'],
axis=axis)
x = self._get_rnd_float32(shape=[5, 5, 5])
cond = np.array([1, 0, 1])
output = run_node(node_def, inputs=[x, cond])
np.testing.assert_almost_equal(output['Y'], np.compress(cond, x, axis=axis))
def test_concat(self):
shape = [10, 20, 5]
for axis in range(len(shape)):
node_def = helper.make_node("Concat", ["X1", "X2"], ["Y"], axis=axis)
x1 = self._get_rnd_float32(shape=shape)
x2 = self._get_rnd_float32(shape=shape)
output = run_node(node_def, [x1, x2])
np.testing.assert_almost_equal(output["Y"], np.concatenate((x1, x2),
axis))
def test_constant(self):
shape = [16, 16]
values = np.random.randn(*shape).flatten().astype(float)
const2_onnx = helper.make_tensor("const2", TensorProto.DOUBLE, shape,
values)
node_def = helper.make_node("Constant", [], ["Y"], value=const2_onnx)
output = run_node(node_def, [])
np.testing.assert_equal(output["Y"].shape, shape)
np.testing.assert_almost_equal(output["Y"].flatten(), values)
# test sparse tensor
if not legacy_opset_pre_ver(11):
expected = np.array([[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]])
x = np.array([[0, 0], [1, 2]]).flatten().astype(np.int64)
values = helper.make_tensor("values", TensorProto.INT32, [2], [1, 2])
indices = helper.make_tensor("indices", TensorProto.INT64, [2, 2], x)
a = helper.make_sparse_tensor(values, indices, [3, 4])
node_def = helper.make_node("Constant", [], ["Y"], sparse_value=a)
output = run_node(node_def, [])
b = tf.sparse.SparseTensor(output["Y"].indices, output["Y"].values,
output["Y"].dense_shape)
b = tf.sparse.to_dense(b)
result = b.numpy()
np.testing.assert_equal(result, expected)
if not legacy_opset_pre_ver(12):
float_attr = 1.0
floats_attr = [1.0, 2.0, 3.0]
int_attr = np.int64(123)
ints_attr = [np.int64(4), np.int64(5), np.int64(6)]
string_attr = 'The Cat in the Hat'
strings_attr = [
'Green Eggs and Ham', 'How the Grinch Stole Christmas!',
'The Cat in the Hat Comes Back'
]
testcases = [(helper.make_node("Constant", [], ["Y"],
value_float=float_attr), float_attr),
(helper.make_node("Constant", [], ["Y"],
value_floats=floats_attr), floats_attr),
(helper.make_node("Constant", [], ["Y"],
value_int=int_attr), int_attr),
(helper.make_node("Constant", [], ["Y"],
value_ints=ints_attr), ints_attr),
(helper.make_node("Constant", [], ["Y"],
value_string=string_attr), string_attr),
(helper.make_node("Constant", [], ["Y"],
value_strings=strings_attr), strings_attr)]
for node_def, expected in testcases:
output = run_node(node_def, [])
if isinstance(expected, str):
np.testing.assert_string_equal(output["Y"].decode('UTF-8'), expected)
elif isinstance(expected, list) and isinstance(expected[0], str):
for i in range(len(expected)):
np.testing.assert_string_equal(output['Y'][i].decode('UTF-8'),
expected[i])
else:
np.testing.assert_equal(output["Y"], expected)
def test_constant_fill(self):
if not legacy_opset_pre_ver(9):
raise unittest.SkipTest(
"ONNX version {} doesn't support ConstantFill.".format(
defs.onnx_opset_version()))
shape = [1, 2, 3, 4]
extra_shape = [5, 6]
value = 3.
node_def = helper.make_node(
"ConstantFill",
["X"],
["Y"],
value=value,
extra_shape=extra_shape,
dtype=1,
)
x = self._get_rnd_float32(shape=shape)
y = np.zeros(shape + extra_shape)
y.fill(value)
output = run_node(node_def, [x])
np.testing.assert_equal(output["Y"].dtype, tf.float32)
np.testing.assert_equal(output["Y"], y)
def test_constant_of_shape(self):
if defs.onnx_opset_version() < 9:
raise unittest.SkipTest(
"ONNX version {} doesn't support ConstantOfShape.".format(
defs.onnx_opset_version()))
v = helper.make_tensor("value", TensorProto.FLOAT, [1], [1])
node_def = helper.make_node("ConstantOfShape", ["X"], ["Y"], value=v)
x = np.array([4, 3, 2])
output = run_node(node_def, inputs=[x])
np.testing.assert_almost_equal(output["Y"], np.ones(x, dtype=np.float32))
v = helper.make_tensor("value", TensorProto.INT32, [1], [0])
node_def = helper.make_node("ConstantOfShape", ["X"], ["Y"], value=v)
x = np.array([10, 6])
output = run_node(node_def, inputs=[x])
np.testing.assert_almost_equal(output["Y"], np.zeros(x, dtype=np.int32))
def test_conv(self):
for device in self._get_device_list():
N, C, H, W = 4, 3, 5, 5
x_shape = [N, C, H, W]
K, kH, kW = 6, 3, 3
weight_shape = [K, C, kH, kW]
node_def = helper.make_node("Conv", ["X", "weights"], ["Y"],
pads=[1, 1, 1, 1],
kernel_shape=[kH, kW])
x = self._get_rnd_float32(shape=x_shape)
weights = self._get_rnd_float32(shape=weight_shape)
output = run_node(node_def, [x, weights], device=device)
out_shape = [N, K, H, W]
test_output = np.zeros(out_shape)
for n in range(N):
for c in range(C):
for h in range(H):
for w in range(W):
for k in range(K):
for kh in range(kH):
for kw in range(kW):
h_in_range = (h - kH // 2 + kh) < H and (h - kH // 2 +
kh) >= 0
w_in_range = (w - kW // 2 + kw) < W and (w - kW // 2 +
kw) >= 0
if h_in_range and w_in_range:
test_output[n][k][h][w] += (
x[n][c][h - kH // 2 + kh][w - kW // 2 + kw] *
weights[k][c][kh][kw])
np.testing.assert_almost_equal(output["Y"], test_output, decimal=4)
def test_conv_integer(self):
if legacy_opset_pre_ver(10):
raise unittest.SkipTest(
"ONNX version {} doesn't support ConvInteger.".format(
defs.onnx_opset_version()))
for device in self._get_device_list():
# Test w_zero_point
x = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int8).reshape(
(1, 1, 3, 3))
w = np.array([2, 2, 2, 2]).astype(np.int8).reshape((1, 1, 2, 2))
w_zero_point = np.int8(1)
y = np.array([16, 20, 28, 32]).astype(np.int32).reshape((1, 1, 2, 2))
node = helper.make_node("ConvInteger",
["X", "W", "x_zero_point", "w_zero_point"], ["Y"],
kernel_shape=[2, 2],
pads=[0, 0, 0, 0],
dilations=[1, 1])
output = run_node(node, [x, w, np.int8(0), w_zero_point], device=device)
np.testing.assert_almost_equal(output["Y"], y)
# Test x_zero_point and w_zero_point
x = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int8).reshape(
(1, 1, 3, 3))
x_zero_point = np.int8(1)
w = np.array([2, 2, 2, 2]).astype(np.int8).reshape((1, 1, 2, 2))
w_zero_point = np.int8(1)
y = np.array([12, 16, 24, 28]).astype(np.int32).reshape((1, 1, 2, 2))
node = helper.make_node("ConvInteger",
["X", "W", "x_zero_point", "w_zero_point"], ["Y"],
kernel_shape=[2, 2],
pads=[0, 0, 0, 0],
dilations=[1, 1])
output = run_node(node, [x, w, x_zero_point, w_zero_point], device=device)
np.testing.assert_almost_equal(output["Y"], y)
# Test w_zero_point as 1d tensor
x = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int8).reshape(
(1, 1, 3, 3))
w = np.array([2, 2, 2, 2]).astype(np.int8).reshape((1, 1, 2, 2))
w_zero_point = np.array([1]).astype(np.int8)
y = np.array([16, 20, 28, 32]).astype(np.int32).reshape((1, 1, 2, 2))
node = helper.make_node("ConvInteger",
["X", "W", "x_zero_point", "w_zero_point"], ["Y"],
kernel_shape=[2, 2],
pads=[0, 0, 0, 0],
dilations=[1, 1])
output = run_node(node, [x, w, np.int8(0), w_zero_point], device=device)
np.testing.assert_almost_equal(output["Y"], y)
# Test w_zero_point as 1d tensor shape 2
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).astype(np.int8).reshape(
(1, 1, 3, 3))
w = np.array([2, 2, 2, 2, 2, 2, 2, 2]).astype(np.int8).reshape(
(2, 1, 2, 2))
w_zero_point = np.array([1, 2]).astype(np.int8)
y = np.array([12, 16, 24, 28, 0, 0, 0, 0]).astype(np.int32).reshape(
(1, 2, 2, 2))
node = helper.make_node("ConvInteger",
["X", "W", "x_zero_point", "w_zero_point"], ["Y"],
kernel_shape=[2, 2],
pads=[0, 0, 0, 0],
dilations=[1, 1])
output = run_node(node, [x, w, np.int8(0), w_zero_point], device=device)
np.testing.assert_almost_equal(output["Y"], y)
def test_conv_transpose(self):
for device in self._get_device_list():
pads = [1, 1]
node_def = helper.make_node("ConvTranspose", ["X", "weights"], ["Y"],
pads=pads)
x_shape = [1, 3, 4]
x = self._get_rnd_float32(shape=x_shape)
weight_shape = [3, 5, 2]
weights = self._get_rnd_float32(shape=weight_shape)
output = run_node(node_def, [x, weights], device=device)
padh_left = weight_shape[2] - 1 - pads[0]
padh_right = weight_shape[2] - 1 - pads[1]
kh = weight_shape[2]
outh = x_shape[2] + padh_right + padh_right - (kh - 1)
out_shape = [x_shape[0], weight_shape[1], outh]
test_output = np.zeros(out_shape)
for b in range(0, x_shape[0]):
for m in range(0, weight_shape[1]):
for c in range(0, x_shape[1]):
for h in range(0, outh):
for k in range(h, h + kh):
if (k - padh_left >= 0):
test_output[b][m][h] += x[b][c][
k - padh_left] * weights[c][m][kh + h - 1 - k]
np.testing.assert_almost_equal(output["Y"], test_output, decimal=5)
# test for spatial dimension of colnolution is 2
pads = [1, 1, 1, 1]
node_def = helper.make_node("ConvTranspose", ["X", "weights"], ["Y"],
pads=pads)
x_shape = [1, 3, 4, 6]
x = self._get_rnd_float32(shape=x_shape)
weight_shape = [3, 5, 2, 2]
weights = self._get_rnd_float32(shape=weight_shape)
output = run_node(node_def, [x, weights], device=device)
padh_left = weight_shape[2] - 1 - pads[0]
padh_right = weight_shape[2] - 1 - pads[1]
padw_left = weight_shape[3] - 1 - pads[2]
padw_right = weight_shape[3] - 1 - pads[3]
kh = weight_shape[2]
kw = weight_shape[3]
outh = x_shape[2] + padh_right + padh_right - (kh - 1)
outw = x_shape[3] + padw_right + padw_right - (kw - 1)
out_shape = [x_shape[0], weight_shape[1], outh, outw]
test_output = np.zeros(out_shape)
for b in range(0, x_shape[0]):
for m in range(0, weight_shape[1]):
for c in range(0, x_shape[1]):
for h in range(0, outh):
for w in range(0, outw):
for k1 in range(h, h + kh):
for k2 in range(w, w + kw):
if (k1 - padh_left >= 0 and k2 - padw_left >= 0):
test_output[b][m][h][w] += x[b][c][k1 - padh_left][
k2 - padw_left] * weights[c][m][kh + h - 1 -
k1][kw + w - 1 - k2]
np.testing.assert_almost_equal(output["Y"], test_output, decimal=5)
def test_cosh(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support Cosh.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("Cosh", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[3, 4, 5])
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.cosh(x),decimal=5)
def test_cumsum(self):
if legacy_opset_pre_ver(11):
raise unittest.SkipTest("ONNX version {} doesn't support CumSum.".format(
defs.onnx_opset_version()))
x = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32)
axis = 0
node_def = helper.make_node("CumSum", ["x", "axis"], ["y"])
# note: if axis is not provided, np.cumsum() will compute over flattened array,
# which is different than the TensorFlow behavior
y = np.cumsum(x, axis).astype(np.int32)
output = run_node(node_def, [x, axis])
np.testing.assert_almost_equal(output["y"], y)
# test data types that are not natively supported by Tensorflow
x = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.uint32)
y = np.cumsum(x, axis).astype(np.uint32)
output = run_node(node_def, [x, axis])
np.testing.assert_almost_equal(output["y"], y)
def test_depth_to_space(self):
for device in self._get_device_list():
node_def = helper.make_node("DepthToSpace", ["X"], ["Y"], blocksize=2)
x_shape = [1, 12, 1, 1]
x = self._get_rnd_float32(shape=x_shape)
output = run_node(node_def, [x], device=device)
x = np.transpose(x, (0, 2, 3, 1))
y = np.reshape(np.swapaxes(x.reshape(1, 1, 1, 2, 2, 3), 2, 3),
(1, 2, 2, 3))
y = np.transpose(y, (0, 3, 1, 2))
np.testing.assert_almost_equal(output["Y"], y, decimal=5)
def test_dequantize_linear(self):
node_def = helper.make_node("DequantizeLinear",
["x", "x_scale", "x_zero_point"], ["y"])
for x, x_zero_point in [[
self._get_rnd_int(-128, 127, [2, 6], np.int8),
self._get_rnd_int(-128, 127, dtype=np.int8)
],
[
self._get_rnd_int(0, 255, [2, 6], np.uint8),
self._get_rnd_int(0, 255, dtype=np.uint8)
],
[self._get_rnd_int(-512, 512, [2, 6]),
np.int32(0)]]:
x_scale = self._get_rnd_float32(-10., 10)
y = np.subtract(np.float32(x), np.float32(x_zero_point))
y = np.multiply(y, x_scale)
output = run_node(node_def, [x, x_scale, x_zero_point])
np.testing.assert_almost_equal(output["y"], y)
def test_div(self):
node_def = helper.make_node("Div", ["X", "Y"], ["Z"])
x = self._get_rnd_float32(shape=[10, 10])
y = self._get_rnd_float32(shape=[10, 10])
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], np.divide(x, y))
def test_dropout(self):
# Since current ONNX only support inference and
# dropout at inference mode is a no-op,
# therefore dropout is always a no-op operator
# in ONNX. This has changed in Opset 12. In Opset
# 12 ONNX has added support for training.
x = self._get_rnd_float32(shape=[3, 4, 5])
if legacy_opset_pre_ver(7):
# at inference mode, is_test attribute is always set to 1
node_def = helper.make_node("Dropout", ["X"], ["Y"], is_test=1)
y = x # output is same is input i.e. nothing is dropped
output = run_node(node_def, [x])
np.testing.assert_equal(output["Y"], y)
elif legacy_opset_pre_ver(12): # for Opset 7, 10
# no is_test attribute anymore
node_def = helper.make_node("Dropout", ["X"], ["Y"])
y = x # output is same is input i.e. nothing is dropped
output = run_node(node_def, [x])
np.testing.assert_equal(output["Y"], y)
else: # for Opset 12, 13
# Inference mode tests
# training_mode is false by default
# ratio is ignored
# nothing will be dropped from the input data
# if mask is requested as output it will contain all ones
# Inference, mask not requested
node_def = helper.make_node("Dropout", ["X"], ["Y"])
y = x # output is same is input i.e. nothing is dropped
output = run_node(node_def, [x])
np.testing.assert_equal(output["Y"], y)
# Inference, mask requested
node_def = helper.make_node("Dropout", inputs=["X"], outputs=["Y", "Z"])
y = x # output is same is input i.e. nothing is dropped
z = np.ones(x.shape, dtype=bool) # mask returned is all ones
output = run_node(node_def, [x])
np.testing.assert_equal(output["Y"], y)
np.testing.assert_equal(output["Z"], z)
# Training mode tests
# training_mode is true
# output is a random dropout that scales masked
# input using the following equation
# output = scale * data * mask
# scale = 1. / (1. - ratio)
ratio = np.float32(0.5)
training_mode = np.bool_(True)
no_of_runs = 20 # run 20 times and make sure that on average we have the desired dropout
# Training, mask not requested
node_def = helper.make_node("Dropout",
inputs=["X", "X1", "X2"],
outputs=["Y"])
sum_ratio_in_output = 0
for _ in range(no_of_runs):
output = run_node(node_def, [x, ratio, training_mode])
output_nonzero_count = np.count_nonzero(output["Y"])
output_size = output["Y"].size
ratio_in_output = (output_size - output_nonzero_count) / output_size
sum_ratio_in_output += ratio_in_output
ratio_in_output = sum_ratio_in_output / no_of_runs
# test by confirming that the dropout is close to the ratio passed in
np.testing.assert_almost_equal(ratio_in_output, ratio, decimal=1)
# Training, mask requested
node_def = helper.make_node("Dropout",
inputs=["X", "X1", "X2"],
outputs=["Y", "Z"])
sum_ratio_in_output = 0
for _ in range(no_of_runs):
output = run_node(node_def, [x, ratio, training_mode])
output_nonzero_count = np.count_nonzero(output["Y"])
output_size = output["Y"].size
ratio_in_output = (output_size - output_nonzero_count) / output_size
sum_ratio_in_output += ratio_in_output
ratio_in_output = sum_ratio_in_output / no_of_runs
# test by confirming that the dropout is close to the ratio passed in
np.testing.assert_almost_equal(ratio_in_output, ratio, decimal=1)
# test mask
np.testing.assert_equal(output["Z"], output["Y"].astype(bool))
def test_dot(self):
# this op is removed
# remove this test in the future
return
node_def = helper.make_node("Dot", ["X", "Y"], ["Z"])
x = np.floor(self._get_rnd_float32(shape=[10, 10]))
y = np.floor(self._get_rnd_float32(shape=[10, 10]))
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], np.dot(x, y))
def test_dynamic_quantize_linear(self):
if legacy_opset_pre_ver(11):
raise unittest.SkipTest(
"ONNX version {} doesn't support DynamicQuantizeLinear.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("DynamicQuantizeLinear", ["X"],
["Y", "Y_Scale", "Y_Zero_Point"])
x = self._get_rnd_float32(shape=[3, 4])
min_x = np.minimum(0, np.min(x))
max_x = np.maximum(0, np.max(x))
y_scale = np.float32((max_x - min_x) / (255 - 0)) # uint8 -> [0, 255]
y_zero_point = np.clip(round((0 - min_x) / y_scale), 0,
255).astype(np.uint8)
y = np.clip(np.round(x / y_scale) + y_zero_point, 0, 255).astype(np.uint8)
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], y)
np.testing.assert_almost_equal(output["Y_Scale"], y_scale)
np.testing.assert_almost_equal(output["Y_Zero_Point"], y_zero_point)
def test_einsum(self):
if legacy_opset_pre_ver(12):
raise unittest.SkipTest("ONNX version {} doesn't support Einsum.".format(
defs.onnx_opset_version()))
equation = 'ij,jk->ik' #matmul
node_def = helper.make_node("Einsum", ["X", "Y"], ["Z"], equation=equation)
x = self._get_rnd_float32(shape=[3, 4])
y = self._get_rnd_float32(shape=[4, 5])
z = np.einsum(equation, x, y)
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], z)
def test_elu(self):
node_def = helper.make_node("Elu", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[100])
output = run_node(node_def, [x])
test_output = [self._elu(a) for a in x]
np.testing.assert_almost_equal(output["Y"], test_output)
def test_equal(self):
node_def = helper.make_node("Equal", ["X", "Y"], ["Z"])
x = self._get_rnd_float32(shape=[5, 3, 3, 2])
y = self._get_rnd_float32(shape=[3, 3, 1])
output = run_node(node_def, [x, y])
np.testing.assert_equal(output["Z"], np.equal(x,
np.reshape(y, [1, 3, 3, 1])))
# test data types that are not natively supported by Tensorflow
x = np.arange(8).reshape((2, 2, 2)).astype(np.uint16)
y = np.arange(8).reshape((2, 2, 2)).astype(np.uint16)
output = run_node(node_def, [x, y])
np.testing.assert_equal(output["Z"], np.equal(x, y))
x = np.arange(8).reshape((2, 2, 2)).astype(np.uint64)
y = np.arange(8).reshape((2, 2, 2)).astype(np.uint64)
self.assertRaises(RuntimeError, run_node, node_def, [x, y])
def test_erf(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support Erf.".format(
defs.onnx_opset_version()))
node_def = helper.make_node("Erf", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[3, 4, 5])
output = run_node(node_def, [x])
exp_output = np.vectorize(math.erf)(x).astype(np.float32)
np.testing.assert_allclose(output['Y'], exp_output, rtol=1e-6, atol=1e-6)
def test_exp(self):
node_def = helper.make_node("Exp", ["X"], ["Y"])
x = self._get_rnd_float32(shape=[100])
x = x - 3.6
output = run_node(node_def, [x])
np.testing.assert_almost_equal(output["Y"], np.exp(x))
def test_expand(self):
node_def = helper.make_node("Expand", ["X", "shape"], ["Y"])
x = np.array([[True], [False], [True]])
shape = [2, 1, 6]
y = x * np.ones(shape, dtype=bool)
output = run_node(node_def, [x, shape])
np.testing.assert_almost_equal(output["Y"], y)
def test_eye_like(self):
if legacy_opset_pre_ver(9):
raise unittest.SkipTest("ONNX version {} doesn't support EyeLike.".format(
defs.onnx_opset_version()))
for shape in [[6, 10], [10, 6]]:
for off_diagonal_offset in [-10, -6, -3, 0, 3, 6, 7, 10]:
node_def = helper.make_node("EyeLike", ['x'], ['y'],
dtype=1,
k=off_diagonal_offset)
x = self._get_rnd_int(0, 100, shape=shape)
y = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32)
output = run_node(node_def, [x])
np.testing.assert_equal(output['y'], y)
def test_flatten(self):
shape = [10, 2, 3, 4, 5]
x = self._get_rnd_float32(shape=shape)
for axis in range(-len(shape), len(shape)):
node_def = helper.make_node("Flatten", ["X"], ["Y"], axis=axis)
output = run_node(node_def, [x])
if axis == 0:
new_shape = (1, -1)
else:
new_shape = (np.prod(shape[0:axis]).astype(int), -1)
np.testing.assert_almost_equal(output["Y"], np.reshape(x, new_shape))
def test_gather(self):
node_def = helper.make_node("Gather", ["X", "Y"], ["Z"])
x = self._get_rnd_float32(shape=[10, 10])
y = np.array([[0, 1], [1, 2]])
output = run_node(node_def, [x, y])
test_output = np.zeros((2, 2, 10))
for i in range(0, 2):
for j in range(0, 10):
test_output[0][i][j] = x[i][j]
for i in range(0, 2):
for j in range(0, 10):
test_output[1][i][j] = x[i + 1][j]
np.testing.assert_almost_equal(output["Z"], test_output)
if defs.onnx_opset_version() >= 11:
# test negative indices
y = np.array([[-10, -9], [1, -8]])
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], test_output)
# test out of bound indices
for y in (np.array([[-10, 11], [1, -8]]), np.array([[-10, -11], [1, -8]])):
try:
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], test_output)
raise AssertionError("Expected ValueError not raised for indices %d" %
str(y))
except tf.errors.InvalidArgumentError as e:
assert 'Gather indices are out of bound' in str(e), str(y)
# test non-0 and negative axis
axis = -3
node_def = helper.make_node("Gather", ["X", "Y"], ["Z"], axis=axis)
x = np.reshape(np.arange(5 * 4 * 3 * 2), (5, 4, 3, 2))
y = np.array([0, 1, 3])
test_output = np.take(x, y, axis=axis)
output = run_node(node_def, [x, y])
np.testing.assert_almost_equal(output["Z"], test_output)
# test axis attribute validation
for axis in [-5, 4, 10]:
try:
node_def = helper.make_node("Gather", ["X", "Y"], ["Z"], axis=axis)
run_node(node_def, [x, y])
raise AssertionError(
"Expected ValueError not raised for axis value %d" % axis)
except ValueError as e:
assert 'out of bounds' in str(e), str(e) + ' for axis ' + str(axis)
def test_gather_elements(self):
if legacy_opset_pre_ver(11):
raise unittest.SkipTest(
"ONNX version {} doesn't support GatherElements.".format(
defs.onnx_opset_version()))
data_dtype = np.int32
data = np.array([
[[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]],
],
dtype=data_dtype)
# test default axis
indices = np.array([[[3, 0], [2, 0], [1, 0], [0, 0], [3, 1]]],
dtype=np.int64)
ref_output = np.array([[[40, 11], [32, 13], [24, 15], [16, 17], [48, 29]]],
dtype=data_dtype)
node_def = helper.make_node("GatherElements", ["data", "indices"],
["outputs"])
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
# test non-default axis
indices = np.array([[[3, 0], [2, 1], [1, 2], [0, 3]]], dtype=data_dtype)
ref_output = np.array([
[[16, 11], [14, 13], [12, 15], [10, 17]],
],
dtype=data_dtype)
node_def = helper.make_node("GatherElements", ["data", "indices"],
["outputs"],
axis=1)
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
# test negative axis
indices = np.array([
[[1, 1, -2], [1, -2, 1], [-1, 1, -1], [-2, 1, -2], [-2, 1, 1]],
],
dtype=data_dtype)
ref_output = np.array([
[[11, 11, 10], [13, 12, 13], [15, 15, 15], [16, 17, 16], [18, 19, 19]],
],
dtype=data_dtype)
node_def = helper.make_node("GatherElements", ["data", "indices"],
["outputs"],
axis=2)
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
def test_gather_nd(self):
if legacy_opset_pre_ver(11):
raise unittest.SkipTest(
"ONNX version {} doesn't support GatherND.".format(
defs.onnx_opset_version()))
# valid positive and negative indices for elements
data = np.array([[0, 1], [2, 3]], dtype=np.int64)
indices = np.array([[0, 0], [1, 1], [-1, -2]], dtype=np.int64)
ref_output = np.array([0, 3, 2], dtype=np.int64)
node_def = helper.make_node("GatherND", ["data", "indices"], ["outputs"])
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
# valid positive and negative indices for slices
data = np.arange(16, dtype=np.int32).reshape([2, 2, 4])
indices = np.array([[0, 0], [-1, -2]], dtype=np.int64)
ref_output = np.array([[0, 1, 2, 3], [8, 9, 10, 11]], dtype=np.int32)
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
indices = np.array([[[0, 0]], [[-1, 0]]], dtype=np.int64)
ref_output = np.array([[[0, 1, 2, 3]], [[8, 9, 10, 11]]], dtype=np.int32)
output = run_node(node_def, [data, indices])
np.testing.assert_almost_equal(output["outputs"], ref_output)
# indices out of bounds
indices = np.array([[5, 0], [-1, -3]], dtype=np.int64)
self.assertRaises(tf.errors.InvalidArgumentError, run_node, node_def,