-
Notifications
You must be signed in to change notification settings - Fork 438
/
Copy pathtest_backend.py
executable file
·6378 lines (5667 loc) · 302 KB
/
test_backend.py
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
# SPDX-License-Identifier: Apache-2.0
"""Unit tests using onnx backends."""
import os
import unittest
from itertools import product
import numpy as np
from numpy.testing import assert_almost_equal
from packaging.version import Version
import tensorflow as tf
from tensorflow.python.ops import lookup_ops
from backend_test_base import Tf2OnnxBackendTestBase
# pylint reports unused-wildcard-import which is false positive, __all__ is defined in common
from common import * # pylint: disable=wildcard-import,unused-wildcard-import
from tf2onnx import constants, utils
from tf2onnx.graph_matcher import OpTypePattern, GraphMatcher
from tf2onnx.tf_loader import is_tf2, tf_placeholder_with_default, tf_placeholder
from tf2onnx.onnx_opset.signal import make_dft_constant
# pylint: disable=missing-docstring,invalid-name,unused-argument,function-redefined,cell-var-from-loop
NCHW_TO_NHWC = [0, 2, 3, 1]
NHWC_TO_NCHW = [0, 3, 1, 2]
HWCN_TO_NCHW = [3, 2, 0, 1]
_STRIDE1x1 = [1, 1, 1, 1]
_KERNEL3x3 = [3, 3, 1, 1]
_DILATIONS1x1 = [1, 1, 1, 1]
# names for input and outputs for tests
_TFINPUT = "input"
_INPUT = "input:0"
_TFINPUT1 = "input1"
_INPUT1 = "input1:0"
_TFINPUT2 = "input2"
_INPUT2 = "input2:0"
_TFINPUT3 = "input3"
_INPUT3 = "input3:0"
_TFOUTPUT = "output"
_OUTPUT = "output:0"
_TFOUTPUT1 = "output1"
_OUTPUT1 = "output1:0"
_TFOUTPUT2 = "output2"
_OUTPUT2 = "output2:0"
_TFOUTPUT3 = "output3"
_OUTPUT3 = "output3:0"
if is_tf2():
conv2d_backprop_input = tf.compat.v1.nn.conv2d_backprop_input
conv3d_transpose = tf.compat.v1.nn.conv3d_transpose
multinomial = tf.compat.v1.random.multinomial
space_to_batch_nd = tf.compat.v1.space_to_batch_nd
batch_to_space_nd = tf.compat.v1.batch_to_space_nd
reverse_v2 = tf.compat.v1.reverse_v2
random_normal = tf.compat.v1.random_normal
random_uniform = tf.compat.v1.random_uniform
fused_batch_norm = tf.compat.v1.nn.fused_batch_norm
dropout = tf.compat.v1.nn.dropout
resize_nearest_neighbor = tf.compat.v1.image.resize_nearest_neighbor
quantize_and_dequantize = tf.quantization.quantize_and_dequantize
resize_bilinear = tf.compat.v1.image.resize_bilinear
resize_bilinear_v2 = tf.compat.v2.image.resize
resize_area = tf.compat.v1.image.resize_area
is_nan = tf.math.is_nan
is_inf = tf.math.is_inf
floormod = tf.math.floormod
matrix_diag_part = tf.compat.v1.matrix_diag_part
fake_quant_with_min_max_args = tf.quantization.fake_quant_with_min_max_args
fake_quant_with_min_max_vars = tf.quantization.fake_quant_with_min_max_vars
elif Version(tf.__version__) >= Version("1.13"):
conv2d_backprop_input = tf.compat.v1.nn.conv2d_backprop_input
conv3d_transpose = tf.compat.v1.nn.conv3d_transpose
multinomial = tf.compat.v1.random.multinomial
space_to_batch_nd = tf.compat.v1.space_to_batch_nd
batch_to_space_nd = tf.compat.v1.batch_to_space_nd
reverse_v2 = tf.compat.v1.reverse_v2
random_normal = tf.compat.v1.random_normal
random_uniform = tf.compat.v1.random_uniform
fused_batch_norm = tf.compat.v1.nn.fused_batch_norm
dropout = tf.compat.v1.nn.dropout
quantize_and_dequantize = tf.compat.v1.quantization.quantize_and_dequantize
resize_area = tf.compat.v1.image.resize_area
resize_nearest_neighbor = tf.compat.v1.image.resize_nearest_neighbor
resize_bilinear = tf.compat.v1.image.resize_bilinear
if Version(tf.__version__) >= Version("1.14"):
resize_bilinear_v2 = tf.compat.v2.image.resize
is_nan = tf.math.is_nan
is_inf = tf.math.is_inf
floormod = tf.floormod
matrix_diag_part = tf.compat.v1.matrix_diag_part
fake_quant_with_min_max_args = tf.compat.v1.quantization.fake_quant_with_min_max_args
fake_quant_with_min_max_vars = tf.compat.v1.quantization.fake_quant_with_min_max_vars
else:
conv2d_backprop_input = tf.nn.conv2d_backprop_input
conv3d_transpose = tf.nn.conv3d_transpose
multinomial = tf.multinomial
space_to_batch_nd = tf.space_to_batch_nd
batch_to_space_nd = tf.batch_to_space_nd
reverse_v2 = tf.reverse_v2
random_normal = tf.random_normal
random_uniform = tf.random_uniform
fused_batch_norm = tf.nn.fused_batch_norm
dropout = tf.nn.dropout
resize_nearest_neighbor = tf.image.resize_nearest_neighbor
resize_bilinear = tf.image.resize_bilinear
is_nan = tf.is_nan
is_inf = tf.is_inf
floormod = tf.floormod
matrix_diag_part = tf.matrix_diag_part
def make_xval(shape):
x_val = np.arange(np.prod(shape)).astype("float32").reshape(shape)
return x_val
def get_conv_getdata(kind=1):
if kind == 0:
# generate all combinations (costly)
dims = [
("padding", ["SAME", "VALID"]),
("input_sizes", [[32, 35, 35, 3], [32, 17, 17, 3], [1, 28, 28, 3], [32, 8, 8, 3]]),
("filter_sizes", [[1, 3, 3, 1], [1, 2, 2, 1], [1, 5, 5, 1], [1, 1, 1, 1], [1, 5, 2, 1], [1, 2, 5, 1]]),
("strides", [[1, 2, 2, 1], [1, 1, 1, 1]]),
]
values = [key_values[1] for key_values in dims]
for idx, v in enumerate(product(*values)):
if True or idx == 30:
yield (idx,) + v
elif kind == 1:
# some combination to that give decent padding coverage
data = [
('SAME', [32, 35, 35, 3], [1, 3, 3, 1], [1, 2, 2, 1]),
('SAME', [32, 35, 35, 3], [1, 2, 2, 1], [1, 2, 2, 1]),
('SAME', [32, 35, 35, 3], [1, 1, 1, 1], [1, 1, 1, 1]),
('SAME', [32, 35, 35, 3], [1, 5, 2, 1], [1, 2, 2, 1]),
('SAME', [32, 35, 35, 3], [1, 2, 5, 1], [1, 2, 2, 1]),
('SAME', [32, 35, 35, 3], [1, 2, 5, 1], [1, 1, 1, 1]),
('SAME', [1, 28, 28, 3], [1, 3, 3, 1], [1, 2, 2, 1]),
('SAME', [1, 28, 28, 3], [1, 3, 3, 1], [1, 1, 1, 1]),
('SAME', [1, 28, 28, 3], [1, 2, 2, 1], [1, 2, 2, 1]),
('SAME', [1, 28, 28, 3], [1, 2, 2, 1], [1, 1, 1, 1]),
('SAME', [1, 28, 28, 3], [1, 5, 5, 1], [1, 2, 2, 1]),
('SAME', [1, 28, 28, 3], [1, 5, 5, 1], [1, 1, 1, 1]),
('SAME', [1, 28, 28, 3], [1, 5, 2, 1], [1, 2, 2, 1]),
('SAME', [32, 8, 8, 3], [1, 3, 3, 1], [1, 2, 2, 1]),
('SAME', [32, 8, 8, 3], [1, 3, 3, 1], [1, 1, 1, 1]),
('VALID', [32, 35, 35, 3], [1, 3, 3, 1], [1, 1, 1, 1]),
('VALID', [32, 35, 35, 3], [1, 2, 2, 1], [1, 2, 2, 1]),
]
for idx, v in enumerate(data):
yield (idx,) + v
else:
raise ValueError("kind not known")
def get_maxpoolwithargmax_getdata():
data = [
('SAME', [1, 3, 3, 2], [1, 3, 3, 1], [1, 2, 2, 1]),
('SAME', [2, 5, 5, 3], [1, 4, 4, 1], [1, 2, 2, 1]),
('SAME', [2, 10, 5, 1], [1, 2, 2, 1], [1, 2, 2, 1]),
('SAME', [2, 10, 5, 3], [1, 4, 4, 1], [1, 1, 1, 1]),
('VALID', [2, 3, 3, 3], [1, 3, 3, 1], [1, 2, 2, 1]),
('VALID', [2, 5, 5, 3], [1, 4, 4, 1], [1, 2, 2, 1]),
]
for idx, v in enumerate(data):
yield (idx,) + v
class BackendTests(Tf2OnnxBackendTestBase):
def _run_test_case(self, func, output_names_with_port, feed_dict, **kwargs):
kwargs["convert_var_to_const"] = False
return self.run_test_case(func, feed_dict, [], output_names_with_port, **kwargs)
def _test_expand_dims_known_rank(self, idx):
x_val = make_xval([3, 4])
def func(x):
op = tf.expand_dims(x, idx)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def test_expand_dims_known_rank(self):
for i in [-1, 0, 1, -2]:
self._test_expand_dims_known_rank(i)
def test_expand_dims_one_unknown_rank(self):
x_val = make_xval([3, 4])
def func(x):
op = tf.expand_dims(x, 0)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def test_expand_dims_with_list(self):
x_val = make_xval([3, 4])
def func(x):
op = tf.expand_dims(x, [[0]])
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def _test_expand_dims_more_unknown_rank(self, idx):
x_val = make_xval([3, 4])
def func(x):
op = tf.expand_dims(x, idx)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def test_expand_dims_more_unknown_rank(self):
for i in [-1, 0, 1, -2]:
self._test_expand_dims_more_unknown_rank(i)
@check_opset_min_version(13, "Unsqueeze")
def test_expand_dims_nonconst_dims(self):
x_val = make_xval([3, 4])
y_val = np.array([-1], dtype=np.int32)
def func(x, y):
op = tf.expand_dims(x, y)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val, _INPUT1: y_val})
@check_opset_min_version(9, "ConstantOfShape")
def test_layer_normalization(self):
x_val = make_xval([3, 4, 5])
scale_val = make_xval([3, 4, 5]) * 0.2
bias_val = make_xval([3, 4, 5]) * 0.1
def func(x):
mean = tf.reduce_mean(x, axis=[2], keepdims=True)
centered = tf.subtract(x, mean)
variance = tf.add(tf.reduce_mean(tf.square(centered), axis=[2], keepdims=True), 0.001)
inv_std_dev = tf.math.rsqrt(variance)
normalized = tf.multiply(centered, inv_std_dev)
scaled = tf.multiply(normalized, scale_val)
biased = tf.add(scaled, bias_val)
return tf.identity(biased, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05,
graph_validator=lambda g: (check_op_count(g, "InstanceNormalization", 1)))
@check_opset_min_version(9, "ConstantOfShape")
def test_eye_non_const1(self):
# tf.eye(num_rows), num_rows is not const here
x_val = np.array(5, dtype=np.int32)
def func(x):
y = tf.eye(x, dtype=tf.int32)
y1 = tf.eye(x, dtype=tf.int64)
y2 = tf.eye(x, dtype=tf.float32)
return tf.identity(y, name=_TFOUTPUT), tf.identity(y1, name=_TFOUTPUT1), tf.identity(y2, name=_TFOUTPUT2)
self._run_test_case(func, [_OUTPUT, _OUTPUT1, _OUTPUT2], {_INPUT: x_val}, rtol=0)
# tf.eye(num_rows, num_columns), both num_rows and num_columns are not const here
x_val = np.array([5, 10], dtype=np.int32)
def func(x):
y = tf.eye(x[0], x[1], dtype=tf.int32)
y1 = tf.eye(x[0], x[1], dtype=tf.int64)
y2 = tf.eye(x[0], x[1], dtype=tf.float32)
return tf.identity(y, name=_TFOUTPUT), tf.identity(y1, name=_TFOUTPUT1), tf.identity(y2, name=_TFOUTPUT2)
self._run_test_case(func, [_OUTPUT, _OUTPUT1, _OUTPUT2], {_INPUT: x_val}, rtol=0)
@check_tf_min_version("1.11", "eye has bug when version is below 1.11")
@check_opset_min_version(9, "ConstantOfShape")
def test_eye_non_const2(self):
# tf.eye(num_rows), num_rows is not const here
for np_dtype in [np.int32, np.int64, np.float32, np.float64]:
x_val = np.array(5, dtype=np_dtype)
def func(x):
y = tf.eye(x, dtype=tf.int32)
y1 = tf.eye(x, dtype=tf.float32)
return tf.identity(y, name=_TFOUTPUT),\
tf.identity(y1, name=_TFOUTPUT1)
self._run_test_case(func, [_OUTPUT, _OUTPUT1], {_INPUT: x_val}, rtol=0)
# tf.eye(num_rows, num_columns), both num_rows and num_columns are not const here
for np_dtype in [np.int32, np.int64, np.float32, np.float64]:
x_val = np.array([5, 10], dtype=np_dtype)
def func(x):
y = tf.eye(x[0], x[1], dtype=tf.int32)
y1 = tf.eye(x[0], x[1], dtype=tf.float32)
return tf.identity(y, name=_TFOUTPUT), \
tf.identity(y1, name=_TFOUTPUT1)
self._run_test_case(func, [_OUTPUT, _OUTPUT1], {_INPUT: x_val}, rtol=0)
@check_opset_min_version(7, "trig")
def test_trig_ops(self):
for op in [tf.sin, tf.cos, tf.tan, tf.asin, tf.acos, tf.atan]:
x_val = make_xval([3, 4])
def func(x):
op_ = op(x)
return tf.identity(op_, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-06)
@check_opset_min_version(9, "trigh")
def test_atrig_ops(self):
for op in [tf.sinh, tf.cosh, tf.atanh, tf.asinh, tf.acosh]:
x_val = make_xval([3, 4])
def func(x):
op_ = op(x)
return tf.identity(op_, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@skip_caffe2_backend()
@check_opset_min_version(7, "multinomial")
def test_multinomial(self):
x_val = np.array([[10., 10.]], dtype=np.float32)
def func(x):
op = multinomial(tf.math.log(x), 5, output_dtype=tf.int32)
return tf.identity(op, name=_TFOUTPUT)
# since returned indexes are random we can only check type and shape
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, check_value=False,
check_shape=True, check_dtype=True)
@skip_caffe2_backend()
@check_opset_min_version(7, "multinomial")
def test_multinomial1(self):
shape = [2, 10]
x_val = np.ones(np.prod(shape)).astype("float32").reshape(shape)
def func(x):
op = multinomial(x, 2, output_dtype=tf.int32)
return tf.identity(op, name=_TFOUTPUT)
# since returned indexes are random we can only check type and shape
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, check_value=False,
check_shape=True, check_dtype=True)
def test_maxpool(self):
for p in get_conv_getdata():
_, padding, x_shape, ksize, strides = p
x_val = make_xval(x_shape)
def func(x):
mp = tf.nn.max_pool(x, ksize, strides, padding=padding)
return tf.identity(mp, name=_TFOUTPUT)
self.logger.debug(str(p))
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_tf_min_version("1.15", "required for max_pool args")
def test_maxpool_int(self):
x_shape = [8, 16, 16, 3]
x_val = make_xval(x_shape).astype("int32")
def func(x):
mp = tf.nn.max_pool(x, ksize=[2], strides=[1, 2, 2, 1], padding="SAME")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@skip_tf_cpu("only tf_gpu can run maxpool with NCHW format")
def test_maxpool_gpu(self):
# make sure converter behaves well when data format is NCHW
# and when data format is NCHW, only gpu version of tensorflow can run it.
ksize = [1, 1, 2, 2]
strides = [1, 1, 2, 2]
x_val = make_xval([1, 3, 50, 80])
for padding in ["SAME", "VALID"]:
def func(x):
mp = tf.nn.max_pool(x, ksize, strides, padding=padding, data_format="NCHW")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_onnxruntime_incompatibility("AveragePool")
def test_avgpool(self):
for p in get_conv_getdata(kind=0):
_, padding, x_shape, ksize, strides = p
x_val = make_xval(x_shape)
def func(x):
mp = tf.nn.avg_pool(x, ksize, strides, padding=padding)
return tf.identity(mp, name=_TFOUTPUT)
self.logger.debug(str(p))
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-06)
@check_onnxruntime_incompatibility("AveragePool")
@skip_tf_cpu("only tf_gpu can run avgpool with NCHW format")
def test_avgpool_gpu(self):
ksize = [1, 1, 2, 2]
strides = [1, 1, 2, 2]
x_val = make_xval([1, 3, 50, 80])
for padding in ["SAME", "VALID"]:
def func(x):
mp = tf.nn.avg_pool(x, ksize, strides, padding=padding, data_format="NCHW")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def _conv_test(self, x_val, w, strides=None, padding="VALID", dilations=None, rtol=1e-07):
if strides is None:
strides = _STRIDE1x1
if dilations is None:
dilations = _DILATIONS1x1
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
conv = tf.nn.conv2d(x, kernel, strides=strides, padding=padding, dilations=dilations)
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=rtol)
def test_conv2d_1(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
w = np.array([[2., 1., 1.],
[1., 3., 1.],
[1., 1., 4.]], dtype=np.float32).reshape(_KERNEL3x3)
self._conv_test(x_val, w)
def test_conv2d_2(self):
x_val = np.array([[4, 3, 1, 0],
[2, 1, 0, 1],
[1, 2, 4, 1],
[3, 1, 0, 2]], dtype=np.float32).reshape([1, 4, 4, 1])
w = np.array([[1, 0, 1],
[2, 1, 0],
[0, 0, 1]], dtype=np.float32).reshape(_KERNEL3x3)
self._conv_test(x_val, w)
def test_conv2d_3(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
w = np.array([[2., 1., 1.],
[1., 3., 1.],
[1., 1., 4.]], dtype=np.float32).reshape(_KERNEL3x3)
self._conv_test(x_val, w)
def test_conv2d_4(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
w = np.random.random_sample(_KERNEL3x3).astype(np.float32)
self._conv_test(x_val, w, padding="SAME", rtol=1e-05)
def test_conv2d_5(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
kernel_shape = [3, 3, 1, 2]
w = np.random.random_sample(kernel_shape).astype(np.float32)
self._conv_test(x_val, w, padding="SAME", rtol=1e-05)
def test_conv2d_6(self):
x_shape = [1, 35, 35, 288] # out: [1, 17, 17, 384]
kernel_shape = [3, 3, 288, 384]
strides = [1, 2, 2, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_val, kernel_val, strides=strides, padding="VALID", rtol=1.1e-05)
@check_tf_min_version("1.14", "tf 1.14 needed for explicit padding")
def test_conv2d_explicit_padding(self):
x_shape = [1, 35, 35, 288]
kernel_shape = [3, 3, 288, 384]
pads = [[0, 0], [1, 2], [3, 4], [0, 0]]
strides = [1, 1, 1, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_val, kernel_val, strides=strides, padding=pads, rtol=1.1e-05)
def test_conv2d_dilation_same(self):
x_shape = [1, 35, 35, 288] # NHWC
kernel_shape = [3, 3, 288, 384] # [filter_height, filter_width, in_channels, out_channels]
strides = [1, 1, 1, 1] # NHWC
dilations = [1, 3, 1, 1] # NHWC
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_val, kernel_val, strides=strides, padding="SAME", dilations=dilations, rtol=1.1e-05)
def test_conv2d_dilation_strides_same(self):
x_shape = [1, 35, 35, 288] # NHWC
kernel_shape = [3, 3, 288, 384] # [filter_height, filter_width, in_channels, out_channels]
strides = [1, 2, 4, 1] # NHWC
dilations = [1, 3, 1, 1] # NHWC
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_val, kernel_val, strides=strides, padding="SAME", dilations=dilations, rtol=1e-05)
def test_conv3d_1(self):
strides = [1, 1, 1, 1, 1]
dilations = [1, 1, 1, 1, 1]
x_val = np.random.random_sample([2, 10, 9, 8, 5]).astype(np.float32)
w = np.random.random_sample([2, 3, 4, 5, 6]).astype(np.float32)
padding = "VALID"
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
conv = tf.nn.conv3d(x, kernel, strides=strides, padding=padding, data_format="NDHWC", dilations=dilations)
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
def test_conv3d_2(self):
strides = [1, 2, 3, 1, 1]
dilations = [1, 1, 1, 1, 1]
x_val = np.random.random_sample([2, 10, 9, 8, 5]).astype(np.float32)
w = np.random.random_sample([2, 3, 4, 5, 6]).astype(np.float32)
padding = "VALID"
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
conv = tf.nn.conv3d(x, kernel, strides=strides, padding=padding, data_format="NDHWC", dilations=dilations)
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
def test_conv3d_3(self):
strides = [1, 2, 3, 1, 1]
dilations = [1, 1, 1, 1, 1]
x_val = np.random.random_sample([2, 10, 9, 8, 5]).astype(np.float32)
w = np.random.random_sample([2, 3, 4, 5, 6]).astype(np.float32)
padding = "SAME"
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
conv = tf.nn.conv3d(x, kernel, strides=strides, padding=padding, data_format="NDHWC", dilations=dilations)
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
def test_avgpool3d(self):
strides = [1, 1, 1, 1, 1]
ksize = [1, 2, 2, 3, 1]
x_val = np.random.random_sample([2, 10, 9, 8, 5]).astype(np.float32)
padding = "VALID"
def func(x):
mp = tf.nn.avg_pool3d(x, ksize, strides, padding=padding, data_format="NDHWC")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
def test_maxpool3d(self):
strides = [1, 1, 1, 1, 1]
ksize = [1, 2, 2, 3, 1]
x_val = np.random.random_sample([2, 10, 9, 8, 5]).astype(np.float32)
padding = "VALID"
def func(x):
mp = tf.nn.max_pool3d(x, ksize, strides, padding=padding, data_format="NDHWC")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_tf_min_version("1.14", "tf.nn.avg_pool2d doesn't exist before tf 1.14")
def test_avgpool2d(self):
strides = [1, 1, 1, 1]
ksize = [1, 2, 3, 1]
x_val = make_xval([2, 10, 12, 3])
padding = "VALID"
def func(x):
mp = tf.nn.avg_pool2d(x, ksize, strides, padding=padding, data_format="NHWC")
return tf.identity(mp, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_tf_min_version("1.7", "tf only support dilation is 1 for now")
def test_conv2d_7(self):
x_shape = [1, 35, 35, 288] # out: [1, 17, 17, 384]
kernel_shape = [3, 3, 288, 384]
strides = [1, 2, 2, 1]
dilations = [1, 3, 3, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
self._conv_test(x_val, kernel_val, strides=strides, padding="VALID",
dilations=dilations, rtol=1e-05)
def test_conv2d_8(self):
for input_shape in [[10, 10], [5, 5]]:
x_val = make_xval((1, 1, *input_shape)).transpose(NCHW_TO_NHWC)
w = np.random.random_sample([3, 3, 1, 2]).astype(np.float32)
strides = [1, 2, 2, 1]
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
conv = tf.nn.conv2d(x, kernel, strides=strides, padding="SAME")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-5)
def test_conv2d_with_pad_valid(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
w = np.random.random_sample([3, 3, 1, 2]).astype(np.float32)
strides = [1, 1, 1, 1]
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
x_pad = tf.pad(x, paddings=[[0, 0], [2, 2], [2, 2], [0, 0]])
conv = tf.nn.conv2d(x_pad, kernel, strides=strides, padding="VALID")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-5)
def test_conv2d_with_pad_same(self):
x_val = make_xval((1, 1, 5, 5)).transpose(NCHW_TO_NHWC)
w = np.random.random_sample([3, 3, 1, 2]).astype(np.float32)
strides = [1, 1, 1, 1]
def func(x):
kernel = tf.constant(w, dtype=tf.float32, name='k')
x_pad = tf.pad(x, paddings=[[0, 0], [2, 2], [2, 2], [0, 0]])
conv = tf.nn.conv2d(x_pad, kernel, strides=strides, padding="SAME")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-5)
def test_conv2d_transpose(self):
x_shape = [2, 6, 4, 3]
output_shape = [2, 13, 9, 2]
kernel_shape = [3, 3, 2, 3]
strides = [1, 2, 2, 1]
x_val = make_xval(x_shape)
kernel_val = make_xval(kernel_shape)
def func(x):
f = tf.constant(kernel_val, name="kernel", dtype=tf.float32)
conv = tf.nn.conv2d_transpose(x, f, output_shape, strides=strides, padding="VALID")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
@check_onnxruntime_min_version("0.5.0", "conv transpose is added since onnxruntime-0.5.0")
def test_conv2d_transpose2(self):
# output_shape is dynamic
extra_opset = [utils.make_opsetid(constants.MICROSOFT_DOMAIN, 1)]
process_args = {"extra_opset": extra_opset}
x_shape = [2, 6, 4, 3]
output_shape = np.array([2, 13, 9, 2]).astype(np.int32)
kernel_shape = [3, 3, 2, 3]
strides = [1, 2, 2, 1]
x_val = make_xval(x_shape)
kernel_val = make_xval(kernel_shape)
def func(x, output_shape_placeholder):
f = tf.constant(kernel_val, name="kernel", dtype=tf.float32)
conv = tf.nn.conv2d_transpose(x, f, output_shape_placeholder, strides=strides, padding="VALID")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val, _INPUT1: output_shape},
rtol=1e-05, process_args=process_args)
@check_opset_min_version(10, "quantize_and_dequantize")
def test_conv2d_quantization_axis(self):
x_shape = [1, 1, 5, 5]
kernel_shape = _KERNEL3x3
strides = [1, 1, 1, 1]
x_val = make_xval(x_shape).transpose(NCHW_TO_NHWC)
kernel_val = make_xval(_KERNEL3x3)
def func(x):
f = tf.constant(kernel_val, name="kernel", dtype=tf.float32)
kernel_dq = quantize_and_dequantize(f, 0, np.prod(kernel_shape))
conv = tf.nn.conv2d(x, kernel_dq, strides=strides, padding="VALID")
return tf.identity(conv, name=_TFOUTPUT)
def graph_validator(g):
return check_quantization_axis(g, "DequantizeLinear", 0)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05, graph_validator=graph_validator,
check_shape=False)
@check_opset_min_version(10, "quantize_and_dequantize")
def test_conv2d_transpose_quantization_axis(self):
x_shape = [2, 6, 4, 3]
output_shape = [2, 13, 9, 2]
kernel_shape = [3, 3, 2, 3]
strides = [1, 2, 2, 1]
x_val = make_xval(x_shape)
kernel_val = make_xval(kernel_shape)
def func(x):
f = tf.constant(kernel_val, name="kernel", dtype=tf.float32)
kernel_dq = quantize_and_dequantize(f, 0, np.prod(kernel_shape))
conv = tf.nn.conv2d_transpose(x, kernel_dq, output_shape, strides=strides, padding="VALID")
return tf.identity(conv, name=_TFOUTPUT)
def graph_validator(g):
return check_quantization_axis(g, "DequantizeLinear", 1)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05, graph_validator=graph_validator,
check_shape=False)
def test_depthwiseconv_0(self):
x_shape = [1, 3, 4, 3]
kernel_shape = [3, 3, 3, 3]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
def func(x):
kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')
conv = tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=0.08)
def test_depthwiseconv_1(self):
x_shape = [1, 112, 112, 32]
kernel_shape = [3, 3, 32, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
def func(x):
kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')
conv = tf.nn.depthwise_conv2d(x, kernel, strides=_STRIDE1x1, padding='VALID')
return tf.identity(conv, name=_TFOUTPUT)
# rtol is a bit high, 2 values have a bit high error. Maybe use different input data.
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=0.08)
def test_depthwiseconv_3(self):
x_shape = [1, 112, 112, 32]
kernel_shape = [3, 3, 32, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
def func(x):
kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')
conv = tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')
return tf.identity(conv, name=_TFOUTPUT)
# rtol is a bit high, 2 values have a bit high error. Maybe use different input data.
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=0.01)
def test_depthwiseconv_shared_kernel(self):
x_shape = [1, 3, 4, 3]
kernel_shape = [3, 3, 3, 3]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
def func(x, y):
kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')
conv1 = tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')
conv2 = tf.nn.depthwise_conv2d(y, kernel, strides=[1, 1, 1, 1], padding='VALID')
conv = tf.add(conv1, conv2)
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val, _INPUT1: x_val}, rtol=0.08)
@check_tf_min_version("1.14", "tf depthwise_conv2d dilations")
@check_opset_min_version(11, "non-const pads")
def test_depthwiseconv_dilations(self):
x_shape = [1, 32, 32, 1]
kernel_shape = [5, 5, 1, 1]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
kernel_val = np.arange(1, 1 + np.prod(kernel_shape)).astype("float32").reshape(kernel_shape)
def func(x):
kernel = tf.constant(kernel_val, dtype=tf.float32, name='k')
conv = tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], padding='SAME', dilations=[3, 4])
return tf.identity(conv, name=_TFOUTPUT)
# rtol is a bit high, 2 values have a bit high error. Maybe use different input data.
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=0.01)
@check_tf_max_version("1.15", "not supported in tf-2.0")
def test_dropout(self):
x_val = np.ones([1, 24, 24, 3], dtype=np.float32)
# Define a scope for reusing the variables
def func(x):
is_training = tf.constant(False, tf.bool)
x_ = tf.identity(x)
fc1 = tf.layers.dropout(x_, rate=.1, training=is_training)
return tf.identity(fc1, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val},
graph_validator=lambda g: (check_op_count(g, "RandomUniform", 0) and
check_op_count(g, "RandomUniformLike", 0)))
def test_nn_dropout(self):
x_val = np.ones([1, 24, 24, 3], dtype=np.float32)
# Define a scope for reusing the variables
def func(x, keep_prob):
x_ = tf.identity(x)
fc1 = dropout(x_, keep_prob)
return tf.identity(fc1, name=_TFOUTPUT)
# when constant_fold is enabled, PlaceholderWithDefault will be folded into either a const or a placeholder.
# here we set it False to test PlaceholderWithDefault bug: https://github.com/onnx/tensorflow-onnx/pull/446
# Dropout with ratio 1.0 will be optimized so that only one Identity is left
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val, _INPUT1: np.array(1., dtype=np.float32)},
graph_validator=lambda g: (check_op_count(g, "RandomUniform", 0) and
check_op_count(g, "RandomUniformLike", 0)))
@check_tf_min_version("1.13")
def test_nn_dropout_with_rate(self):
rate = tf.constant(0., name="rate")
x_val = np.ones([1, 24, 24, 3], dtype=np.float32)
# Define a scope for reusing the variables
def func(x):
x_ = tf.identity(x)
fc1 = tf.nn.dropout(x_, rate=rate)
return tf.identity(fc1, name="output")
feed_dict = {"input_1:0": x_val}
input_names_with_port = ["input_1:0"]
output_names_with_port = ["output:0"]
self.run_test_case(func, feed_dict, input_names_with_port, output_names_with_port,
graph_validator=lambda g: (check_op_count(g, "RandomUniform", 0) and
check_op_count(g, "RandomUniformLike", 0)))
def test_inputs_as_nchw_arg(self):
x_shape = [2, 32, 32, 3]
kernel_shape = [3, 3, 3, 3]
x_val = make_xval(x_shape)
x_val_for_onnx = x_val.transpose(NHWC_TO_NCHW)
def func(x):
kernel = tf.constant(make_xval(kernel_shape), dtype=tf.float32, name='k')
conv = tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding="SAME")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05,
process_args={"inputs_as_nchw": [_INPUT]},
onnx_feed_dict={_INPUT: x_val_for_onnx})
def test_outputs_as_nchw_arg(self):
x_shape = [2, 32, 32, 3]
kernel_shape = [3, 3, 3, 3]
x_val = make_xval(x_shape)
def func(x):
kernel = tf.constant(make_xval(kernel_shape), dtype=tf.float32, name='kernel')
conv = tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding="SAME")
return tf.identity(conv, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05,
process_args={"outputs_as_nchw": [_OUTPUT]})
@skip_tflite("TFlite adds ops that obscure pattern")
@check_tf_min_version("1.15")
def test_conv1d_dilations_rewriter(self):
x_shape = [2, 32, 3]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
t = tf.keras.layers.Conv1D(filters=768, kernel_size=3, dilation_rate=3, padding=p)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
@skip_tf_cpu("only tf_gpu can run conv2d with NCHW format")
def test_conv2d_biasadd_rewriter(self):
x_shape = [2, 3, 32, 16]
x_val = make_xval(x_shape)
def func(x):
middles = tf.keras.layers.ZeroPadding2D(
padding=(0, 4),
data_format="channels_first",
name="padding"
)(x)
t = tf.keras.layers.Conv2D(
filters=768,
kernel_size=3,
strides=1,
use_bias=True,
data_format="channels_first",
name="conv2d"
)(middles)
return tf.identity(t, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Add", 0, disabled=False))
@check_tf_min_version("1.15")
def test_conv2d_dilations_rewriter(self):
x_shape = [2, 32, 16, 3]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
t = tf.keras.layers.Conv2D(filters=768, kernel_size=3, dilation_rate=3, padding=p)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
def func(x):
t = tf.keras.layers.DepthwiseConv2D(kernel_size=3, dilation_rate=3, padding=p)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
@skip_tf_cpu("only tf_gpu can run conv2d with NCHW format")
def test_nchw_conv2d_dilations_rewriter(self):
x_shape = [2, 3, 32, 16]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
t = tf.keras.layers.Conv2D(
filters=768,
kernel_size=3,
dilation_rate=3,
padding=p,
data_format='channels_first'
)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
def func(x):
t = tf.keras.layers.DepthwiseConv2D(
kernel_size=3,
dilation_rate=3,
padding=p,
data_format='channels_first'
)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
@skip_tflite("TFlite adds ops that obscure pattern")
@allow_missing_shapes("Rewriting makes some shapes known")
def test_conv2d_dilations_rewriter_unknown_shape(self):
x_shape = [2, 32, 16, 3]
x_val = make_xval(x_shape)
def func():
x = tf_placeholder(tf.float32, [2, None, None, 3], name=_TFINPUT)
t = tf.keras.layers.Conv2D(filters=768, kernel_size=3, dilation_rate=3, padding="VALID")
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2,
as_session=True, premade_placeholders=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
@skip_tflite("TFlite adds ops that obscure pattern")
@skip_tf_cpu("only tf_gpu can run conv2d with NCHW format")
@allow_missing_shapes("Rewriting makes some shapes known")
def test_nchw_conv2d_dilations_rewriter_unknown_shape(self):
x_shape = [2, 3, 32, 16]
x_val = make_xval(x_shape)
def func():
x = tf_placeholder(tf.float32, [2, 3, None, None], name=_TFINPUT)
t = tf.keras.layers.Conv2D(
filters=768,
kernel_size=3,
dilation_rate=3,
padding="VALID",
data_format='channels_first'
)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2,
as_session=True, premade_placeholders=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
def test_conv3d_dilations_rewriter(self):
x_shape = [2, 32, 16, 8, 3]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
t = tf.keras.layers.Conv3D(filters=768, kernel_size=3, dilation_rate=3, padding=p)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@check_tf_min_version("1.15")
@skip_tf_cpu("only tf_gpu can run conv3d with NCDHW format")
def test_ncdhw_conv3d_dilations_rewriter(self):
x_shape = [2, 3, 32, 16, 8]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
t = tf.keras.layers.Conv3D(
filters=768,
kernel_size=3,
dilation_rate=3,
padding=p,
data_format='channels_first'
)
t.build(x_shape)
y = t.call(x)
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@skip_tf2("Uses tf.layers")
def test_conv1d_tf1_dilations_rewriter(self):
x_shape = [2, 32, 3]
x_val = make_xval(x_shape)
for p in ['SAME', 'VALID']:
def func(x):
y = tf.layers.conv1d(x, filters=768, kernel_size=3, dilation_rate=3, padding=p, name="conv1")
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2, as_session=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
@skip_tf2("Uses tf.layers")
def test_conv1d_tf1_dilations_rewriter_unknown_shape(self):
x_shape = [2, 32, 3]
x_val = make_xval(x_shape)
def func():
x = tf_placeholder(tf.float32, [2, None, 3], name=_TFINPUT)
y = tf.layers.conv1d(x, filters=768, kernel_size=3, dilation_rate=3, padding="VALID", name="conv1")
return tf.identity(y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-04, atol=1e-2,
as_session=True, premade_placeholders=True,
graph_validator=lambda g: check_op_count(g, "Reshape", 0, disabled=False))
def test_lrn_default(self):
x_shape = [1, 3, 4, 3]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
def func(x):
op = tf.nn.local_response_normalization(x)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
def test_lrn(self):
# can't set bias = 0
x_shape = [1, 2, 2, 8]
x_val = np.arange(1, 1 + np.prod(x_shape)).astype("float32").reshape(x_shape)
def func(x):
op = tf.nn.local_response_normalization(x, depth_radius=4, bias=2, alpha=2, beta=1)
return tf.identity(op, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val}, rtol=1e-05)
@check_onnxruntime_incompatibility("Abs")
def test_abs(self):
x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))
def func(x):
x_ = tf.abs(x)
return tf.identity(x_, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_onnxruntime_incompatibility("Add")
def test_const(self):
x_val = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32).reshape((2, 2))
def func(x):
y = tf.constant(x_val, name="y")
return tf.add(x, y, name=_TFOUTPUT)
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
@check_onnxruntime_incompatibility("Add")
def test_add(self):
x_val = np.array([1.0, 2.0, -3.0, -4.0], dtype=np.float32).reshape((2, 2))
def func(x):
x_ = tf.add(x, x)