forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_misc.py
5334 lines (4343 loc) · 168 KB
/
test_misc.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: dynamo"]
import abc
import collections
import copy
import dataclasses
import dis
import enum
import logging
import math
import operator
import os
import sys
import typing
import unittest
import unittest.mock as mock
import weakref
from unittest.mock import patch
import numpy as np
import torch
import torch._dynamo.test_case
import torch._dynamo.testing
import torch.onnx.operators
from torch._C import FileCheck
from torch._dynamo import bytecode_transformation, graph_break
from torch._dynamo.output_graph import OutputGraph
from torch._dynamo.testing import (
CompileCounter,
requires_static_shapes,
same,
unsupported,
)
from torch._dynamo.utils import CompileProfiler, ifunspec
from torch.ao.quantization import MinMaxObserver
from torch.ao.quantization.fake_quantize import FakeQuantize
from torch.ao.quantization.qconfig import QConfig
from torch.ao.quantization.quantize_fx import prepare_qat_fx
from torch.autograd.profiler import _enable_dynamo_cache_lookup_profiler
from torch.nn import functional as F
from torch.testing._internal.common_cuda import (
PLATFORM_SUPPORTS_FUSED_SDPA,
SM80OrLater,
)
from torch.testing._internal.common_utils import freeze_rng_state
from torch.testing._internal.jit_utils import JitTestCase
mytuple = collections.namedtuple("mytuple", ["a", "b", "ab"])
def my_custom_function(x):
return x + 1
class MyPickledModule(torch.nn.Module):
def __init__(self, z):
super().__init__()
self.z = z
def forward(self, x, y):
return x * x * x + y + self.z
# These are used for test_{cond/map}_with_quantization
default_symmetric_fake_quant = FakeQuantize.with_args(
observer=MinMaxObserver, qscheme=torch.per_tensor_symmetric, dtype=torch.quint8
)
default_weight_symmetric_fake_quant = FakeQuantize.with_args(
observer=MinMaxObserver, qscheme=torch.per_tensor_symmetric, dtype=torch.qint8
)
uniform_qconfig_8bit = QConfig(
activation=default_symmetric_fake_quant,
weight=default_weight_symmetric_fake_quant.with_args,
)
qconfig_dict = {"object_type": [(torch.nn.Linear, uniform_qconfig_8bit)]}
class MiscTests(torch._dynamo.test_case.TestCase):
def test_boolarg(self):
def boolarg(aa, bb, flag):
if flag:
return aa - bb
else:
return bb - aa
a = torch.randn(10, 10)
b = torch.randn(10, 10)
correct1 = boolarg(a, b, True)
correct2 = boolarg(a, b, False)
correct3 = boolarg(a, b, None)
counter = CompileCounter()
opt_boolarg = torch._dynamo.optimize_assert(counter)(boolarg)
val1 = opt_boolarg(a, b, True)
val2 = opt_boolarg(a, b, False)
val3 = opt_boolarg(a, b, None)
val4 = opt_boolarg(a, b, True)
self.assertTrue(same(val1, correct1))
self.assertTrue(same(val2, correct2))
self.assertTrue(same(val3, correct3))
self.assertTrue(same(val4, correct1))
self.assertEqual(counter.frame_count, 3)
def test_callpacked(self):
def call_packed(args):
a, b, c = args
return a - b * c
counter = CompileCounter()
a = torch.randn(10, 10)
b = torch.randn(10, 10)
c = torch.randn(10, 10)
correct = call_packed([a, b, c])
opt_call_packed = torch._dynamo.optimize_assert(counter)(call_packed)
val1 = opt_call_packed([a, b, c])
val2 = opt_call_packed((a, b, c))
val3 = opt_call_packed([a, b, c])
val4 = opt_call_packed((a, b, c))
self.assertTrue(same(val1, correct))
self.assertTrue(same(val2, correct))
self.assertTrue(same(val3, correct))
self.assertTrue(same(val4, correct))
self.assertEqual(counter.frame_count, 2)
def test_raises(self):
def fn(a, b, c, cls):
x = a + b - c * 10
raise cls(str(x))
counter = CompileCounter()
a = torch.randn(10, 10)
b = torch.randn(10, 10)
c = torch.randn(10, 10)
opt_fn = torch._dynamo.optimize(counter)(fn)
self.assertRaises(AssertionError, lambda: opt_fn(a, b, c, AssertionError))
self.assertEqual(counter.frame_count, 1)
self.assertEqual(counter.op_count, 3)
def test_inplace(self):
def inplace1(a, b):
o = torch.empty((10, 10))
o.copy_(a)
o -= b
return o
torch._dynamo.testing.standard_test(self, inplace1, 2, expected_ops=3)
def test_unpack4(self):
def unpack4(a, b):
a = a[:5, :]
b = b[:5, :]
x, y = a.size()
o = torch.empty((x, y))
o.copy_(a / b)
return o
torch._dynamo.testing.standard_test(
self, unpack4, 2, expected_ops=5, expected_ops_dynamic=8
)
def test_unpack5(self):
def unpack5(a, b):
a = a[:5, :]
b = b[:5, :]
x, y = a.shape
o = torch.empty((x, y))
o.copy_(a / b)
return o
torch._dynamo.testing.standard_test(
self, unpack5, 2, expected_ops=5, expected_ops_dynamic=8
)
def test_matmul1(self):
def matmul_op1(a, b):
return a @ b
# TODO(jansel): FX doesn't support this, should add upstream support
torch._dynamo.testing.standard_test(self, matmul_op1, 2, expected_ops=1)
def test_int_shape_binops(self):
def fn(x):
# Test reversal by putting int arg first.
y = 15 - x.shape[0]
y = 4 + y
y = 5 * y
y = 2 % y
y = 3**y
y = 10 // y
y = pow(2, y)
y = 10 / y
return x + y
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=1, expected_ops_dynamic=11
)
def test_shape_int_inplace_binops(self):
def fn(x):
p = x.shape[0]
p += 2
p -= 2
p **= 2
p /= 2
p *= 2
p //= 2
p %= 2
return x + p
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=1, expected_ops_dynamic=10
)
def test_int_shape_inplace_binops(self):
def fn(x):
p = x.shape[0]
# Test reversal by putting constant first
y = 2
y += p
y = 2
y -= p
y = 2
y **= p
y = 2
y /= p
y = 2
y *= p
y = 2
y //= p
y = 2
y %= p
return x + y
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=1, expected_ops_dynamic=10
)
def test_int_int_comparisons(self):
def fn(x):
if 2 != 2:
out = 1
elif 2 < 1:
out = 1
elif 1 > 2:
out = 1
elif 1 >= 2:
out = 1
elif 2 <= 1:
out = 1
elif 2 == 2:
out = 2
else:
out = 1
return x + out
torch._dynamo.testing.standard_test(self, fn, 1, expected_ops=1)
def test_shape_int_comparisons(self):
def fn(x):
a = x.shape[0]
# Ensure support for constant on right side
if a != 10:
out = 1
elif a < 2:
out = 1
elif a > 12:
out = 1
elif a >= 12:
out = 1
elif a <= 2:
out = 1
elif a == 10:
out = 2
else:
out = 1
return x + out
# expect for dynamic: size, index, 6 comparison ops, add
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=1, expected_ops_dynamic=9
)
def test_int_shape_comparisons(self):
def fn(x):
a = x.shape[0]
# Ensure support for constant on left side
if 10 != a:
out = 1
elif 12 < a:
out = 1
elif 2 > a:
out = 1
elif 2 >= a:
out = 1
elif 12 <= a:
out = 1
elif 10 == a:
out = 2
else:
out = 1
return x + out
# expect for dynamic: size, index, 6 comparison ops, add
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=1, expected_ops_dynamic=9
)
def test_param_shape_binops(self):
class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.param = torch.nn.Parameter(torch.randn(15))
def forward(self, x):
# Test reversal by putting param shape arg first.
p = self.param.shape[0]
y = p - x.shape[0]
y = p + y
y = p * y
y = p % y
y = p**y
y = p // y
y = pow(p, y)
y = p / y
return x + y
counts = torch._dynamo.testing.CompileCounter()
mod = MyModule()
optimized_mod = torch._dynamo.optimize(counts, nopython=True)(mod)
x = torch.randn(3)
ref = mod(x)
res = optimized_mod(x)
self.assertTrue(same(ref, res))
self.assertEqual(counts.frame_count, 1)
expected_op_count = 13 if torch._dynamo.testing.config.dynamic_shapes else 1
self.assertEqual(counts.op_count, expected_op_count)
def test_user_defined_binop(self):
class MyClass:
def __init__(self, value):
self.value = value
def __radd__(self, other):
return self.value + other
def fn(x, c):
y = x.shape[0] + c
return x + y
counts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(counts)(fn)
x = torch.randn(3)
c = MyClass(4)
ref = fn(x, c)
res = opt_fn(x, c)
self.assertTrue(same(ref, res))
self.assertEqual(counts.frame_count, 1)
expected_op_count = 4 if torch._dynamo.testing.config.dynamic_shapes else 1
self.assertEqual(counts.op_count, expected_op_count)
def test_compare_shapes_eq(self):
def compare_shapes(a, b, to_list):
x = list(a.unsqueeze(-1).shape) if to_list else a.shape
y = list(b.unsqueeze(-1).shape) if to_list else b.shape
if x == y:
return a + 1
else:
return a + 2
# Test both ListVariable and ShapeVariable
torch._dynamo.testing.standard_test(
self, lambda a, b: compare_shapes(a, b, to_list=True), 2
)
torch._dynamo.testing.standard_test(
self, lambda a, b: compare_shapes(a, b, to_list=False), 2
)
def test_compare_shapes_tuple_eq(self):
def compare_shapes(a, b):
x = tuple(a.unsqueeze(-1).shape)
y = tuple(b.unsqueeze(-1).shape)
if x == y:
return a + 1
else:
return a + 2
torch._dynamo.testing.standard_test(self, lambda a, b: compare_shapes(a, b), 2)
def test_compare_shapes_tuple_neq(self):
def compare_shapes(a, b):
x = tuple(a.unsqueeze(-1).shape)
y = tuple(b.unsqueeze(-1).shape)
if x != y:
return a + 1
else:
return a + 2
torch._dynamo.testing.standard_test(self, lambda a, b: compare_shapes(a, b), 2)
def test_compare_shapes_neq(self):
def compare_shapes(a, b, to_list):
x = list(a.unsqueeze(-1).shape) if to_list else a.shape
y = list(b.unsqueeze(-1).shape) if to_list else b.shape
if x != y:
return a + 1
else:
return a + 2
# Test both ListVariable and ShapeVariable
torch._dynamo.testing.standard_test(
self, lambda a, b: compare_shapes(a, b, to_list=True), 2
)
torch._dynamo.testing.standard_test(
self, lambda a, b: compare_shapes(a, b, to_list=False), 2
)
@patch.object(torch._dynamo.config, "dynamic_shapes", True)
def test_compare_shapes_with_constant(self):
def compare_shapes(a):
x = a.shape
if x[0] != 3:
return a * 4
return a * 3
guard_failure = None
def guard_failures(failure):
nonlocal guard_failure
guard_failure = failure
opt_fn = torch._dynamo.optimize(
"eager", nopython=True, guard_fail_fn=guard_failures
)(compare_shapes)
opt_fn(torch.randn([3, 4]))
opt_fn(torch.randn([4, 3]))
self.assertEqual(guard_failure.reason, "a.size()[0] == 3")
def test_builtin_isinstance(self):
def fn(x):
t = torch.arange(1, 3)
a = isinstance(x, torch.Tensor)
b = isinstance(t, torch.Tensor)
c = isinstance(x, int)
d = isinstance(3, int)
e = isinstance([1, 2, 3], list)
f = isinstance({"foo": 1, "bar": 2}, dict)
res = [a, b, c, d, e, f]
# Can't run yet due to other unimplemented instructions
# res += [isinstance(torch.nn.LazyLinear(2, 3), torch.nn.Linear)]
return res
torch._dynamo.testing.standard_test(self, fn, 1, expected_ops=1)
def test_fold(self):
def fn(a):
return a + math.sqrt(63)
torch._dynamo.testing.standard_test(self, fn, 1, expected_ops=1)
def test_shape_unpack(self):
def fn(x):
a, b = x.size()
return x * b
i = torch.randn(5, 10)
r1 = fn(i)
opt_fn = torch._dynamo.optimize("eager")(fn)
r2 = opt_fn(i)
self.assertTrue(same(r1, r2))
def test_tensor_iter(self):
def fn(x):
for y in x:
y.add_(1.0)
return y
# expect extra size node for dynamic
torch._dynamo.testing.standard_test(
self, fn, 1, expected_ops=20, expected_ops_dynamic=21
)
def test_empty_list(self):
def fn(x, ll):
if len(ll) == 0 and not ll and ll is not None:
return x + 1
i = torch.randn(5, 10)
r1 = fn(i, [])
opt_fn = torch._dynamo.optimize("eager")(fn)
r2 = opt_fn(i, [])
r3 = opt_fn(i, tuple())
self.assertTrue(same(r1, r2))
self.assertTrue(same(r1, r3))
def test_min_max_over_iterable(self):
def get_test_fn(func):
def _fn(a, b, func=func):
# try all of list, iterator, tuple, vararg.
lst = [a.shape[0] + 1, 8, a.shape[0]]
x = func(lst)
y = func(iter(lst))
z = func(tuple(lst))
w = func(*lst)
return a + (x + y + z + w)
return _fn
# expect for dynamic:
# 2 * (size, getitem) ops +
# 1 add op +
# 4 * 2 min / max ops +
# 4 final add ops = 17
torch._dynamo.testing.standard_test(
self, get_test_fn(func=min), 2, expected_ops=1, expected_ops_dynamic=17
)
torch._dynamo.testing.standard_test(
self, get_test_fn(func=max), 2, expected_ops=1, expected_ops_dynamic=17
)
def test_config_obj(self):
class Cfg:
def __init__(self):
self.val = 0.5
self.count = 3
def fn(x, cfg):
for i in range(cfg.count):
x = x + cfg.val
return x
cfg1 = Cfg()
cfg1.val = 1.0
cfg2 = Cfg()
v = torch.zeros(1)
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
v = opt_fn(v, cfg1) # 3
v = opt_fn(v, cfg2) # 4.5
cfg2.count = 1
v = opt_fn(v, cfg2) # 5
cfg2.val = 2.0
v = opt_fn(v, cfg2) # 7
self.assertEqual(v[0], 7)
self.assertEqual(cnts.op_count, 8)
def test_config_getattr_default(self):
class Cfg:
def __init__(self):
self.val = 0.5
self.count = 10
def fn(x, cfg):
if getattr(cfg, "just_add_7", False):
return x + 7
for i in range(cfg.count):
x = x + cfg.val
return x
cfg1 = Cfg()
v = torch.zeros(1)
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(v, cfg1)[0], 5)
self.assertEqual(opt_fn(v, cfg1)[0], 5)
cfg1.just_add_7 = True
self.assertEqual(opt_fn(v, cfg1)[0], 7)
self.assertEqual(opt_fn(v, cfg1)[0], 7)
cfg1.just_add_7 = False
self.assertEqual(opt_fn(v, cfg1)[0], 5)
self.assertEqual(opt_fn(v, cfg1)[0], 5)
self.assertEqual(cnts.frame_count, 3)
def test_size_input(self):
def fn(x, s):
a, b = s
return x + (a - b)
v = torch.zeros(10, 20)
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(v, v.size())[0, 0], -10)
self.assertEqual(opt_fn(v, (10, 20))[0, 0], -10)
self.assertEqual(opt_fn(v, [10, 20])[0, 0], -10)
# One recompile per differing input type
self.assertEqual(cnts.frame_count, 3)
def test_cell_output1(self):
out = None
def fn(a, b):
nonlocal out
out = a + b * 10
v = torch.Tensor([100])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertIsNone(opt_fn(v, v))
self.assertEqual(out[0], 1100)
self.assertEqual(cnts.op_count, 2)
def test_cell_output2(self):
out = None
def fn(a, b):
nonlocal out
c = unsupported(a, b)
out = a + b * 10 + c
v = torch.Tensor([100])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertIsNone(opt_fn(v, v))
self.assertEqual(out[0], 1200)
self.assertEqual(cnts.op_count, 3)
def test_return_nested_function(self):
out = None
def fn(a, b):
nonlocal out
c = a + b
d = a + 1.0
def fn2(f: int = 7, g: float = 9.0):
nonlocal out
out = a + b * 10
return c * f - d * g
return fn2
v1 = torch.Tensor([100])
v2 = torch.Tensor([200])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
opt_fn_ret = torch._dynamo.optimize(cnts)(opt_fn(v1, v2))
self.assertEqual(opt_fn_ret(1.5)[0], -459)
self.assertEqual(out[0], 2100)
self.assertEqual(cnts.frame_count, 2)
self.assertEqual(cnts.op_count, 7)
def test_tensor_dict1(self):
def fn(inputs):
return inputs["a"] - inputs["b"] * 1.5
v1 = torch.Tensor([100])
v2 = torch.Tensor([200])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn({"a": v1, "b": v2})[0], -200)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
def test_tensor_dict2(self):
def fn1(inputs):
total = torch.zeros(1)
for k, v in inputs.items():
total += v
return total
def fn2(inputs):
total = torch.zeros(1)
for v in inputs.values():
total += v
return total
def fn3(inputs):
total = torch.zeros(1)
for k in inputs.keys():
total += inputs[k]
return total
v1 = torch.Tensor([100])
v2 = torch.Tensor([200])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn1 = torch._dynamo.optimize(cnts)(fn1)
opt_fn2 = torch._dynamo.optimize(cnts)(fn2)
opt_fn3 = torch._dynamo.optimize(cnts)(fn3)
self.assertEqual(opt_fn1({"a": v1, "b": v2})[0], 300)
self.assertEqual(opt_fn2({"a": v1, "b": v2})[0], 300)
self.assertEqual(opt_fn3({"a": v1, "b": v2})[0], 300)
self.assertEqual(cnts.frame_count, 3)
self.assertEqual(cnts.op_count, 9)
def test_dictcomp(self):
def fn1(inputs):
return {k: v + 1 for k, v in inputs.items()}
v1 = torch.Tensor([100])
v2 = torch.Tensor([200])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn1 = torch._dynamo.optimize(cnts)(fn1)
self.assertEqual(opt_fn1({"a": v1, "b": v2})["a"], 101)
self.assertEqual(opt_fn1({"a": v1, "b": v2})["b"], 201)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
def test_listcomp(self):
def fn2(inputs):
return torch.sum(torch.cat([v + 1 for k, v in inputs.items()], 0))
v1 = torch.Tensor([100])
v2 = torch.Tensor([200])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn2 = torch._dynamo.optimize(cnts)(fn2)
self.assertEqual(opt_fn2({"a": v1, "b": v2}), 302)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 4)
def test_is_floating_point(self):
def fn(a, b):
x = a + 1.0
if torch.is_floating_point(b):
x = x + b
return x + 2.0
return torch._dynamo.testing.standard_test(self, fn=fn, nargs=2, expected_ops=3)
def test_is_floating_point2(self):
def fn(a, b):
x = a + 1.0
if b.is_floating_point():
x = x + b
return x + 2.0
return torch._dynamo.testing.standard_test(self, fn=fn, nargs=2, expected_ops=3)
def test_is_tensor(self):
def fn(a, b):
x = a + 1.0
if torch.is_tensor(b):
x = x + b
return x + 2.0
return torch._dynamo.testing.standard_test(self, fn=fn, nargs=2, expected_ops=3)
def test_is_tensor2(self):
def fn(x):
if torch.is_tensor(x):
return x + 1
else:
return torch.ones([2, 3])
x1 = {"input": torch.rand(2, 3)}
x2 = torch.rand(2, 3)
ref1 = fn(x1)
ref2 = fn(x2)
opt_fn = torch._dynamo.optimize("eager")(fn)
res1 = opt_fn(x1)
res2 = opt_fn(x2)
self.assertEqual(ref1, res1)
self.assertEqual(ref2, res2)
def test_numel(self):
def fn(a):
return (a + a.numel() + torch.numel(a), a + a.nelement())
return torch._dynamo.testing.standard_test(
self, fn=fn, nargs=1, expected_ops=3, expected_ops_dynamic=6
)
def test_pair(self):
def fn(a):
return (
torch.zeros(torch.nn.modules.utils._pair(a.size()))
+ a
+ torch.ones(torch.nn.modules.utils._ntuple(3)(3)).sum()
)
return torch._dynamo.testing.standard_test(
self, fn=fn, nargs=1, expected_ops=5, expected_ops_dynamic=8
)
@patch.object(torch._dynamo.config, "dynamic_shapes", True)
@patch.object(torch._dynamo.config, "capture_scalar_outputs", True)
def test_tensor_item_capture(self):
def fn(a, b):
return (a + b).sum().item()
v1 = torch.randn((10, 10))
v2 = torch.randn((10, 10))
correct = fn(v1, v2)
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize((cnts))(fn)
self.assertEqual(opt_fn(v1, v2), correct)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 3)
@patch.object(torch._dynamo.config, "dynamic_shapes", True)
@patch.object(torch._dynamo.config, "capture_scalar_outputs", False)
def test_tensor_item_no_capture(self):
def fn(a, b):
return (a + b).sum().item()
v1 = torch.randn((10, 10))
v2 = torch.randn((10, 10))
correct = fn(v1, v2)
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize((cnts))(fn)
self.assertEqual(opt_fn(v1, v2), correct)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
def test_namedtuple1(self):
def fn(a, b):
tmp = mytuple(a, b, a + b)
return mytuple(tmp.a, tmp[1], tmp.ab + b)
v1 = torch.Tensor([10])
v2 = torch.Tensor([20])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(v1, v2).ab, 50)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
def test_namedtuple2(self):
def fn(packed):
a, b, c = packed
if hasattr(packed, "b"):
b = packed.b + 1
c = packed[2]
return a + b + c
v1 = torch.Tensor([1])
v2 = torch.Tensor([2])
v3 = torch.Tensor([3])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(mytuple(v1, v2, v3))[0], 7)
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 3)
def test_namedtuple3(self):
def fn(x, packed):
if isinstance(packed, mytuple):
return x + 1
else:
return x - 1
x = torch.rand([2, 3])
packed = mytuple(1, 2, 3)
ref = fn(x, packed)
opt_fn = torch._dynamo.optimize("eager")(fn)
res = opt_fn(x, packed)
self.assertTrue(same(ref, res))
def test_range_input(self):
def fn(a, rng):
x = a
for i in rng:
x = x + i
return x
def fn1(a):
return fn(a, rng=range(3))
return torch._dynamo.testing.standard_test(
self, fn=fn1, nargs=1, expected_ops=3
)
def test_range_with_shape(self):
def fn(a):
for i in range(1, a.shape[0]):
a += 1
return a
# expect 1 more op (size call) for dynamic
return torch._dynamo.testing.standard_test(
self, fn=fn, nargs=1, expected_ops=9, expected_ops_dynamic=10
)
def test_no_grad(self):
def fn1(a, b):
x = a + 1
# redundant no_grad should get ignored
with torch.no_grad():
x = x + b
x = x + 2
return x
def fn2(a, b):
x = a + 1
with torch.set_grad_enabled(False):
x = x + b
x = x + 2
return x
def fn3(a, b):
x = a + 1
with torch.enable_grad():
x = x + b
x = x + 2
return x
def fn4(a, b):
x = a + 1
with torch.set_grad_enabled(True):
if torch.is_grad_enabled():
x = x + b
x = x + 2
return x
with torch.no_grad():
torch._dynamo.testing.standard_test(self, fn=fn1, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn2, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn3, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn4, nargs=2, expected_ops=5)
with torch.enable_grad():
torch._dynamo.testing.standard_test(self, fn=fn1, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn2, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn3, nargs=2, expected_ops=5)
torch._dynamo.testing.standard_test(self, fn=fn4, nargs=2, expected_ops=5)
def test_grad_mode_guard(self):
def fn(a, b):
prev_grad = torch.is_grad_enabled()
torch.set_grad_enabled(False)
a = a + 1
a.tolist() # graph break
ret = a + b
torch.set_grad_enabled(prev_grad)
return ret
a = torch.randn([3, 4])
b = torch.randn([3, 4])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
for _ in range(10):
opt_fn(a, b)
self.assertEqual(cnts.frame_count, 2)
def test_nested_grad_mode_graph_break(self):
def fn(x):
before = torch.is_grad_enabled()
with torch.set_grad_enabled(False):
torch._dynamo.graph_break()
with torch.set_grad_enabled(True):
x = torch.mul(x, 5)
torch._dynamo.graph_break()
x = torch.sqrt(x)
assert torch.is_grad_enabled()
assert not torch.is_grad_enabled()
assert torch.is_grad_enabled() == before
return x
a = torch.randn([3, 4])
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
for _ in range(10):
opt_fn(a)
self.assertEqual(cnts.frame_count, 3)
def test_build_tuple_unpack(self):
def fn1(a, b, c):
return a - b / c
def fn2(a, b, c):
tmp1 = (a,)
tmp2 = (b, c)
args = (*tmp1, *tmp2)
return fn1(*args)
def fn3(a, *args):
return fn1(a, *args)
torch._dynamo.testing.standard_test(self, fn=fn2, nargs=3, expected_ops=2)
torch._dynamo.testing.standard_test(self, fn=fn3, nargs=3, expected_ops=2)
def test_list_mul(self):
def fn(count):
head_mask = count * [None] * count
return head_mask
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(2), [None] * 4)
# TODO: the captured frame here is a bit goofy, because we don't
# output anything and none of the traced operations have side
# effects. Probably need better heuristic for bailing on
# dynamo if there are no outputs
self.assertEqual(cnts.frame_count, ifunspec(1, 0))
self.assertEqual(cnts.op_count, ifunspec(2, 0))
def test_list_slice_mul(self):
def fn(count):
a = [1, 2, 3]
head_mask = count * a[1:] * count
return head_mask
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch._dynamo.optimize(cnts)(fn)
self.assertEqual(opt_fn(2), [2, 3] * 4)
self.assertEqual(cnts.frame_count, ifunspec(1, 0))
self.assertEqual(cnts.op_count, ifunspec(14, 0))