forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_torchinductor.py
11244 lines (9430 loc) · 357 KB
/
test_torchinductor.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: inductor"]
import contextlib
import copy
import dataclasses
import functools
import gc
import importlib
import itertools
import math
import operator
import os
import random
import re
import subprocess
import sys
import threading
import time
import typing
import unittest
import unittest.mock
import weakref
from pathlib import Path
from typing import Tuple
from unittest.mock import patch
import numpy as np
import torch
import torch._dynamo.config as dynamo_config
import torch.nn as nn
from torch._dispatch.python import enable_python_dispatcher
from torch._dynamo.debug_utils import aot_graph_input_parser
from torch._dynamo.testing import (
CompileCounterWithBackend,
expectedFailureCodegenDynamic,
rand_strided,
same,
skipIfPy312,
)
from torch._dynamo.utils import ifdynstaticdefault
from torch._inductor.codegen.common import DataTypePropagation, OptimizationContext
from torch._inductor.fx_passes import pad_mm
from torch._inductor.test_case import TestCase as InductorTestCase
from torch._inductor.utils import (
add_scheduler_init_hook,
aoti_compile_with_persistent_cache,
aoti_eager_cache_dir,
load_aoti_eager_cache,
run_and_get_code,
run_and_get_cpp_code,
run_and_get_triton_code,
)
from torch._inductor.virtualized import V
from torch._prims_common import is_integer_dtype
from torch.fx.experimental.proxy_tensor import make_fx
from torch.library import _scoped_library
from torch.nn import functional as F
from torch.testing import FileCheck, make_tensor
from torch.testing._internal.common_cuda import (
PLATFORM_SUPPORTS_FLASH_ATTENTION,
PLATFORM_SUPPORTS_MEM_EFF_ATTENTION,
SM80OrLater,
TEST_CUDNN,
with_tf32_off,
)
from torch.testing._internal.common_device_type import (
_has_sufficient_memory,
expectedFailureXPU,
)
from torch.testing._internal.common_dtype import all_types, get_all_dtypes
from torch.testing._internal.common_utils import (
DeterministicGuard,
instantiate_parametrized_tests,
IS_CI,
IS_FBCODE,
IS_MACOS,
IS_WINDOWS,
IS_X86,
parametrize,
serialTest,
skipIfRocm,
skipIfXpu,
subtest,
TEST_WITH_ASAN,
TEST_WITH_ROCM,
)
from torch.utils import _pytree as pytree
from torch.utils._python_dispatch import TorchDispatchMode
from torch.utils._pytree import tree_flatten, tree_unflatten
from torch.utils.weak import WeakTensorKeyDictionary
DO_PERF_TEST = os.environ.get("DO_PERF_TEST") == "1"
if IS_WINDOWS and IS_CI:
sys.stderr.write(
"Windows CI does not have necessary dependencies for test_torchinductor yet\n"
)
if __name__ == "__main__":
sys.exit(0)
raise unittest.SkipTest("requires sympy/functorch/filelock")
importlib.import_module("functorch")
importlib.import_module("filelock")
from torch._inductor import config, test_operators
from torch._inductor.compile_fx import (
compile_fx,
compile_fx_inner,
complex_memory_overlap,
)
from torch._inductor.utils import has_torchvision_roi_align
from torch.testing._internal.common_utils import slowTest
from torch.testing._internal.inductor_utils import (
GPU_TYPE,
HAS_CPU,
HAS_GPU,
HAS_MULTIGPU,
skipCPUIf,
skipCUDAIf,
)
HAS_AVX2 = "fbgemm" in torch.backends.quantized.supported_engines
aten = torch.ops.aten
requires_gpu = functools.partial(unittest.skipIf, not HAS_GPU, "requires gpu")
requires_multigpu = functools.partial(
unittest.skipIf, not HAS_MULTIGPU, f"requires multiple {GPU_TYPE} devices"
)
skip_if_x86_mac = functools.partial(
unittest.skipIf, IS_MACOS and IS_X86, "Does not work on x86 Mac"
)
vec_dtypes = [torch.float, torch.bfloat16, torch.float16]
libtest = torch.library.Library("test", "FRAGMENT") # noqa: TOR901
ids = set()
f32 = torch.float32
i64 = torch.int64
i32 = torch.int32
def _large_cumprod_input(shape, dim, dtype, device):
# Construct a cumprod input which guaruntees not to overflow or underflow
if is_integer_dtype(dtype):
# Large products don't fit in integers, the best we can do
# is random +/-1 values to test the sign of the result
x = torch.randint(0, 1, shape, dtype=dtype, device=device)
return x * 2 - 1
comp_dtype = torch._prims_common.get_computation_dtype(dtype)
batch_size = 256
if comp_dtype != dtype:
batch_size = math.floor(math.log2(torch.finfo(dtype).max) / 3)
# Create random values with a uniform magnitude and uniform exponent
num_batches = (shape[dim] + 2 * batch_size - 1) // (2 * batch_size)
batch_shape = (
shape[:dim]
+ (
num_batches,
batch_size,
)
+ shape[dim + 1 :]
)
magnitude = 1 + torch.rand(batch_shape, dtype=comp_dtype, device=device)
exponent = torch.randint(-1, 1, batch_shape, device=device).to(comp_dtype)
batch = magnitude * exponent.exp2()
# Alternate each batch of values with their reciprocals so the product
# never gets too far away from 1
t = torch.cat((batch, batch.reciprocal()), dim=dim + 1)
t = t.flatten(dim, dim + 1)
t = aten.slice(t, dim=dim, start=0, end=shape[dim])
# Randomize sign
sign = torch.randint(0, 1, shape, device=device) * 2 - 1
return (t * sign).to(dtype)
def define_custom_op_for_test(id_, fn_cpu, fn_cuda, fn_xpu, fn_meta, tags=()):
global libtest
global ids
if id_ not in ids:
libtest.define(f"{id_}(Tensor self) -> Tensor", tags=tags)
libtest.impl(id_, fn_cpu, "CPU")
libtest.impl(id_, fn_cuda, "CUDA")
libtest.impl(id_, fn_xpu, "XPU")
libtest.impl(id_, fn_meta, "Meta")
ids.add(id_)
def define_custom_op_2_for_test(id_, fn_cpu, fn_cuda, fn_xpu, fn_meta, tags=()):
global libtest
global ids
if id_ not in ids:
libtest.define(
f"{id_}(Tensor self, float scale) -> (Tensor, Tensor)", tags=tags
)
libtest.impl(id_, fn_cpu, "CPU")
libtest.impl(id_, fn_cuda, "CUDA")
libtest.impl(id_, fn_xpu, "XPU")
libtest.impl(id_, fn_meta, "Meta")
ids.add(id_)
def define_custom_op_3_for_test(id_, fn_cpu, fn_cuda, fn_xpu, fn_meta, tags=()):
global libtest
global ids
if id_ not in ids:
libtest.define(f"{id_}(Tensor[] x) -> Tensor", tags=tags)
libtest.impl(id_, fn_cpu, "CPU")
libtest.impl(id_, fn_cuda, "CUDA")
libtest.impl(id_, fn_xpu, "XPU")
libtest.impl(id_, fn_meta, "Meta")
ids.add(id_)
f32 = torch.float32
def run_fw_bw_and_get_code(fn):
def run_with_backward():
result = fn()
result.sum().backward()
return result
return run_and_get_code(run_with_backward)
class TestCase(InductorTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._stack = contextlib.ExitStack()
cls._stack.enter_context(
config.patch(
{
"debug": True,
"debug_index_asserts": True,
"cpp.min_chunk_size": 1,
"triton.autotune_pointwise": False, # too slow
"implicit_fallbacks": False,
"generate_intermediate_hooks": True,
}
)
)
@classmethod
def tearDownClass(cls):
cls._stack.close()
super().tearDownClass()
def setUp(self):
torch._dynamo.reset()
torch._inductor.metrics.reset()
super().setUp()
self._start = time.perf_counter()
def tearDown(self):
super().tearDown()
torch._dynamo.reset()
if os.environ.get("ERROR_ON_SLOW") == "1":
elapsed = time.perf_counter() - self._start
assert elapsed < 120
class ToTuple(torch.nn.Module):
def forward(self, x):
return (x,)
@dataclasses.dataclass
class InputGen:
n: int
device: str
def dense(self):
return torch.randn((self.n, self.n), device=self.device)
def transposed(self):
return self.dense().transpose(0, 1)
def strided(self):
return torch.randn((self.n * 2, self.n * 3), device=self.device)[
self.n :, self.n :: 2
]
def broadcast1(self):
return torch.randn((self.n,), device=self.device)
def broadcast2(self):
return torch.randn((1, self.n, 1), device=self.device)
def broadcast3(self):
return torch.randn((1,), device=self.device)
def double(self):
return torch.randn((self.n, self.n), device=self.device, dtype=torch.double)
def int(self):
return torch.arange(self.n, device=self.device, dtype=torch.int32)
def compute_grads(args, kwrags, results, grads):
def gather_leaf_tensors(args, kwargs):
args = pytree.arg_tree_leaves(*args, **kwargs)
leaf_tensors = [
arg for arg in args if isinstance(arg, torch.Tensor) and arg.requires_grad
]
return leaf_tensors
flat_results = pytree.tree_leaves(results)
flat_diff_results = [
r for r in flat_results if isinstance(r, torch.Tensor) and r.requires_grad
]
assert len(flat_diff_results) > 0
leaf_tensors = gather_leaf_tensors(args, kwrags)
assert len(leaf_tensors) > 0
return torch.autograd.grad(
flat_diff_results,
leaf_tensors,
grads,
allow_unused=True,
retain_graph=True,
)
def clone_preserve_strides(x, device=None):
if not isinstance(x, torch.Tensor):
return x
buffer = torch.as_strided(
x, (x.untyped_storage().size() // x.element_size(),), (1,), 0
)
if not device:
buffer = buffer.clone()
else:
buffer = buffer.to(device, copy=True)
out = torch.as_strided(buffer, x.size(), x.stride(), x.storage_offset())
return out
def check_model(
self: TestCase,
model,
example_inputs,
kwargs=None,
*,
atol=None,
rtol=None,
grad_atol=None,
grad_rtol=None,
check_lowp=True,
exact_dtype=True,
nopython=True,
copy_to_gpu=True,
reference_in_float=True,
assert_equal=True,
check_gradient=False,
check_has_compiled=True,
output_process_fn_grad=lambda x: x,
):
kwargs = kwargs or {}
torch._dynamo.reset()
ref_inputs = [clone_preserve_strides(x) for x in example_inputs]
ref_kwargs = kwargs
has_lowp_args = False
if reference_in_float and exact_dtype:
# Store expected dtypes so we can check actual result gives the correct types
torch.manual_seed(0)
try:
eager_result = model(*ref_inputs, **ref_kwargs)
except RuntimeError:
# Eager model may fail if the dtype is not supported
eager_result = None
ref_inputs = [clone_preserve_strides(x) for x in example_inputs]
expect_dtypes = [
x.dtype if isinstance(x, torch.Tensor) else None
for x in pytree.tree_leaves(eager_result)
]
del eager_result
ref_model = model
if reference_in_float:
# check_lowp is ignored here, it's kept just to be able to call `common` with extra arg
def upcast_fn(x):
nonlocal has_lowp_args
if isinstance(x, torch.Tensor) and (
x.dtype == torch.float16 or x.dtype == torch.bfloat16
):
has_lowp_args = True
return x.float()
else:
return x
ref_inputs = list(map(upcast_fn, example_inputs))
ref_kwargs = {k: upcast_fn(v) for k, v in kwargs.items()}
if has_lowp_args and hasattr(model, "to"):
ref_model = copy.deepcopy(model).to(torch.float)
torch.manual_seed(0)
correct = ref_model(*ref_inputs, **ref_kwargs)
torch._inductor.metrics.reset()
called = False
def compile_fx_wrapper(model_, example_inputs_):
nonlocal called
called = True
return compile_fx(model_, example_inputs_)
def run(*ex, **kwargs):
return model(*ex, **kwargs)
run = torch._dynamo.optimize(compile_fx_wrapper, nopython=nopython)(run)
torch.manual_seed(0)
actual = run(*example_inputs, **kwargs)
# if not called:
# exp = torch._dynamo.explain(run)(*example_inputs)
# print("Explain:", exp[0])
# for graph in exp[2]:
# print("Graph", graph)
if check_has_compiled:
assert called, "Ran graph without calling compile_fx"
assert type(actual) == type(correct)
if isinstance(actual, (tuple, list)):
assert len(actual) == len(correct)
assert all(
type(actual_item) == type(correct_item)
for actual_item, correct_item in zip(actual, correct)
)
correct_flat, correct_spec = tree_flatten(correct)
actual_flat = pytree.tree_leaves(actual)
def reference_to_expect(actual_flat, correct_flat):
return tuple(
(
y.to(x.dtype)
if isinstance(y, torch.Tensor) and y.dtype.is_floating_point
else y
)
for x, y in zip(actual_flat, correct_flat)
)
if reference_in_float and exact_dtype:
for expect_dtype, actual_result in zip(expect_dtypes, actual_flat):
if expect_dtype is not None:
assert (
actual_result.dtype == expect_dtype
), f"dtype mismatch, expected {expect_dtype} but got {actual_result.dtype}"
if reference_in_float:
correct_flat = reference_to_expect(actual_flat, correct_flat)
correct = tree_unflatten(correct_flat, correct_spec)
if assert_equal:
self.assertEqual(
actual,
correct,
atol=atol,
rtol=rtol,
equal_nan=True,
exact_dtype=exact_dtype,
)
# In case of input mutations, check that inputs are the same
self.assertEqual(
ref_inputs,
example_inputs,
atol=atol,
rtol=rtol,
equal_nan=True,
# our testing sometimes uses higher precision inputs for the reference
exact_dtype=False,
)
else:
for correct_val, actual_val in zip(correct_flat, actual_flat):
if isinstance(correct_val, torch.Tensor):
assert correct_val.device == actual_val.device
assert correct_val.size() == actual_val.size()
strides_equal, _ = torch._prims_common.check_significant_strides(
correct_val, actual_val
)
assert strides_equal
assert correct_val.layout == actual_val.layout
if exact_dtype:
assert correct_val.dtype == actual_val.dtype
if check_gradient:
actual = output_process_fn_grad(actual)
correct = output_process_fn_grad(correct)
actual_flat = pytree.tree_leaves(actual)
correct_flat = pytree.tree_leaves(correct)
# generate random unit norm gradients
grads = [
torch.rand(r.shape, device=r.device, dtype=r.dtype)
for r in correct_flat
if isinstance(r, torch.Tensor) and r.requires_grad
]
for g in grads:
g /= g.norm()
correct_grad = compute_grads(ref_inputs, ref_kwargs, correct, grads)
all_none_grads = all(x is None for x in correct_grad)
if all_none_grads:
# See Note [Detaching inputs that never need gradients]
# There are a handful of ops that can return None gradients, into of zero gradients.
# If all inputs to an AOTAutograd graph are supposed to get None gradients,
# AOTAutograd will end up forcing all of the outputs of the forward to not require grad.
# There's no easy fix to this (see the note above), although one option is to
# force any derivative formulas in core to return tensors of zeros instead of None.
flat_results = pytree.tree_leaves(actual)
results_that_require_grad = [
x
for x in flat_results
if isinstance(x, torch.Tensor) and x.requires_grad
]
self.assertEqual(len(results_that_require_grad), 0)
else:
actual_grad = compute_grads(example_inputs, kwargs, actual, grads)
if reference_in_float:
expect_grad = reference_to_expect(actual_grad, correct_grad)
else:
expect_grad = correct_grad
self.assertEqual(
actual_grad,
expect_grad,
atol=grad_atol or atol,
rtol=grad_rtol or rtol,
equal_nan=True,
exact_dtype=exact_dtype,
)
torch._dynamo.reset()
@torch._inductor.config.patch("triton.cudagraphs", False)
def check_model_gpu(
self: TestCase,
model,
example_inputs,
kwargs=None,
*,
atol=None,
rtol=None,
grad_atol=None,
grad_rtol=None,
check_lowp=True,
exact_dtype=True,
nopython=True,
copy_to_gpu=True,
reference_in_float=True,
assert_equal=True,
check_gradient=False,
check_has_compiled=True,
output_process_fn_grad=lambda x: x,
):
kwargs = kwargs or {}
if hasattr(model, "to"):
model = model.to(device=GPU_TYPE)
if copy_to_gpu:
example_inputs = tuple(
clone_preserve_strides(x, device=GPU_TYPE) for x in example_inputs
)
check_model(
self,
model,
example_inputs,
kwargs,
atol=atol,
rtol=rtol,
grad_atol=grad_atol,
grad_rtol=grad_rtol,
exact_dtype=exact_dtype,
nopython=nopython,
reference_in_float=reference_in_float,
assert_equal=assert_equal,
check_gradient=check_gradient,
check_has_compiled=check_has_compiled,
output_process_fn_grad=output_process_fn_grad,
)
if check_lowp:
def downcast_fn(x):
if not isinstance(x, torch.Tensor) or not x.dtype == torch.float:
return x
return torch.empty_strided(
x.size(), x.stride(), device=GPU_TYPE, dtype=torch.half
).copy_(x)
example_inputs = list(map(downcast_fn, example_inputs))
if hasattr(model, "to"):
model = model.to(torch.half)
if rtol is not None:
rtol = max(2e-3, rtol)
check_model(
self,
model,
example_inputs,
kwargs,
atol=atol,
rtol=rtol,
grad_atol=grad_atol,
grad_rtol=grad_rtol,
exact_dtype=exact_dtype,
nopython=nopython,
reference_in_float=reference_in_float,
assert_equal=assert_equal,
check_gradient=check_gradient,
check_has_compiled=check_has_compiled,
output_process_fn_grad=output_process_fn_grad,
)
check_model_cuda = check_model_gpu
def _run_and_assert_no_indirect_indexing(
test_case, func, *args, has_wrapping=None, has_assert=False, **kwargs
):
result, source_codes = run_and_get_code(func, *args, **kwargs)
for code in source_codes:
for line in code.split("\n"):
stmt = None
# Find indexing expressions
if ".load(" in line:
stmt = line.split(".load")[-1]
elif "tl.store" in line:
stmt = line.split(".store")[-1]
stmt = ",".join(stmt.split(",")[:-2]) # Remove store value and mask
elif ".store" in line:
stmt = line.split(".store")[-1]
elif "[" in line:
stmt = line.split("[")[-1].split("]")[0]
if "tl.make_block_ptr(" in line:
continue
if stmt is None:
continue
# indirect indexing involves a `tmp` variable
test_case.assertTrue(
"tmp" not in stmt,
msg=f"Found indirect indexing in statement '{stmt}' from code:\n{code}",
)
if has_wrapping is not None:
test_case.assertTrue(
("where" in code or "?" in code) is has_wrapping,
msg=f"Wanted {has_wrapping=} but got\n{code}",
)
test_case.assertTrue(
any(
("device_assert" in code or "TORCH_CHECK" in code) is has_assert
for code in source_codes
)
)
return result
def assertGeneratedKernelCountEqual(self: TestCase, expected: int):
if config.triton.multi_kernel:
# when multi_kernel is enabled, we generated both persistent reduction
# and non-persistent reduction kernels for the same node schedule.
# That will mess up with the kernel count. Just don't check it.
return
if config.cpp_wrapper:
expected *= 2
self.assertEqual(torch._inductor.metrics.generated_kernel_count, expected)
class SweepInputs2:
input_gen_types1 = [
"dense",
"transposed",
"strided",
"broadcast1",
"broadcast2",
"broadcast3",
"double",
"int",
]
input_gen_types2 = input_gen_types1
gen = None
@staticmethod
def kernel(a, b):
return (a + b,)
@classmethod
def gen_template(cls, name1, name2):
def test(self):
check_model(
self,
cls.kernel,
(
getattr(cls.gen, name1)(),
getattr(cls.gen, name2)(),
),
)
test.__name__ = f"test_{cls.gen.device}_{name1}_{name2}"
setattr(cls, test.__name__, test)
@classmethod
def populate(cls):
for name1 in cls.input_gen_types1:
for name2 in cls.input_gen_types2:
cls.gen_template(name1, name2)
@instantiate_parametrized_tests
class CommonTemplate:
def test_bool(self):
def fn(a, b):
return (
a + b,
a * b,
a & b,
a | b,
a ^ b,
torch.logical_and(a, b),
torch.logical_or(a, b),
torch.logical_not(a),
torch.sign(b),
)
self.common(
fn,
(
torch.tensor([True, False, True, False]),
torch.tensor([False, False, True, True]),
),
)
@skipCUDAIf(not SM80OrLater, "Requires sm80")
def test_eager_aoti_cache_hit(self):
ns = "aten"
op_name = "abs"
dispatch_key = "CPU"
device = "cpu"
if self.device.lower() == "cuda":
dispatch_key = "CUDA"
device = "cuda"
input_tensor = torch.randn(128, dtype=torch.float, device=device)
kernel_lib_path = aoti_compile_with_persistent_cache(
ns,
op_name,
device,
False,
getattr(torch.ops.aten, op_name),
(input_tensor,),
{},
)
self.assertTrue(Path(kernel_lib_path).exists())
from unittest import mock
# Patch the aoti_compile_with_persistent_cache as None to ensure no new kernel is generated
with mock.patch(
"torch._inductor.utils.aoti_compile_with_persistent_cache", None
):
qualified_op_name = f"{ns}::{op_name}"
_, overload_names = torch._C._jit_get_operation(qualified_op_name)
with _scoped_library("aten", "IMPL") as torch_compile_op_lib_impl:
# Get ref result from eager
ref_value = getattr(torch.ops.aten, op_name)(input_tensor)
for overload_name in overload_names:
try:
reg_op_name = qualified_op_name
schema = torch._C._get_schema(qualified_op_name, overload_name)
if schema.overload_name:
reg_op_name = f"{qualified_op_name}.{schema.overload_name}"
torch_compile_op_lib_impl._impl_with_aoti_compile( # noqa: F821
reg_op_name, dispatch_key
)
except Exception as e:
continue
# Invoke the pre-compiled kernel and get result.
res_value = getattr(torch.ops.aten, op_name)(input_tensor)
self.assertEqual(ref_value, res_value)
@skipCUDAIf(not SM80OrLater, "Requires sm80")
def test_aoti_compile_with_persistent_cache(self):
def fn(a):
return torch.abs(a)
ns = "aten"
op_name = "abs"
device = "cpu"
if self.device.lower() == "cuda":
device = "cuda"
input_tensor = torch.randn(128, dtype=torch.float, device=device)
kernel_lib_path = aoti_compile_with_persistent_cache(
ns,
op_name,
input_tensor.device.type,
False,
fn,
args=(input_tensor,),
kwargs={},
)
self.assertTrue(len(kernel_lib_path) > 0)
device_kernel_cache = aoti_eager_cache_dir(ns, device)
kernel_conf = device_kernel_cache / f"{op_name}.json"
self.assertTrue(kernel_conf.exists())
json_data = load_aoti_eager_cache("aten", "abs", input_tensor.device.type)
self.assertTrue(json_data is not None)
self.assertTrue(isinstance(json_data, list))
self.assertTrue(len(json_data) > 0)
op_info = json_data[0]
self.assertTrue(isinstance(op_info, dict))
self.assertTrue("meta_info" in op_info)
self.assertTrue("kernel_path" in op_info)
kernel_libs_abs_path = []
for item in json_data:
kernel_path = device_kernel_cache / item["kernel_path"]
kernel_libs_abs_path.append(kernel_path.as_posix())
self.assertTrue(kernel_lib_path in kernel_libs_abs_path)
@skipCUDAIf(not SM80OrLater, "Requires sm80")
def test_eager_aoti_with_scalar(self):
namespace_name = "aten"
op_name = "add"
op_overload_name = "Tensor"
op_name_with_overload = f"{op_name}.{op_overload_name}"
dispatch_key = "CPU"
device = torch.device("cpu")
if self.device.lower() == "cuda":
dispatch_key = "CUDA"
device = torch.device("cuda")
# Test the difference between scalar tensor and scalar
a = torch.scalar_tensor(1.0, device=device)
b = torch.scalar_tensor(2.0, device=device)
kernel_lib_path = aoti_compile_with_persistent_cache(
namespace_name,
op_name_with_overload,
a.device.type,
False,
torch.ops.aten.add,
args=(a, b),
kwargs={"alpha": 3.0},
)
self.assertTrue(Path(kernel_lib_path).exists())
device_kernel_cache = aoti_eager_cache_dir(namespace_name, device.type)
kernel_conf = device_kernel_cache / f"{op_name_with_overload}.json"
self.assertTrue(kernel_conf.exists())
json_data = load_aoti_eager_cache(
namespace_name, op_name_with_overload, a.device.type
)
op_info = json_data[0]
self.assertTrue(isinstance(op_info, dict))
self.assertTrue("meta_info" in op_info)
self.assertTrue(len(op_info["meta_info"]) == 3)
self.assertTrue(op_info["meta_info"][0]["sizes"] == [])
self.assertTrue(op_info["meta_info"][0]["strides"] == [])
# Scalar Tensor
self.assertTrue("scalar_value" not in op_info["meta_info"][0])
self.assertTrue(op_info["meta_info"][1]["sizes"] == [])
self.assertTrue(op_info["meta_info"][1]["strides"] == [])
# Scalar Tensor
self.assertTrue("scalar_value" not in op_info["meta_info"][1])
self.assertTrue(op_info["meta_info"][2]["sizes"] == [])
self.assertTrue(op_info["meta_info"][2]["strides"] == [])
# Scalar
self.assertTrue("scalar_value" in op_info["meta_info"][2])
with _scoped_library("aten", "IMPL") as torch_compile_op_lib_impl:
a = torch.randn(128, device=device)
b = torch.randn(128, device=device)
scalar_values = [1.0, 2.0, 3.0]
ref_values = []
for scalar_value in scalar_values:
ref_values.append(torch.add(a, b, alpha=scalar_value))
qualified_op_name = f"{namespace_name}::{op_name}"
_, overload_names = torch._C._jit_get_operation(qualified_op_name)
for overload_name in overload_names:
try:
reg_op_name = qualified_op_name
schema = torch._C._get_schema(reg_op_name, overload_name)
if schema.overload_name:
reg_op_name = f"{reg_op_name}.{schema.overload_name}"
torch_compile_op_lib_impl._impl_with_aoti_compile( # noqa: F821
reg_op_name, dispatch_key
)
except Exception as e:
continue
res_values = []
for scalar_value in scalar_values:
res_values.append(torch.add(a, b, alpha=scalar_value))
self.assertEqual(len(ref_values), len(res_values))
self.assertEqual(ref_values, res_values)
@skipCUDAIf(not SM80OrLater, "Requires sm80")
def test_torch_compile_override_registration(self):
dynamic = False
namespace_name = "aten"
dispatch_key = "CPU"
device = torch.device("cpu")
if self.device.lower() == "cuda":
dispatch_key = "CUDA"
device = torch.device("cuda")
unary_op_set = ["abs", "acos"]
def fn(x, op_name=""):
return getattr(torch, op_name)(x)
# Invoke torch.compile directly to get referent results
x = torch.randn(3, 4, device=device)
ref_array = []
for unary_op_name in unary_op_set:
opt_fn = torch.compile(functools.partial(fn, op_name=unary_op_name))
ref = opt_fn(x)
ref_array.append(ref)
def register_ops(op_set, dispatch_key, torch_compile_op_lib_impl):
for _op_name in op_set:
qualified_op_name = f"{namespace_name}::{_op_name}"
_, overload_names = torch._C._jit_get_operation(qualified_op_name)
for overload_name in overload_names:
try:
reg_op_name = qualified_op_name
schema = torch._C._get_schema(qualified_op_name, overload_name)
if schema.overload_name:
reg_op_name = f"{qualified_op_name}.{schema.overload_name}"
torch_compile_op_lib_impl._impl_with_aoti_compile( # noqa: F821
reg_op_name, dispatch_key
)
except Exception as e:
continue
with _scoped_library("aten", "IMPL") as torch_compile_op_lib_impl:
register_ops(unary_op_set, dispatch_key, torch_compile_op_lib_impl)
res_array = []
for unary_op_name in unary_op_set:
res_array.append(getattr(torch, unary_op_name)(x))
for ref, res in zip(ref_array, res_array):
self.assertEqual(ref, res)
a = torch.randn(128, device=device)
min_tensor = torch.randn(128, device=device)
max_tensor = min_tensor + 0.5
ref_with_min = torch.ops.aten.clamp(a, min_tensor)
ref_with_min_max = torch.ops.aten.clamp(a, min_tensor, max_tensor)
with _scoped_library("aten", "IMPL") as torch_compile_op_lib_impl:
register_ops(["clamp"], dispatch_key, torch_compile_op_lib_impl)
res_with_min = torch.ops.aten.clamp(a, min_tensor)
res_with_min_max = torch.ops.aten.clamp(a, min_tensor, max_tensor)
self.assertEqual(ref_with_min, res_with_min)
self.assertEqual(ref_with_min_max, res_with_min_max)
def test_add_const_int(self):
def fn(a):
return (a + 1, torch.add(a, 1, alpha=2))
for dtype in [torch.float32, torch.int32, torch.int64]:
self.common(fn, (torch.arange(32, dtype=dtype),))
def test_add_const_float(self):