forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utility_funs.py
1974 lines (1698 loc) · 71.4 KB
/
test_utility_funs.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
# Owner(s): ["module: onnx"]
import copy
import functools
import io
import re
import warnings
from typing import Callable
import onnx
import parameterized
import pytorch_test_common
import torchvision
from autograd_helper import CustomFunction as CustomFunction2
from pytorch_test_common import (
skipIfNoCuda,
skipIfUnsupportedMaxOpsetVersion,
skipIfUnsupportedMinOpsetVersion,
)
import torch
import torch.onnx
import torch.utils.cpp_extension
from torch.onnx import _constants, OperatorExportTypes, TrainingMode, utils
from torch.onnx._globals import GLOBALS
from torch.onnx.symbolic_helper import _unpack_list, parse_args
from torch.testing._internal import common_utils
from torch.testing._internal.common_utils import skipIfNoLapack
def _remove_test_environment_prefix_from_scope_name(scope_name: str) -> str:
"""Remove test environment prefix added to module.
Remove prefix to normalize scope names, since different test environments add
prefixes with slight differences.
Example:
>>> _remove_test_environment_prefix_from_scope_name(
>>> "test_utility_funs.M"
>>> )
"M"
>>> _remove_test_environment_prefix_from_scope_name(
>>> "test_utility_funs.test_abc.<locals>.M"
>>> )
"M"
>>> _remove_test_environment_prefix_from_scope_name(
>>> "__main__.M"
>>> )
"M"
"""
prefixes_to_remove = ["test_utility_funs", "__main__"]
for prefix in prefixes_to_remove:
scope_name = re.sub(f"{prefix}\\.(.*?<locals>\\.)?", "", scope_name)
return scope_name
class _BaseTestCase(pytorch_test_common.ExportTestCase):
def _model_to_graph(
self,
model,
input,
do_constant_folding=True,
training=TrainingMode.EVAL,
operator_export_type=OperatorExportTypes.ONNX,
input_names=None,
dynamic_axes=None,
):
torch.onnx.utils._setup_trace_module_map(model, False)
if training == torch.onnx.TrainingMode.TRAINING:
model.train()
elif training == torch.onnx.TrainingMode.EVAL:
model.eval()
utils._validate_dynamic_axes(dynamic_axes, model, None, None)
graph, params_dict, torch_out = utils._model_to_graph(
model,
input,
do_constant_folding=do_constant_folding,
_disable_torch_constant_prop=True,
operator_export_type=operator_export_type,
training=training,
input_names=input_names,
dynamic_axes=dynamic_axes,
)
return graph, params_dict, torch_out
@common_utils.instantiate_parametrized_tests
class TestUnconvertibleOps(pytorch_test_common.ExportTestCase):
"""Unit tests for the `unconvertible_ops` function."""
def setUp(self):
class EinsumModule(torch.nn.Module):
def forward(self, x):
return torch.einsum("ii", x)
self.einsum_module = EinsumModule()
def test_it_returns_graph_and_unconvertible_ops_at_lower_opset_version(self):
x = torch.randn(4, 4)
# Einsum is supported since opset 12. It should be unconvertible at opset 9.
graph, unconvertible_ops = utils.unconvertible_ops(
self.einsum_module, (x,), opset_version=9
)
nodes = graph.nodes()
self.assertEqual(next(nodes).kind(), "prim::Constant")
self.assertEqual(next(nodes).kind(), "prim::ListConstruct")
self.assertEqual(next(nodes).kind(), "prim::Constant")
self.assertEqual(next(nodes).kind(), "aten::einsum")
self.assertEqual(unconvertible_ops, ["aten::einsum"])
@common_utils.parametrize(
"jit_function",
[
common_utils.subtest(
functools.partial(torch.jit.trace, example_inputs=torch.randn(4, 4)),
name="traced",
),
common_utils.subtest(torch.jit.script, name="scripted"),
],
)
def test_it_returns_unconvertible_ops_at_lower_opset_version_for_jit_module(
self, jit_function: Callable
):
module = jit_function(self.einsum_module)
x = torch.randn(4, 4)
# Einsum is supported since opset 12. It should be unconvertible at opset 9.
_, unconvertible_ops = utils.unconvertible_ops(module, (x,), opset_version=9)
self.assertEqual(unconvertible_ops, ["aten::einsum"])
@common_utils.parametrize(
"jit_function",
[
common_utils.subtest(lambda x: x, name="nn_module"),
common_utils.subtest(
functools.partial(torch.jit.trace, example_inputs=torch.randn(4, 4)),
name="traced",
),
common_utils.subtest(torch.jit.script, name="scripted"),
],
)
def test_it_returns_empty_list_when_all_ops_convertible(
self, jit_function: Callable
):
module = jit_function(self.einsum_module)
x = torch.randn(4, 4)
# Einsum is supported since opset 12
_, unconvertible_ops = utils.unconvertible_ops(module, (x,), opset_version=12)
self.assertEqual(unconvertible_ops, [])
def test_it_returns_empty_list_when_model_contains_supported_inplace_ops(self):
class SkipConnectionModule(torch.nn.Module):
def forward(self, x):
out = x
out += x
out = torch.nn.functional.relu(out, inplace=True)
return out
module = SkipConnectionModule()
x = torch.randn(4, 4)
_, unconvertible_ops = utils.unconvertible_ops(module, (x,), opset_version=13)
self.assertEqual(unconvertible_ops, [])
@parameterized.parameterized_class(
[
{"opset_version": opset}
for opset in range(
_constants.ONNX_BASE_OPSET,
_constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET + 1,
)
],
class_name_func=lambda cls,
num,
params_dict: f"{cls.__name__}_opset_{params_dict['opset_version']}",
)
class TestUtilityFuns(_BaseTestCase):
opset_version = None
def test_is_in_onnx_export(self):
test_self = self
class MyModule(torch.nn.Module):
def forward(self, x):
test_self.assertTrue(torch.onnx.is_in_onnx_export())
raise ValueError
return x + 1
x = torch.randn(3, 4)
f = io.BytesIO()
try:
torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version)
except ValueError:
self.assertFalse(torch.onnx.is_in_onnx_export())
def test_validate_dynamic_axes_invalid_input_output_name(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
utils._validate_dynamic_axes(
{"input1": {}, "output": {}, "invalid_name1": {}, "invalid_name2": {}},
None,
["input1", "input2"],
["output"],
)
messages = [str(warning.message) for warning in w]
self.assertIn(
"Provided key invalid_name1 for dynamic axes is not a valid input/output name",
messages,
)
self.assertIn(
"Provided key invalid_name2 for dynamic axes is not a valid input/output name",
messages,
)
self.assertEqual(len(messages), 2)
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_to_slice(self):
class SplitModule(torch.nn.Module):
def forward(self, x, y, t):
splits = (x.size(1), y.size(1))
out, out2 = torch.split(t, splits, dim=1)
return out, out2
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.randn(2, 3)
y = torch.randn(2, 4)
t = torch.randn(2, 7)
graph, _, _ = self._model_to_graph(
SplitModule(),
(x, y, t),
input_names=["x", "y", "t"],
dynamic_axes={"x": [0, 1], "y": [0, 1], "t": [0, 1]},
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::SplitToSequence")
def test_constant_fold_transpose(self):
class TransposeModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.transpose(a, 1, 0)
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(3, 2)
graph, _, __ = self._model_to_graph(
TransposeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Transpose")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
@skipIfUnsupportedMaxOpsetVersion(17)
def test_constant_fold_reduceL2(self):
class ReduceModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.norm(a, p=2, dim=-2, keepdim=False)
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(2, 3)
graph, _, __ = self._model_to_graph(
ReduceModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::ReduceL2")
@skipIfUnsupportedMaxOpsetVersion(17)
def test_constant_fold_reduceL1(self):
class NormModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.norm(a, p=1, dim=-2)
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(2, 3)
graph, _, __ = self._model_to_graph(
NormModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::ReduceL1")
def test_constant_fold_slice(self):
class NarrowModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.narrow(a, 0, 0, 1)
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(1, 3)
graph, _, __ = self._model_to_graph(
NarrowModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Slice")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_slice_index_exceeds_dim(self):
class SliceIndexExceedsDimModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = a[1:10] # index exceeds dimension
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(1, 3)
graph, _, __ = self._model_to_graph(
SliceIndexExceedsDimModule(),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1]},
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Slice")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_slice_negative_index(self):
class SliceNegativeIndexModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = a[0:-1] # index relative to the end
c = torch.select(a, dim=-1, index=-2)
d = torch.select(a, dim=1, index=0)
return b + x, c + d
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(1, 3)
graph, _, __ = self._model_to_graph(
SliceNegativeIndexModule(),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1]},
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Slice")
self.assertNotEqual(node.kind(), "onnx::Cast")
def test_constant_fold_gather(self):
class GatherModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.select(a, dim=1, index=-2)
c = torch.index_select(a, dim=-2, index=torch.tensor([0, 1]))
return b + 1, c + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(1, 3)
model = GatherModule()
model(x)
graph, _, __ = self._model_to_graph(
GatherModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Gather")
def test_constant_fold_unsqueeze(self):
class UnsqueezeModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = torch.unsqueeze(a, -2)
return b + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(1, 2, 3)
graph, _, __ = self._model_to_graph(
UnsqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Unsqueeze")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_unsqueeze_multi_axies(self):
class PReluModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.prelu = torch.nn.PReLU()
def forward(self, x):
a = torch.randn(2, 3, 4, 5, 8, 7)
return self.prelu(x) + a
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.randn(2, 3, 4, 5, 8, 7)
graph, _, __ = self._model_to_graph(
PReluModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3, 4, 5]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Unsqueeze")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 5)
def test_constant_fold_squeeze_without_axes(self):
class SqueezeModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]])
return torch.squeeze(a) + x + torch.squeeze(a)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(2, 3)
graph, _, __ = self._model_to_graph(
SqueezeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Squeeze")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 4)
def test_constant_fold_squeeze_with_axes(self):
class SqueezeAxesModule(torch.nn.Module):
def forward(self, x):
a = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]])
return torch.squeeze(a, dim=-3) + x
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(2, 3)
graph, _, __ = self._model_to_graph(
SqueezeAxesModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Squeeze")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_concat(self):
class ConcatModule(torch.nn.Module):
def forward(self, x):
# Why did I insert a Cast here? There appears to be intentional
# behavior in ONNX constant folding where constant tensors which
# are not attached to any known to be foldable onnx
# operations don't get extracted into the initializer graph. So
# without these casts, we will actually fail to pull out one of
# the constants, thus failing constant folding. I think the
# test is wrong but I don't have time to write a more correct
# test (I think the right way to go about the test is to setup
# a predicate for what invariant graphs should hold after
# constant folding, and then verify this predicate holds.
# I think the asserts below are an attempt at this predicate,
# but it is not right!)
#
# More commentary at
# https://github.com/pytorch/pytorch/pull/18698/files#r340107552
a = torch.tensor([[1.0, 2.0, 3.0]]).to(torch.float)
b = torch.tensor([[4.0, 5.0, 6.0]]).to(torch.float)
c = torch.cat((a, b), 0)
d = b + c
return x + d
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.ones(2, 3)
graph, _, __ = self._model_to_graph(
ConcatModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Concat")
self.assertNotEqual(node.kind(), "onnx::Cast")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_lstm(self):
class GruNet(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.mygru = torch.nn.GRU(7, 3, 1, bidirectional=False)
def forward(self, input, initial_state):
return self.mygru(input, initial_state)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
input = torch.randn(5, 3, 7)
h0 = torch.randn(1, 3, 3)
graph, _, __ = self._model_to_graph(
GruNet(),
(input, h0),
input_names=["input", "h0"],
dynamic_axes={"input": [0, 1, 2], "h0": [0, 1, 2]},
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Slice")
self.assertNotEqual(node.kind(), "onnx::Concat")
self.assertNotEqual(node.kind(), "onnx::Unsqueeze")
if self.opset_version <= 12:
self.assertEqual(len(list(graph.nodes())), 3)
else:
# Unsqueeze op parameter "axes" as an input instead of as an attribute when opset version >= 13
self.assertEqual(len(list(graph.nodes())), 4)
def test_constant_fold_transpose_matmul(self):
class MatMulNet(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.B = torch.nn.Parameter(torch.ones(5, 3))
def forward(self, A):
return torch.matmul(A, torch.transpose(self.B, -1, -2))
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
A = torch.randn(2, 3)
graph, _, __ = self._model_to_graph(
MatMulNet(), (A,), input_names=["A"], dynamic_axes={"A": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Transpose")
self.assertEqual(len(list(graph.nodes())), 1)
def test_constant_fold_reshape(self):
class ReshapeModule(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
b = self.weight.reshape(1, -1, 1, 1)
return x * b
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
x = torch.randn(4, 5)
graph, _, __ = self._model_to_graph(
ReshapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Reshape")
self.assertEqual(len(list(graph.nodes())), 1)
def test_constant_fold_div(self):
class Module(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
div = self.weight.div(torch.tensor([1, 2, 3, 4, 5]))
return div * x
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, _, __ = self._model_to_graph(
Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Div")
self.assertEqual(len(list(graph.nodes())), 1)
def test_constant_fold_mul(self):
class Module(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
mul = self.weight.mul(torch.tensor([1, 2, 3, 4, 5]))
return mul / x
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, _, __ = self._model_to_graph(
Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Mul")
self.assertEqual(len(list(graph.nodes())), 1)
def test_constant_fold_add(self):
class Module(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
add = self.weight + torch.tensor([1, 2, 3, 4, 5])
return add - x
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, params_dict, __ = self._model_to_graph(
Module(),
(x,),
do_constant_folding=True,
operator_export_type=OperatorExportTypes.ONNX,
input_names=["x"],
dynamic_axes={"x": [0, 1]},
)
for node in graph.nodes():
self.assertTrue(node.kind() != "onnx::Add")
self.assertEqual(len(list(graph.nodes())), 1)
params = list(params_dict.values())
self.assertEqual(len(params), 1)
weight = params[0]
self.assertEqual(weight, torch.tensor([2.0, 3.0, 4.0, 5.0, 6.0]))
def test_constant_fold_sub(self):
class Module(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
sub = self.weight - torch.tensor([1, 2, 3, 4, 5])
return sub + x
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, params_dict, __ = self._model_to_graph(
Module(),
(x,),
do_constant_folding=True,
operator_export_type=OperatorExportTypes.ONNX,
input_names=["x"],
dynamic_axes={"x": [0, 1]},
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Sub")
self.assertEqual(len(list(graph.nodes())), 1)
params = list(params_dict.values())
self.assertEqual(len(params), 1)
weight = params[0]
self.assertEqual(weight, torch.tensor([0.0, -1.0, -2.0, -3.0, -4.0]))
def test_constant_fold_sqrt(self):
class Module(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
sqrt = torch.sqrt(self.weight)
return sqrt / x
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, _, __ = self._model_to_graph(
Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Sqrt")
self.assertEqual(len(list(graph.nodes())), 1)
def test_constant_fold_shape(self):
class ShapeModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
shape = self.weight.shape[0]
return x + shape
x = torch.randn(2, 5)
GLOBALS.export_onnx_opset_version = self.opset_version
GLOBALS.operator_export_type = OperatorExportTypes.ONNX
graph, _, __ = self._model_to_graph(
ShapeModule(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]}
)
for node in graph.nodes():
self.assertNotEqual(node.kind(), "onnx::Shape")
self.assertEqual(len(list(graph.nodes())), 2)
def test_constant_fold_upsample_scale_fold_as_constant(self):
# upsample scale is a constant, not a model parameter,
# therefore should not be added as initializer after constant folding.
model = torch.nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
x = torch.randn(1, 32, 224, 224)
f = io.BytesIO()
torch.onnx.export(model, x, f)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
self.assertEqual(len(onnx_model.graph.initializer), 0)
def test_verbose(self):
class MyModule(torch.nn.Module):
def forward(self, input):
return torch.exp(input)
x = torch.randn(3, 4)
def is_model_stripped(f, verbose=None):
if verbose is None:
torch.onnx.export(MyModule(), x, f, opset_version=self.opset_version)
else:
torch.onnx.export(
MyModule(), x, f, verbose=verbose, opset_version=self.opset_version
)
model = onnx.load(io.BytesIO(f.getvalue()))
model_strip = copy.copy(model)
onnx.helper.strip_doc_string(model_strip)
return model == model_strip
# test verbose=False (default)
self.assertTrue(is_model_stripped(io.BytesIO()))
# test verbose=True
self.assertFalse(is_model_stripped(io.BytesIO(), True))
# NB: remove this test once DataParallel can be correctly handled
def test_error_on_data_parallel(self):
model = torch.nn.DataParallel(torch.nn.ReflectionPad2d((1, 2, 3, 4)))
x = torch.randn(1, 2, 3, 4)
f = io.BytesIO()
with self.assertRaisesRegex(
ValueError,
"torch.nn.DataParallel is not supported by ONNX "
"exporter, please use 'attribute' module to "
"unwrap model from torch.nn.DataParallel. Try ",
):
torch.onnx.export(model, x, f, opset_version=self.opset_version)
@skipIfUnsupportedMinOpsetVersion(11)
def test_sequence_dim(self):
class Module(torch.nn.Module):
def forward(self, x, y):
return [x, y]
model = Module()
# Export with scripting to keep output as Sequence type.
# Tracing unpacks the list.
script_model = torch.jit.script(model)
x = torch.randn(2, 3)
# Case 1: dynamic axis
f = io.BytesIO()
y = torch.randn(2, 3)
torch.onnx.export(
script_model,
(x, y),
f,
opset_version=self.opset_version,
input_names=["x", "y"],
dynamic_axes={"y": [1]},
)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
loop_output_value_info_proto = onnx_model.graph.output[0]
ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info(
loop_output_value_info_proto.name, 1, [2, None]
)
self.assertEqual(loop_output_value_info_proto, ref_value_info_proto)
# Case 2: no dynamic axes.
f = io.BytesIO()
y = torch.randn(2, 3)
torch.onnx.export(script_model, (x, y), f, opset_version=self.opset_version)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
loop_output_value_info_proto = onnx_model.graph.output[0]
ref_value_info_proto = onnx.helper.make_tensor_sequence_value_info(
loop_output_value_info_proto.name, 1, [2, 3]
)
self.assertEqual(loop_output_value_info_proto, ref_value_info_proto)
def test_export_mode(self):
class MyModule(torch.nn.Module):
def forward(self, x):
y = x + 1
return y
model = MyModule()
x = torch.randn(10, 3, 128, 128)
f = io.BytesIO()
# set mode to in inference mode and export in training mode
model.eval()
old_state = model.training
torch.onnx.export(
model,
(x,),
f,
opset_version=self.opset_version,
training=torch.onnx.TrainingMode.TRAINING,
)
# verify that the model state is preserved
self.assertEqual(model.training, old_state)
# set mode to training mode and export in inference mode
model.train()
old_state = model.training
torch.onnx.export(
model,
(x,),
f,
opset_version=self.opset_version,
training=torch.onnx.TrainingMode.EVAL,
)
# verify that the model state is preserved
self.assertEqual(model.training, old_state)
def test_export_does_not_fail_on_frozen_scripted_module(self):
class Inner(torch.nn.Module):
def forward(self, x):
if x > 0:
return x
else:
return x * x
class Outer(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.inner = torch.jit.script(Inner())
def forward(self, x):
return self.inner(x)
x = torch.zeros(1)
# Freezing is only implemented in eval mode. So we need to call eval()
outer_module = Outer().eval()
module = torch.jit.trace_module(outer_module, {"forward": (x)})
# jit.freeze removes the training attribute in the module
module = torch.jit.freeze(module)
torch.onnx.export(module, (x,), io.BytesIO(), opset_version=self.opset_version)
@skipIfUnsupportedMinOpsetVersion(15)
def test_local_function(self):
class N(torch.nn.Module):
def __init__(self, prob):
super().__init__()
self.dropout = torch.nn.Dropout(prob)
def forward(self, x):
return self.dropout(x)
class M(torch.nn.Module):
def __init__(self, num_layers):
super().__init__()
self.num_layers = num_layers
self.lns = torch.nn.ModuleList(
[torch.nn.LayerNorm(3, eps=i) for i in range(num_layers)]
)
self.celu1 = torch.nn.CELU(1.0)
self.celu2 = torch.nn.CELU(2.0)
self.dropout = N(0.5)
def forward(self, x, y, z):
res1 = self.celu1(x)
res2 = self.celu2(y)
for ln in self.lns:
z = ln(z)
return res1 + res2, self.dropout(z)
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
# Export specified modules. Test against specifying modules that won't
# exist in the exported model.
# Model export in inference mode will remove dropout node,
# thus the dropout module no longer exist in graph.
f = io.BytesIO()
torch.onnx.export(
M(3),
(x, y, z),
f,
opset_version=self.opset_version,
export_modules_as_functions={
torch.nn.CELU,
torch.nn.Dropout,
torch.nn.LayerNorm,
},
)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
# Check function definition
funcs = onnx_model.functions
celu_funcs = [f for f in funcs if f.name == "CELU"]
self.assertEqual(len(celu_funcs), 1)
self.assertEqual(celu_funcs[0].domain, "torch.nn.modules.activation")
self.assertEqual(len(celu_funcs[0].attribute), 3)
ln_funcs = [f for f in funcs if f.name == "LayerNorm"]
self.assertEqual(len(ln_funcs), 1)
self.assertEqual(ln_funcs[0].domain, "torch.nn.modules.normalization")
self.assertEqual(len(ln_funcs[0].attribute), 3)
# Check local function nodes
nodes = onnx_model.graph.node
celu_ns = [n for n in nodes if n.op_type == "CELU"]
ln_ns = [n for n in nodes if n.op_type == "LayerNorm"]
self.assertEqual(len(celu_ns), 2)
self.assertEqual(celu_ns[0].domain, "torch.nn.modules.activation")
self.assertEqual(len(celu_ns[0].attribute), 3)
self.assertEqual(len(ln_ns), 3)
self.assertEqual(ln_ns[0].domain, "torch.nn.modules.normalization")
self.assertEqual(len(ln_ns[0].attribute), 3)
# Export specified modules.
f = io.BytesIO()
torch.onnx.export(
M(3),
(x, y, z),
f,
opset_version=self.opset_version,
export_modules_as_functions={torch.nn.CELU},
)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
funcs = onnx_model.functions
self.assertEqual(len(funcs), 1)
self.assertEqual(funcs[0].name, "CELU")
# Export with empty specified modules. Normal export.
f = io.BytesIO()
torch.onnx.export(
M(3),
(x, y, z),
f,
opset_version=self.opset_version,
export_modules_as_functions=set(),
)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
funcs = onnx_model.functions
self.assertEqual(len(funcs), 0)
# Export all modules. Should contain {M, CELU, LayerNorm}.
f = io.BytesIO()
torch.onnx.export(
M(3),
(x, y, z),
f,
opset_version=self.opset_version,
export_modules_as_functions=True,
)
onnx_model = onnx.load(io.BytesIO(f.getvalue()))
funcs = onnx_model.functions
self.assertEqual(len(funcs), 3)
@skipIfUnsupportedMinOpsetVersion(15)
def test_local_function_overloads(self):
class NWithOverloads(torch.nn.Module):
def forward(self, x, y=None, z=None):
if y is None:
return x + 1
elif z is None:
return x + y
else:
return x + y, x + z
class M(torch.nn.Module):
def __init__(self, num_layers):
super().__init__()
self.n = NWithOverloads()
def forward(self, x, y, z):
return self.n(x), self.n(x, y), self.n(x, y, z)