forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_custom_ops.py
4012 lines (3241 loc) · 139 KB
/
test_custom_ops.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: custom-operators"]
import collections
import itertools
import os
import re
import subprocess
import sys
import typing
import unittest
from typing import * # noqa: F403
import numpy as np
import torch._custom_ops as custom_ops
import torch.testing._internal.optests as optests
import torch.utils._pytree as pytree
import torch.utils.cpp_extension
from functorch import make_fx
from torch import Tensor
from torch._custom_op.impl import CustomOp, infer_schema
from torch._library.infer_schema import tuple_to_list
from torch._utils_internal import get_file_path_2 # @manual
from torch.testing._internal import custom_op_db
from torch.testing._internal.common_cuda import TEST_CUDA
from torch.testing._internal.common_device_type import (
instantiate_device_type_tests,
OpDTypes,
ops,
)
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
IS_WINDOWS,
parametrize,
run_tests,
scoped_load_inline,
skipIfTorchDynamo,
subtest,
TestCase,
)
from torch.testing._internal.custom_op_db import numpy_nonzero
# Shadowed by `torch.testing._internal.common_utils.custom_op`
from torch._custom_op.impl import custom_op # usort: skip
def requires_compile(fun):
fun = unittest.skipIf(IS_WINDOWS, "torch.compile doesn't work with windows")(fun)
return fun
class CustomOpTestCaseBase(TestCase):
test_ns = "_test_custom_op"
def setUp(self):
super().setUp()
self.libraries = []
def tearDown(self):
super().tearDown()
import torch._custom_op
keys = list(torch._custom_op.impl.global_registry.keys())
for key in keys:
if not key.startswith(f"{self.test_ns}::"):
continue
torch._custom_op.impl.global_registry[key]._destroy()
if hasattr(torch.ops, self.test_ns):
delattr(torch.ops, self.test_ns)
for lib in self.libraries:
lib._destroy()
del self.libraries
def ns(self):
return getattr(torch.ops, self.test_ns)
def lib(self):
result = torch.library.Library(self.test_ns, "FRAGMENT") # noqa: TOR901
self.libraries.append(result)
return result
def get_op(self, qualname):
return torch._custom_op.impl.get_op(qualname)
@requires_compile
class TestCustomOpTesting(CustomOpTestCaseBase):
@parametrize("check_gradients", (False, "auto"))
@parametrize("dynamic", (True, False))
def test_aot_autograd_check_degenerate_cases(
self, device, dynamic, check_gradients
):
def simple(x):
return x.clone()
# Should not raise
x = torch.randn(3, device=device)
optests.aot_autograd_check(
simple, (x,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def outputs_dont_require_grad(x):
return x.detach()
# Should not raise
y = torch.randn(3, device=device, requires_grad=True)
optests.aot_autograd_check(
simple, (y,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def no_outputs(x):
return x.detach()
# Should not raise
x = torch.randn(3, device=device, requires_grad=True)
y = torch.randn(3, device=device, requires_grad=False)
optests.aot_autograd_check(
no_outputs, (x,), {}, dynamic=dynamic, check_gradients=check_gradients
)
optests.aot_autograd_check(
no_outputs, (y,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def test_incorrect_schema_mutation(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
guard = torch._C._AutoDispatchBelowAutograd()
try:
return op(x)
finally:
del guard
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
x.sin_()
return x.clone()
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.tensor(3.14159 / 3, requires_grad=True, device=device)
with self.assertRaisesRegex(
optests.OpCheckError, "Argument x is not defined as mutable but was mutated"
):
torch.library.opcheck(op, (x,), {})
def test_incorrect_schema_view(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# Emulate AutoDispatchBelowADInplaceOrView, which is not bound into python
with torch._C._AutoDispatchBelowAutograd():
with torch._C._ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.ADInplaceOrView)
):
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.view_as(x)
def foo_meta(x):
return x.view_as(x)
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor(3.14159 / 3, requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError,
"Argument x is not defined to alias output but was aliasing",
):
torch.library.opcheck(op, (x,), {})
def test_missing_abstract_impl(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return 2 * gx
def foo_impl(x):
return torch.tensor(x.cpu().numpy() ** 2, device=x.device)
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.tensor([0, 1.0], requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError,
"_test_custom_op.foo.default",
):
torch.library.opcheck(op, (x,), {})
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_incorrect_abstract_impl(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# Emulate AutoDispatchBelowADInplaceOrView, which is not bound into python
guard = torch._C._AutoDispatchBelowAutograd()
guard2 = torch._C.ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.ADInplaceOrView)
)
try:
return op(x)
finally:
del guard
del guard2
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x**2
def foo_meta(x):
return x.unsqueeze(1) ** 2
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor([0, 1.0], requires_grad=True)
with self.assertRaisesRegex(optests.OpCheckError, "Shapes .* are not equal"):
torch.library.opcheck(op, (x,), {})
def test_missing_functionalization(self, device):
lib = self.lib()
lib.define("foo(Tensor(a!) x) -> Tensor(a!)")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.mark_dirty(x)
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.sin_()
def foo_meta(x):
return x
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor([0, 1.0])
y = x.clone()
with self.assertRaisesRegex(
optests.OpCheckError,
"We only support functionalizing operators whose outputs do not have alias annotations",
):
torch.library.opcheck(op, (y,), {})
def test_autograd_registered_at_backend(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.clone()
@staticmethod
def backward(ctx, gx):
return gx * 0.5
lib.impl("foo", Foo.apply, "CPU")
lib.impl("foo", Foo.apply, "CUDA")
lib.impl("foo", lambda x: x.clone(), "Meta")
x = torch.randn([], requires_grad=True)
with self.assertRaisesRegex(
torch.testing._internal.optests.OpCheckError,
"does not have an autograd kernel",
):
torch.library.opcheck(op, (x,), {})
# I'm not sure why this is necessary
del lib
def test_global_state_mutation(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
invoked = 0
@staticmethod
def forward(ctx, x):
Foo.invoked += 1
return x.clone() * Foo.invoked
@staticmethod
def backward(ctx, gx):
return gx
lib.impl("foo", Foo.apply, "CompositeImplicitAutograd")
x = torch.tensor(3.14159 / 3, requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError, "eager-mode PyTorch vs AOTAutograd"
):
torch.library.opcheck(op, (x,), {})
@ops(custom_op_db.custom_op_db, dtypes=OpDTypes.any_one)
def test_opcheck_opinfo(self, device, dtype, op):
for sample_input in op.sample_inputs(
device, dtype, requires_grad=op.supports_autograd
):
args = [sample_input.input] + list(sample_input.args)
kwargs = sample_input.kwargs
torch.library.opcheck(op.op, args, kwargs)
def test_opcheck_fails_basic(self, device):
@custom_op(f"{self.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor: ...
@foo.impl(["cpu", "cuda"])
def foo_impl(x):
return x.sum()
x = torch.randn(3, device=device, requires_grad=True)
# Triggers the CustomOp autograd NYI error
with self.assertRaisesRegex(
optests.OpCheckError, "Autograd has not been implemented for operator"
):
torch.library.opcheck(self.get_op(f"{self.test_ns}::foo"), (x,), {})
def test_autograd_registration_check_autograd_kernel(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.sin()
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.randn(3, requires_grad=True, device=device)
# Should not raise
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_compositeimplicitautograd(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
def foo_impl(x):
return x.sin().cos()
lib.impl("foo", foo_impl, "CompositeImplicitAutograd")
x = torch.randn(3, requires_grad=True, device=device)
# Should not raise
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_incorrect_composite(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
def foo_impl(x):
return x.sin().cos()
lib.impl("foo", foo_impl, "CompositeExplicitAutograd")
x = torch.randn(3, requires_grad=True, device=device)
with self.assertRaisesRegex(AssertionError, "incorrectly registered"):
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_incorrect(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return torch.sin(x)
@staticmethod
def backward(ctx, gx):
return gx
lib.impl("foo", Foo.apply, "CPU")
lib.impl("foo", Foo.apply, "CUDA")
x = torch.randn(3, requires_grad=True, device=device)
with self.assertRaisesRegex(AssertionError, "incorrectly registered"):
optests.autograd_registration_check(op, (x,), {})
def test_assert_raises_regex(self, device):
from torch.testing._internal.optests.aot_autograd import assert_raises_regex
with assert_raises_regex(RuntimeError, "c"):
raise RuntimeError("abcd")
with assert_raises_regex(RuntimeError, "c.*"):
raise RuntimeError("abcd")
with self.assertRaisesRegex(AssertionError, "instead got"):
with assert_raises_regex(RuntimeError, "c.*"):
raise ValueError("abcd")
with self.assertRaisesRegex(AssertionError, "Expected exception"):
with assert_raises_regex(RuntimeError, "c.*"):
pass
with self.assertRaisesRegex(AssertionError, "to match regex"):
with assert_raises_regex(RuntimeError, "f"):
raise RuntimeError("abcd")
class TestCustomOp(CustomOpTestCaseBase):
test_ns = "_test_custom_op"
def test_deploy_interaction(self):
# run in a different process to avoid parallel issues when we monkeypatch torch._running_with_deploy
script = """
import torch
torch._running_with_deploy = lambda: True
# creating the library is a no-op, so you can DEF multiple times
m1 = torch.library.Library("mylib4392", "DEF") # noqa: TOR901
m2 = torch.library.Library("mylib4392", "DEF") # noqa: TOR901
m = torch.library.Library("aten", "FRAGMENT") # noqa: TOR901
# define is a no-op
m.define("foobarbaz9996(Tensor x) -> Tensor")
assert not hasattr(torch.ops.aten, "foobarbaz9996"), "m.define should have been a noop"
def sin_override(x):
raise AssertionError("m.impl should have been a noop")
# impl is a no-op
m.impl("sin", sin_override, "CompositeImplicitAutograd")
x = torch.randn(3)
y = torch.sin(x)
# should be a no-op
@torch.library.custom_op("mylib::foobar", mutates_args={})
def foobar(x: torch.Tensor) -> torch.Tensor:
return x.sin()
# should be a no-op
@foobar.register_fake
def _(x):
return torch.empty_like(x)
# should be a no-op
m2.define("foobarbaz9996(Tensor x) -> Tensor")
# should be a no-op
@torch.library.register_fake("mylib4392::foobarbaz9996")
def _(x):
return torch.empty_like(x)
"""
script = script.strip()
env = os.environ.copy()
try:
subprocess.check_output(
[sys.executable, "-c", script],
stderr=subprocess.STDOUT,
# On Windows, opening the subprocess with the default CWD makes `import torch`
# fail, so just set CWD to this script's directory
cwd=os.path.dirname(os.path.realpath(__file__)),
env=env,
)
except subprocess.CalledProcessError as e:
self.fail(msg=("Subprocess exception:\n" + e.output.decode("utf-8")))
@requires_compile
def test_functionalize_error(self):
with torch.library._scoped_library(self.test_ns, "FRAGMENT") as lib:
lib.define("foo(Tensor(a!) x) -> Tensor(a!)")
def foo(x):
return x.sin_()
lib.impl("foo", foo, "CompositeExplicitAutograd")
foo_op = self.get_op(f"{self.test_ns}::foo")
lib.define("bar(Tensor(a) x) -> Tensor(a)")
def bar(x):
return x.view(-1)
lib.impl("bar", bar, "CompositeExplicitAutograd")
bar_op = self.get_op(f"{self.test_ns}::bar")
msg = r".*We only support functionalizing operators whose outputs do not have alias annotations"
x = torch.randn(3)
@torch.compile(backend="aot_eager", fullgraph=True)
def f(x):
return foo_op(x)
@torch.compile(backend="aot_eager", fullgraph=True)
def g(x):
return bar_op(x)
with self.assertRaisesRegex(RuntimeError, msg):
f(x)
with self.assertRaisesRegex(RuntimeError, msg):
g(x)
def test_invalid_schemas(self):
# function schmea validation goes through torchgen, so this is just a
# basic test.
with self.assertRaisesRegex(AssertionError, "Invalid function schema: foo"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(")
def test_invalid_qualname(self):
with self.assertRaisesRegex(ValueError, "overload"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo.Tensor", "() -> ()")
def test_name_must_match(self):
with self.assertRaisesRegex(ValueError, "to have name"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def baz(x: Tensor) -> Tensor:
raise NotImplementedError
def test_unsupported_schemas(self):
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(
f"{TestCustomOp.test_ns}::foo", "(Tensor(a!) x) -> Tensor(a)"
)(foo)
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(
f"{TestCustomOp.test_ns}::foo", "(Tensor(a) x) -> Tensor(a)"
)(foo)
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(Tensor x) -> ()")(
foo
)
with self.assertRaisesRegex(ValueError, "self"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(Tensor self) -> ()")(
foo
)
# Tests for the older custom_op API
def test_schema_matches_signature(self):
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(f"{TestCustomOp.test_ns}::blah", "(Tensor y) -> Tensor")
def blah(x):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah2", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah2(x, y):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah3",
"(Tensor x, *, Tensor w, Tensor z) -> Tensor",
)
def blah3(x, *, y, z):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah4",
"(Tensor x, *, Tensor z, Tensor y) -> Tensor",
)
def blah4(x, *, y, z):
pass
with self.assertRaisesRegex(ValueError, "not supported"):
@custom_op(f"{TestCustomOp.test_ns}::blah5", "(Tensor x) -> Tensor")
def blah5(*args):
pass
with self.assertRaisesRegex(ValueError, "not supported"):
@custom_op(
f"{TestCustomOp.test_ns}::blah6", "(*, Tensor z, Tensor y) -> Tensor"
)
def blah6(**kwargs):
pass
with self.assertRaisesRegex(ValueError, "default arguments"):
@custom_op(
f"{TestCustomOp.test_ns}::blah7", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah7(x=1, *, y):
pass
with self.assertRaisesRegex(ValueError, "default arguments"):
@custom_op(
f"{TestCustomOp.test_ns}::blah8", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah8(x, *, y=1):
pass
# kwonly-arg works
@custom_op(
f"{TestCustomOp.test_ns}::blah9", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah9(x, *, y):
pass
def test_infer_schema_no_return(self):
with self.assertRaisesRegex(
ValueError, "No return type annotation was provided. Please add one."
):
@torch.library.custom_op("mylib::foo", mutates_args={})
def foo(x: torch.Tensor, y: int):
return x * y
def test_infer_schema_supported(self):
def a(x: Tensor) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(a, mutates_args=()), """(Tensor x) -> Tensor"""
)
def kwonly1(x: Tensor, *, y: int, z: float) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(kwonly1, mutates_args=()),
"""(Tensor x, *, SymInt y, float z) -> Tensor""",
)
def kwonly2(*, y: Tensor) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(kwonly2, mutates_args=()), """(*, Tensor y) -> Tensor"""
)
def b(
x: Tensor,
y: int,
z: bool,
a: float,
b: torch.dtype,
c: torch.device,
d: torch.types.Number,
) -> Tuple[Tensor, int, float, bool]:
return torch.empty([]), 1, 0.1, True
self.assertExpectedInline(
infer_schema(b, mutates_args=()),
"""(Tensor x, SymInt y, bool z, float a, ScalarType b, Device c, Scalar d) -> (Tensor, SymInt, float, bool)""",
)
def c(
x: Tensor,
y: Sequence[Tensor],
z: Optional[Tensor],
w: Sequence[Optional[Tensor]],
) -> List[Tensor]:
return [torch.empty([])]
self.assertExpectedInline(
infer_schema(c, mutates_args=()),
"""(Tensor x, Tensor[] y, Tensor? z, Tensor?[] w) -> Tensor[]""",
)
def d(x: Tensor) -> Tuple[List[Tensor], Tensor]:
return [torch.empty([])], torch.empty([])
self.assertExpectedInline(
infer_schema(d, mutates_args=()), """(Tensor x) -> (Tensor[], Tensor)"""
)
def e() -> Tensor:
return torch.empty([])
self.assertExpectedInline(infer_schema(e, mutates_args=()), """() -> Tensor""")
def f(x: Tensor) -> None:
pass
self.assertExpectedInline(
infer_schema(f, mutates_args=()), """(Tensor x) -> ()"""
)
def g(
x: Tensor, y: List[Tensor], z: List[Tensor], w: List[Optional[Tensor]]
) -> None:
pass
self.assertExpectedInline(
infer_schema(g, mutates_args=()),
"""(Tensor x, Tensor[] y, Tensor[] z, Tensor?[] w) -> ()""",
)
self.assertExpectedInline(
infer_schema(g, mutates_args={"x", "w", "z"}),
"""(Tensor(a0!) x, Tensor[] y, Tensor(a2!)[] z, Tensor(a3!)?[] w) -> ()""",
)
self.assertExpectedInline(
infer_schema(g, mutates_args="unknown"),
"""(Tensor(a0!) x, Tensor(a1!)[] y, Tensor(a2!)[] z, Tensor(a3!)?[] w) -> ()""",
)
def h(
x: Tensor,
a: Optional[int] = None,
b: float = 3.14,
c: bool = True,
d: int = 3,
e: str = "foo",
f: torch.dtype = torch.float,
g: torch.dtype = torch.float32,
h: torch.dtype = torch.int,
i: torch.device = torch.device("cpu:0"),
j: torch.device = "cpu",
) -> None:
pass
self.assertExpectedInline(
infer_schema(h, mutates_args=()),
(
"""(Tensor x, SymInt? a=None, float b=3.14, bool c=True, SymInt d=3, str e="foo", """
"""ScalarType f=float32, ScalarType g=float32, ScalarType h=int32, Device i="cpu:0", Device j="cpu") -> ()"""
),
)
def foo_impl(x: torch.Tensor) -> torch.Tensor:
return x.sin()
schema = torch.library.infer_schema(foo_impl, op_name="myop", mutates_args={})
self.assertExpectedInline(schema, "myop(Tensor x) -> Tensor")
def test_infer_schema_unsupported(self):
with self.assertRaisesRegex(ValueError, "varargs"):
def foo(*args):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "varkwargs"):
def foo(**kwargs):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "must have a type annotation"):
def foo(x):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "unsupported"):
def foo(x: Tensor) -> Tuple[Tensor, ...]:
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "can be mutated"):
def foo(x: Tensor, y: int) -> Tensor:
raise NotImplementedError
infer_schema(foo, mutates_args={"y"})
def _generate_examples(self, typ):
if typ is int:
return [17]
if typ is float:
return [3.14]
if typ is bool:
return [True]
if typ is str:
return ["foo"]
if typ is torch.dtype:
return [torch.float32]
if typ is torch.device:
return [torch.device("cpu")]
if typ == torch.types.Number:
return [2.718]
if typ is torch.Tensor:
return [torch.tensor(3)]
if typ == Optional[torch.types.Number]:
return [None, 2.718]
origin = typing.get_origin(typ)
if origin is Union:
args = typing.get_args(typ)
assert len(args) == 2 and (args[0] is type(None) or args[1] is type(None))
elt = args[0] if args[1] is type(None) else args[1]
return self._generate_examples(elt) + [None]
if origin is list:
args = typing.get_args(typ)
assert len(args) == 1
elt = args[0]
return [
self._generate_examples(elt),
self._generate_examples(elt),
self._generate_examples(elt),
]
if origin is collections.abc.Sequence:
args = typing.get_args(typ)
assert len(args) == 1
examples = self._generate_examples(args[0])
return list(itertools.product(examples, examples)) + []
raise NotImplementedError(
f"testrunner cannot generate instanstance of type {typ}"
)
def test_supported_return_types_single_return(self):
for typ in torch._library.infer_schema.SUPPORTED_RETURN_TYPES:
for example in self._generate_examples(typ):
try:
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> typ:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x: Tensor) -> typ:
return example
op = self.get_op(f"{self.test_ns}::foo")
result = op(torch.randn([]))
self.assertEqual(result, example, msg=f"{typ} {example}")
finally:
custom_ops._destroy(f"{self.test_ns}::foo")
def test_supported_return_types_multi_return(self):
for typ in torch._library.infer_schema.SUPPORTED_RETURN_TYPES:
for example in self._generate_examples(typ):
try:
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> Tuple[typ, typ]:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x: Tensor) -> Tuple[typ, typ]:
return (example, example)
op = self.get_op(f"{self.test_ns}::foo")
result = op(torch.randn([]))
expected = (example, example)
self.assertEqual(result, expected, msg=f"{typ} {example}")
finally:
custom_ops._destroy(f"{self.test_ns}::foo")
def test_supported_param_types(self):
for typ in torch._library.infer_schema.SUPPORTED_PARAM_TYPES:
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: typ) -> Tensor:
raise NotImplementedError
yeet = None
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types=["cpu"])
def foo_cpu(x, y):
nonlocal yeet
yeet = y
return x.clone()
try:
for example in self._generate_examples(typ):
op = self.get_op(f"{self.test_ns}::foo")
op(torch.randn([]), example)
self.assertEqual(yeet, example, msg=f"{typ} {example}")
yeet = None
finally:
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
def test_sequences(self):
# Sequence[int] gets automagically turned into int[] in the schema.
# This test checks that we actually do support arbitrary sequence types.
class MySequence(collections.abc.Sequence):
def __init__(self) -> None:
self._container = [1, 2, 3]
def __getitem__(self, idx):
return self._container[idx]
def __len__(self):
return len(self._container)
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: torch.Tensor, sizes: Sequence[int]) -> torch.Tensor:
raise NotImplementedError
called = 0
@custom_ops.impl(f"{self.test_ns}::foo", device_types="cpu")
def foo_cpu(x, sizes):
nonlocal called
called += 1
# Dispatcher will normalize the sequence type into a List
self.assertEqual(sizes, [1, 2, 3])
return x.clone()
x = torch.randn([])
seq = MySequence()
op = self.get_op(f"{self.test_ns}::foo")
op(x, seq)
self.assertEqual(called, 1)
def test_unsupported_param_types(self):
# Not comprehensive (it doesn't need to be), just a check that our mechanism works
with self.assertRaisesRegex(ValueError, "unsupported type"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: List[Optional[int]]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaisesRegex(ValueError, "unsupported type"):
# int[N] in Dispatcher is a bit wild, so we don't try to support it.
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: Tuple[int, int]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaisesRegex(ValueError, r"For example, typing.List\[int\]"):
# test that we propose a correct and supported type.
@torch.library.custom_op(f"{TestCustomOp.test_ns}::foo", mutates_args={})
def foo(x: Tensor, y: Tuple[int, int]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaises(ValueError) as cm:
@torch.library.custom_op(f"{TestCustomOp.test_ns}::foo", mutates_args={})