forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pytorch_onnx_onnxruntime.py
More file actions
12840 lines (10773 loc) · 442 KB
/
test_pytorch_onnx_onnxruntime.py
File metadata and controls
12840 lines (10773 loc) · 442 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
# Owner(s): ["module: onnx"]
from __future__ import annotations
import io
import itertools
import os
import unittest
from collections import OrderedDict
from typing import Dict, List, Optional, Tuple, Type, Union
import numpy as np
import onnx
import onnx_test_common
import parameterized
import torch
import torchvision
from model_defs import (
lstm_flattening_result,
rnn_model_with_packed_sequence,
word_language_model,
)
from pytorch_test_common import (
BATCH_SIZE,
RNN_BATCH_SIZE,
RNN_HIDDEN_SIZE,
RNN_INPUT_SIZE,
RNN_SEQUENCE_LENGTH,
skipDtypeChecking,
skipIfUnsupportedMaxOpsetVersion,
skipIfUnsupportedMinOpsetVersion,
skipIfUnsupportedOpsetVersion,
skipScriptTest,
skipShapeChecking,
skipTraceTest,
)
from torch import Tensor
from torch.nn.utils import rnn as rnn_utils
from torch.onnx import _constants, verification
from torch.testing._internal import common_utils
from torch.testing._internal.common_utils import skipIfNoLapack
# The min onnx opset version to test for
MIN_ONNX_OPSET_VERSION = 9
# The max onnx opset version to test for
MAX_ONNX_OPSET_VERSION = _constants.ONNX_MAX_OPSET
def _init_test_generalized_rcnn_transform():
min_size = 100
max_size = 200
image_mean = [0.485, 0.456, 0.406]
image_std = [0.229, 0.224, 0.225]
transform = torchvision.models.detection.transform.GeneralizedRCNNTransform(
min_size, max_size, image_mean, image_std
)
return transform
def _init_test_rpn():
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
rpn_anchor_generator = torchvision.models.detection.rpn.AnchorGenerator(
anchor_sizes, aspect_ratios
)
out_channels = 256
rpn_head = torchvision.models.detection.rpn.RPNHead(
out_channels, rpn_anchor_generator.num_anchors_per_location()[0]
)
rpn_fg_iou_thresh = 0.7
rpn_bg_iou_thresh = 0.3
rpn_batch_size_per_image = 256
rpn_positive_fraction = 0.5
rpn_pre_nms_top_n = dict(training=2000, testing=1000)
rpn_post_nms_top_n = dict(training=2000, testing=1000)
rpn_nms_thresh = 0.7
rpn_score_thresh = 0.0
rpn = torchvision.models.detection.rpn.RegionProposalNetwork(
rpn_anchor_generator,
rpn_head,
rpn_fg_iou_thresh,
rpn_bg_iou_thresh,
rpn_batch_size_per_image,
rpn_positive_fraction,
rpn_pre_nms_top_n,
rpn_post_nms_top_n,
rpn_nms_thresh,
score_thresh=rpn_score_thresh,
)
return rpn
def _construct_tensor_for_quantization_test(
shape: Tuple[int, ...],
offset: Optional[Union[int, float]] = None,
max_val: Optional[Union[int, float]] = None,
) -> Tensor:
"""Helper function to generate weights and test inputs in a deterministic way.
Due to difference in implementation details between PyTorch and ONNXRuntime, randomly generated
test data for quantization tests can be flaky. To help stablize the test, this helper function is
used to generate weights and test inputs in a deterministic way.
Args:
shape (Tuple[int]): Shape for tensor to construct.
offset (Optional[Union[int, float]]): Offset to be added to the generated tensor.
max_val (Optional[Union[int, float]]): If any element within tensor has a larger absolute value than
max_val, the tensor will be scaled by max_val / tensor.abs().max(). This step is done after
applying offset.
"""
tensor = torch.arange(np.prod(shape), dtype=torch.float).view(shape)
if offset is not None:
tensor = tensor + offset
if max_val is not None and tensor.abs().max() > max_val:
tensor = tensor * max_val / tensor.abs().max()
return tensor
def _parameterized_class_attrs_and_values(
min_opset_version: int, max_opset_version: int
):
attrs = ("opset_version", "is_script", "keep_initializers_as_inputs")
input_values = []
input_values.extend(itertools.product((7, 8), (True, False), (True,)))
# Valid opset versions are defined in torch/onnx/_constants.py.
# Versions are intentionally set statically, to not be affected by changes elsewhere.
if min_opset_version < 9:
raise ValueError("min_opset_version must be >= 9")
input_values.extend(
itertools.product(
range(min_opset_version, max_opset_version + 1),
(True, False),
(True, False),
)
)
return {"attrs": attrs, "input_values": input_values}
def _parametrize_rnn_args(arg_name):
options = {
"layers": {1: "unilayer", 3: "trilayer"},
"bidirectional": {True: "bidirectional", False: "forward"},
"initial_state": {True: "with_initial_state", False: "no_initial_state"},
"packed_sequence": {
0: "without_sequence_lengths",
1: "with_variable_length_sequences",
2: "with_batch_first_sequence_lengths",
},
"dropout": {0.2: "with_dropout", 0.0: "without_dropout"},
}
return {
"arg_str": arg_name,
"arg_values": options[arg_name].keys(),
"name_fn": lambda val: options[arg_name][val],
}
@parameterized.parameterized_class(
**_parameterized_class_attrs_and_values(
MIN_ONNX_OPSET_VERSION, MAX_ONNX_OPSET_VERSION
),
class_name_func=onnx_test_common.parameterize_class_name,
)
@common_utils.instantiate_parametrized_tests
class TestONNXRuntime(onnx_test_common._TestONNXRuntime):
def test_fuse_conv_bn1d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv1d(16, 33, 3, stride=2)
self.bn = torch.nn.BatchNorm1d(33)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(20, 16, 50, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn2d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv2d(
3, 2, kernel_size=1, stride=2, padding=3, bias=False
)
self.bn = torch.nn.BatchNorm2d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 2, 2, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn3d(self):
class Fuse(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv3d(
3, 2, (3, 5, 2), stride=(2, 1, 1), padding=(3, 2, 0), bias=False
)
self.bn = torch.nn.BatchNorm3d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 10, 50, 100, requires_grad=True)
self.run_test(model, (x,), rtol=1e-3, atol=1e-6)
def test_fuse_conv_in_block(self):
class Fuse(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv1d(
in_channels=5,
out_channels=5,
kernel_size=3,
stride=1,
padding=2,
dilation=1,
)
self.bn = torch.nn.BatchNorm1d(5)
def forward(self, x):
results_available = True
if x.sum() > -1:
results_available = False
if results_available:
x = self.conv(x)
x = self.bn(x)
return x
model = Fuse()
x = torch.randn(2, 5, 9, requires_grad=True)
self.run_test(
torch.jit.script(model),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 2]},
rtol=1e-3,
atol=1e-6,
)
def test_conv_tbc(self):
from torch.nn.modules.utils import _single
class ConvTBC(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding=0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = _single(kernel_size)
self.padding = _single(padding)
self.weight = torch.nn.Parameter(
Tensor(self.kernel_size[0], in_channels, out_channels)
)
self.bias = torch.nn.Parameter(Tensor(out_channels))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_normal_(self.weight)
torch.nn.init.zeros_(self.bias)
def conv_tbc(self, input):
return torch.conv_tbc(
input.contiguous(), self.weight, self.bias, self.padding[0]
)
def forward(self, input):
return self.conv_tbc(input)
in_channels = 3
out_channels = 5
kernel_size = 5
model = ConvTBC(in_channels, out_channels, kernel_size, padding=0)
x = torch.randn(10, 7, in_channels, requires_grad=True)
self.run_test(model, (x,), atol=1e-5)
def test_reshape_constant_fold(self):
class Reshape(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.register_buffer("weight", torch.ones(5))
def forward(self, x):
scale_1 = self.weight.reshape(1, -1, 1, 1)
return x * scale_1
x = torch.randn(4, 5)
self.run_test(Reshape(), (x,), rtol=1e-3, atol=1e-5)
def run_word_language_model(self, model_name):
ntokens = 50
emsize = 5
nhid = 5
nlayers = 5
dropout = 0.2
tied = False
batchsize = 5
if model_name == "GRU":
model = word_language_model.RNNModelWithTensorHidden(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
elif model_name == "LSTM":
model = word_language_model.RNNModelWithTupleHidden(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
else:
model = word_language_model.RNNModel(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
x = torch.arange(0, ntokens).long().view(-1, batchsize)
# Only support CPU version, since tracer is not working in GPU RNN.
self.run_test(model, (x, model.hidden))
def get_image(self, rel_path: str, size: Tuple[int, int]) -> Tensor:
from PIL import Image
from torchvision import transforms
data_dir = os.path.join(os.path.dirname(__file__), "assets")
path = os.path.join(data_dir, *rel_path.split("/"))
image = Image.open(path).convert("RGB").resize(size, Image.BILINEAR)
return transforms.ToTensor()(image)
def get_test_images(self) -> Tuple[List[Tensor], List[Tensor]]:
return (
[self.get_image("grace_hopper_517x606.jpg", (100, 320))],
[self.get_image("rgb_pytorch.png", (250, 380))],
)
def test_paste_mask_in_image(self):
masks = torch.rand(10, 1, 26, 26)
boxes = torch.rand(10, 4)
boxes[:, 2:] += torch.rand(10, 2)
boxes *= 50
o_im_s = (100, 100)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out = paste_masks_in_image(masks, boxes, o_im_s)
jit_trace = torch.jit.trace(
paste_masks_in_image,
(masks, boxes, [torch.tensor(o_im_s[0]), torch.tensor(o_im_s[1])]),
)
out_trace = jit_trace(
masks, boxes, [torch.tensor(o_im_s[0]), torch.tensor(o_im_s[1])]
)
assert torch.all(out.eq(out_trace))
masks2 = torch.rand(20, 1, 26, 26)
boxes2 = torch.rand(20, 4)
boxes2[:, 2:] += torch.rand(20, 2)
boxes2 *= 100
o_im_s2 = (200, 200)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out2 = paste_masks_in_image(masks2, boxes2, o_im_s2)
out_trace2 = jit_trace(
masks2, boxes2, [torch.tensor(o_im_s2[0]), torch.tensor(o_im_s2[1])]
)
assert torch.all(out2.eq(out_trace2))
def test_heatmaps_to_keypoints(self):
maps = torch.rand(10, 1, 26, 26)
rois = torch.rand(10, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out = heatmaps_to_keypoints(maps, rois)
jit_trace = torch.jit.trace(heatmaps_to_keypoints, (maps, rois))
out_trace = jit_trace(maps, rois)
assert torch.all(out[0].eq(out_trace[0]))
assert torch.all(out[1].eq(out_trace[1]))
maps2 = torch.rand(20, 2, 21, 21)
rois2 = torch.rand(20, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out2 = heatmaps_to_keypoints(maps2, rois2)
out_trace2 = jit_trace(maps2, rois2)
assert torch.all(out2[0].eq(out_trace2[0]))
assert torch.all(out2[1].eq(out_trace2[1]))
def test_word_language_model_RNN_TANH(self):
self.run_word_language_model("RNN_TANH")
def test_word_language_model_RNN_RELU(self):
self.run_word_language_model("RNN_RELU")
@skipScriptTest() # scripting prim::unchecked_cast prim::setattr
def test_word_language_model_LSTM(self):
self.run_word_language_model("LSTM")
def test_word_language_model_GRU(self):
self.run_word_language_model("GRU")
def test_index_1d(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_1dimslice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_sliceint(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_neg_slice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:-1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_mask(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.uint8)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.bool)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_data(self):
class Data(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.new_zeros(x.data.size())
x = torch.randn(3, 4)
self.run_test(Data(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Data(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_mask_nd(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[input > 0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipScriptTest()
def test_dict(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(
x_in[list(x_in.keys())[0]], list(x_in.keys())[0]
)
return x_out
x = {torch.tensor(1.0): torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x,))
@skipScriptTest()
def test_dict_str(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(x_in["test_key_in"], 2.0)
return x_out
x = {"test_key_in": torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x,))
@skipScriptTest() # User-defined class not supported
def test_dict_output(self):
class DictModelOutput(OrderedDict):
tensor_out: Tensor
tuple_out: Optional[Tuple[Tensor]] = None
list_out: Optional[List[Tensor]] = None
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return DictModelOutput(
tensor_out=a,
tuple_out=(b, c),
list_out=[d],
)
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, (b, c), d
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_nested_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, ((b,), (c, d))
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: Tuple[Tensor, Tensor]):
return a
x = (torch.randn(3, 4), torch.randn(4, 3))
self.run_test(TupleModel(), input_args=(x,))
def test_tuple_primitive_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: Tuple[int, Tensor], b):
return a[0], a[1] + b
x = (3, torch.randn(4, 3))
y = torch.randn(4, 3)
self.run_test(TupleModel(), input_args=(x, y))
def test_nested_tuple_input(self):
class NestedTupleModel(torch.nn.Module):
def forward(self, a, b: Tuple[Tensor, Tuple[Tensor, Tensor]]):
return a + b[0] + b[1][0] + b[1][1]
x = torch.randn(4, 5)
y = (torch.randn(4, 5), (torch.randn(1, 5), torch.randn(4, 1)))
self.run_test(NestedTupleModel(), input_args=(x, y))
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_none(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = None,
z: Optional[Tensor] = None,
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = Model()
# Without kwargs dict.
self.run_test(model, (x, y, None))
self.run_test(model, (x, None, z))
# With kwargs dict.
self.run_test(model, (x,), {"y": y, "z": None})
self.run_test(model, (x,), {"y": None, "z": z})
self.run_test(model, (x,), {"z": z})
self.run_test(model, (x,), {"y": y})
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = torch.ones(2, 3),
z: Optional[Tensor] = torch.zeros(2, 3),
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, y, None))
self.run_test(model, (x, None, z))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = torch.ones(2, 3),
z: Optional[Tensor] = torch.zeros(2, 3),
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = torch.jit.script(Model())
self.run_test(model, (x, y, z), input_names=("x", "y", "z"))
self.run_test(model, (x,), {"y": y, "z": z}, input_names=("x", "y", "z"))
# Requires input_names to be set so that we can feed the inputs properly into ORT.
# TODO: Export default values as ONNX initializers, then this should not raise.
# https://msdata.visualstudio.com/Vienna/_workitems/edit/969268
# Default values are accessible via FunctionSchema.
with self.assertRaisesRegex(
ValueError, "Model requires 3 inputs. Input Feed contains 2"
):
self.run_test(model, (x,), {"y": y}, input_names=("x", "y"))
for example_inputs, example_kwargs in (
((x, y, None), {}),
((x, None, z), {}),
((x,), {"y": y, "z": None}),
((x,), {"y": None, "z": z}),
):
with self.assertRaisesRegex(
ValueError, "args contained 1 None's after flattening."
):
self.run_test(
model, example_inputs, example_kwargs, input_names=("x", "y", "z")
)
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_none(self):
class Model(torch.nn.Module):
def forward(self, x: Optional[Tensor] = None, y: Optional[Tensor] = None):
if x is not None:
return x
if y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(
model,
(),
{"x": x, "y": None},
# y disappears in tracing.
input_names=("x",),
)
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x: Optional[Tensor] = torch.ones(2, 3),
y: Optional[Tensor] = torch.zeros(2, 3),
):
if x is not None:
return x
elif y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
y = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(model, (None, y))
# tracing means y is never used so it's removed from the exported model inputs,
# and we fail when trying to run ORT.
with self.assertRaisesRegex(ValueError, "got too many positional inputs"):
self.run_test(model, (x, y))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x: Optional[Tensor] = torch.ones(2, 3),
y: Optional[Tensor] = torch.zeros(2, 3),
):
if x is not None:
return x
elif y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
y = torch.randn(2, 3)
model = torch.jit.script(Model())
# TODO: Export default values as ONNX initializers, then this should not raise.
# https://msdata.visualstudio.com/Vienna/_workitems/edit/969268
# Default values are accessible via FunctionSchema.
with self.assertRaisesRegex(
ValueError, "Model requires 2 inputs. Input Feed contains 1"
):
self.run_test(model, (x,))
self.run_test(model, (), {"y": y})
self.run_test(model, (x, y))
self.run_test(model, (), {"x": x, "y": y}, input_names=("x", "y"))
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional(self):
class Model(torch.nn.Module):
def forward(self, x, y: Optional[Tensor]):
if y is not None:
return x + y
return x
x = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(model, (x, x))
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional(self):
class Model(torch.nn.Module):
def forward(self, x, y: Tuple[Optional[Tensor], Optional[Tensor]]):
if y[0] is not None:
return x + y[0]
if y[1] is not None:
return x + y[1]
return x
x = torch.randn(2, 3)
y1 = torch.randn(2, 3)
self.run_test(Model(), (x, (None, y1)))
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Tuple[Optional[Tensor], Optional[Tensor]] = (
torch.zeros(2, 3),
torch.zeros(2, 3),
),
):
y0, y1 = y
if y0 is not None:
return x + y0
if y1 is not None:
return x + y1
return x
x = torch.randn(2, 3)
y1 = torch.randn(2, 3)
self.run_test(Model(), (x, (None, y1)))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Tuple[Optional[Tensor], Optional[Tensor]] = (
torch.zeros(2, 3),
torch.zeros(2, 3),
),
):
y0, y1 = y
if y0 is not None:
return x + y0
if y1 is not None:
return x + y1
return x
x = torch.randn(2, 3)
y0 = torch.randn(2, 3)
y1 = torch.randn(2, 3)
model = torch.jit.script(Model())
with self.assertRaisesRegex(
ValueError, "args contained 1 None's after flattening."
):
self.run_test(model, (x, (None, y1)))
self.run_test(model, (x, (y0, y1)))
# export succeeds, but running ORT through run_test would fail because the exported model
# has the inputs flattened into 3 inputs.
torch.onnx.export(
model, (x, {"y": (y0, y1)}), io.BytesIO(), opset_version=self.opset_version
)
def test_primitive_input_integer(self):
class Model(torch.nn.Module):
def forward(self, x: int, y):
return x + y
x = 3
y = torch.randint(10, (2, 3, 4))
self.run_test(Model(), (x, y))
@skipDtypeChecking
def test_primitive_input_floating(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: float, y):
return x + y
x = 3.0
y = torch.randn(2, 3, 4)
self.run_test(Model(), (x, y))
def test_primitive_input_bool(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, flag: bool, x, y):
if flag:
return x
else:
return y
flag = True
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(torch.jit.script(Model()), (flag, x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cste_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.zeros(x.size(0)), torch.ones(
(x.size(1), x.size(0)), dtype=torch.int64
)
x = torch.randn(3, 4)
self.run_test(MyModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(MyModel(), x, remained_onnx_input_idx=[])
def test_scalar_tensor(self):
class test(torch.nn.Module):
def forward(self, input):
return torch.scalar_tensor(input.size(0)), torch.scalar_tensor(
input.size(1), dtype=torch.int64
)
x = torch.randn(2, 3, 4)
y = torch.randn(7, 8, 9)
model = test()
self.run_test(
model,
x,
additional_test_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2]},
)
def test_tensor(self):
class ScalarInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1])
x = torch.randn(3, 4)
self.run_test(
ScalarInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(ScalarInputModel(), x, remained_onnx_input_idx=[])
class TensorInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], input.shape[1]])
x = torch.randn(3, 4)
self.run_test(
TensorInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(TensorInputModel(), x, remained_onnx_input_idx=[])
class FloatInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([float(input)])
x = torch.randn(1)
self.run_test(FloatInputModel(), x)
class InputWithDtypeModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1], dtype=torch.long)
x = torch.randn(3, 4)
self.run_test(
InputWithDtypeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(InputWithDtypeModel(), x, remained_onnx_input_idx=[])
class MixedInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], int(input)])
x = torch.randn(1)
self.run_test(MixedInputModel(), x)
def test_hardtanh(self):
model = torch.nn.Hardtanh(-1.5, 2.5)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardtanh_script_with_default_values(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardtanh(x)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardswish(self):
model = torch.nn.Hardswish()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# Testing edge cases
x = torch.tensor(3).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-3).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardswish_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardswish(x)
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardsigmoid(self):
model = torch.nn.Hardsigmoid()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# corner cases