forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_ops.py
1362 lines (1132 loc) · 54.3 KB
/
_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
# mypy: allow-untyped-defs
import abc
import contextlib
import ctypes
import importlib
import inspect
import sys
import types
from typing import Any, Callable, Dict, List, Set, Type, TypeVar, Union
import torch
import torch.utils._pytree as pytree
from torch import _utils_internal
from torch._C import _dispatch_is_included_in_alias as is_included_in_alias, DispatchKey
from torch._functorch.pyfunctorch import dispatch_functorch
from torch.utils._python_dispatch import TorchDispatchMode
_F = TypeVar("_F", bound=Callable[..., Any])
# Query `hasattr` only once.
_SET_GLOBAL_FLAGS = hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags")
@contextlib.contextmanager
def dl_open_guard():
"""
Context manager to set the RTLD_GLOBAL dynamic linker flag while we open a
shared library to load custom operators.
"""
if not _SET_GLOBAL_FLAGS:
yield
return
old_flags = sys.getdlopenflags()
sys.setdlopenflags(old_flags | ctypes.RTLD_GLOBAL)
try:
yield
finally:
sys.setdlopenflags(old_flags)
class OperatorBase:
"""
Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator
(which represents Python-only operators that are unrepresentable in TorchScript).
"""
def __init__(self):
# The dispatch cache precomputes a mapping of dispatch key that the
# dispatcher wants to dispatch to, to an actual implementation of the
# dispatch key. Confusingly, the actual implementation could *also* be a
# dispatch key, but in this case, this refers to the C++ kernel that
# was registered to some dispatch key. Aliases are permitted in the
# latter but not the former; for example, you might lookup the
# entry for AutogradCPU, and this maps you to the Autograd key for
# the generic autograd kernel that works for all devices. Since this
# is the Python dispatcher, you can also put an arbitrary Python
# callable to call instead. This handler gets precisely the
# args/kwargs that the operator was __call__'ed with.
# NB: This name is hard-coded in torch/csrc/autograd/python_variable.cpp
# for use with OpOverload; cache lookup is done entirely from C++
# for speed.
# TODO: The cache is NOT currently used by HigherOrderOperator, but it should!
self._dispatch_cache: Dict[
DispatchKey, Union[DispatchKey, Callable[..., Any]]
] = {}
# This table allows you to override the behavior of a particular
# dispatch key to call a custom Python function, rather than the
# ordinary C++ configured behavior. This is the raison d'etre of
# Python dispatcher: to let you program the dispatcher from Python
# in case you need something unusual, and don't want to clobber
# the existing registrations using the Python operator registration
# API.
self.py_kernels: Dict[DispatchKey, Callable[..., Any]] = {}
# This table allows you to override the behavior of a particular
# operator for a particular TorchDispatchMode. In practice,
# we are using this mostly for ProxyTensorMode. Modes can be
# thought of as an open world extension of dispatch keys, so it
# makes sense that you should be able to register them, the same
# way you can register dispatch keys.
self.python_key_table: Dict[
Union[Type[TorchDispatchMode], Type[torch.Tensor]], Callable[..., Any]
] = {}
# This table allows you to override the behavior of functorch
# transformations. NB: this currently only does something for
# HigherOrderOperator
self.functorch_table = {}
def __call__(self, *args, **kwargs):
raise NotImplementedError
def has_kernel_for_dispatch_key(self, k):
return k in self.py_kernels
def has_kernel_for_any_dispatch_key(self, ks):
for k in self.py_kernels:
if not torch._C._dispatch_is_alias_key(k) and ks.has(k):
return True
return False
def py_impl(self, k: Any) -> Callable[[_F], _F]:
def inner(fn: _F) -> _F:
if inspect.isclass(k) and (
issubclass(k, TorchDispatchMode) or issubclass(k, torch.Tensor)
):
assert k not in self.python_key_table
# TODO(voz): Should we replace setting DispatchKey.Python entirely with setting mode keys?
self.python_key_table[k] = fn
self._dispatch_cache.clear()
return fn
if isinstance(k, torch._C._functorch.TransformType):
assert k not in self.functorch_table
self.functorch_table[k] = fn
return fn
assert isinstance(k, DispatchKey)
assert (
k != DispatchKey.Python
), "Please register a mode for the torch._C.DispatchKey.Python key instead."
if k in self.py_kernels:
raise RuntimeError(
f"Trying to override a python impl for {k} on operator {self.name()}"
)
self.py_kernels[k] = fn
self._dispatch_cache.clear()
return fn
return inner
# Registers an implementation to all **3** variants of functionalization that we have:
# - DispatchKey.Functionalize
# - functorch.TransformType.Functionalize
# - FunctionalTensorMode
# Example:
# @py_functionalize_impl
# def functionalize_rule(ctx, inner_f, *args):
# args_unwrapped = ctx.unwrap_tensors(args)
# with ctx.redispatch_to_next():
# out = ctx.functionalize(inner_f)(*args_unwrapped)
# return ctx.wrap_tensors(out)
def py_functionalize_impl(self, fn: _F) -> _F:
from torch._subclasses.functional_tensor import (
CppFunctionalizeAPI as _CppFunctionalizeAPI,
FunctorchFunctionalizeAPI as _FunctorchFunctionalizeAPI,
PythonFunctionalizeAPI as _PythonFunctionalizeAPI,
)
# Construct our three flavors of functionalization,
# each of which have slightly different wrap/unwrap/redispatch policies
def functionalize_dk_fn(*args, **kwargs):
return fn(_CppFunctionalizeAPI(), *args, **kwargs)
def functionalize_dispatch_mode_fn(mode, *args, **kwargs):
return fn(_PythonFunctionalizeAPI(mode), *args, **kwargs)
def functionalize_functorch_fn(interpreter, *args, **kwargs):
return fn(_FunctorchFunctionalizeAPI(interpreter), *args, **kwargs)
self.py_impl(DispatchKey.Functionalize)(functionalize_dk_fn)
self.py_impl(torch._subclasses.functional_tensor.FunctionalTensorMode)(
functionalize_dispatch_mode_fn
)
self.py_impl(torch._C._functorch.TransformType.Functionalize)(
functionalize_functorch_fn
)
return fn
def name(self):
raise NotImplementedError
# Equivalent to computeDispatchTableEntryWithDebug
def resolve_key(op: OperatorBase, k: DispatchKey): # type: ignore[valid-type]
# 1. (Direct) operator registration
if op.has_kernel_for_dispatch_key(k):
return k
# 2.1 Use CompositeExplicitAutogradNonFunctional kernel if available
cand = DispatchKey.CompositeExplicitAutogradNonFunctional
if (
k == DispatchKey.Undefined or is_included_in_alias(k, cand)
) and op.has_kernel_for_dispatch_key(cand):
return cand
# 2.2 Use CompositeExplicitAutograd kernel if available
cand = DispatchKey.CompositeExplicitAutograd
if (
k == DispatchKey.Undefined or is_included_in_alias(k, cand)
) and op.has_kernel_for_dispatch_key(cand):
return cand
has_backend_kernel = op.has_kernel_for_any_dispatch_key(
torch._C._dispatch_get_backend_keyset_from_autograd(k)
) or op.has_kernel_for_dispatch_key(DispatchKey.CompositeExplicitAutograd)
# 2.3. Use CompositeImplicitAutograd kernel if available
cand = DispatchKey.CompositeImplicitAutogradNestedTensor
if (
(k != DispatchKey.Undefined and is_included_in_alias(k, cand))
and op.has_kernel_for_dispatch_key(cand)
and not has_backend_kernel
):
return cand
cand = DispatchKey.CompositeImplicitAutograd
if (
k == DispatchKey.Undefined or is_included_in_alias(k, cand)
) and op.has_kernel_for_dispatch_key(cand):
if k == DispatchKey.AutogradOther and op.has_kernel_for_any_dispatch_key(
torch._C._dispatch_autogradother_backends
):
raise RuntimeError("ambiguous autogradother kernel")
elif not has_backend_kernel:
return cand
# 2.4. For autograd backend keys, use kernel from DispatchKey::Autograd if available
cand = DispatchKey.Autograd
if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand):
return cand
# 2.5 Use kernel from DispatchKey::FuncTorchBatchedDecomposition if available
cand = DispatchKey.FuncTorchBatchedDecomposition
if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand):
return cand
# Backend fallback
if torch._C._dispatch_has_backend_fallback(k):
# The dispatch key itself will implicitly route to backend fallback.
# This is probably not great for the pure Python implementation.
return k
raise NotImplementedError(f"could not find kernel for {op} at dispatch key {k}")
_higher_order_ops: Dict[str, "HigherOrderOperator"] = {}
_HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS = [
DispatchKey.PythonDispatcher, # type: ignore[attr-defined]
DispatchKey.PythonTLSSnapshot, # type: ignore[attr-defined]
DispatchKey.ADInplaceOrView,
DispatchKey.BackendSelect,
DispatchKey.AutocastCPU, # type: ignore[attr-defined]
DispatchKey.AutocastCUDA, # type: ignore[attr-defined]
]
class HigherOrderOperator(OperatorBase, abc.ABC):
# The HigherOrderOperator will appear as torch.ops.higher_order.{name}
#
# If you're creating a new HigherOrderOperator, please do not change the
# default. Adding operators to the global torch.ops namespace is a bad
# practice due to name collisions.
def __init__(self, name, *, cacheable=False):
super().__init__()
if type(self) is HigherOrderOperator:
raise RuntimeError(
"Direct instantiation of HigherOrderOperator is not allowed. Please subclass it."
)
self._name = name
# Make _OPNamespace not scream, this whole name based association needs a good hard look
self.__name__ = name
_higher_order_ops[name] = self
self._ns = "higher_order"
self.__module__ = "torch.ops.higher_order"
self._cacheable = cacheable
self.non_fallthrough_keys = torch._C._dispatch_keyset_full()
for dispatch_key in _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS:
self.fallthrough(dispatch_key)
# [NOTE] We have to register pre-dispatch key implementation
# because sometimes HOP use aot-dispatch tracing to detect certaion
# mutations. This is problematic when we are functionalizing HOP
# during pre-dispatch because when the inner tracer starts, it will see
# that PreDispatch key is still active. In that case, we just redispatch
# it to next key. This is only safe to do when PreDispatch key stack has no
# active modes.
def py_impl(self, k: Any) -> Callable[[_F], _F]:
if isinstance(k, DispatchKey) and not self.non_fallthrough_keys.has(k):
self.non_fallthrough_keys = self.non_fallthrough_keys.add(k)
return super().py_impl(k)
@property
def namespace(self):
return self._ns
def cacheable(self):
return self._cacheable
def fallthrough(self, dispatch_key):
self.non_fallthrough_keys = self.non_fallthrough_keys.remove(dispatch_key)
# Use positional-only argument to avoid naming collide with custom ops arguments
# that are named "self".
def dispatch(self, /, dispatch_key, *args, **kwargs):
from torch.utils._python_dispatch import _get_current_dispatch_mode
if dispatch_key in self._dispatch_cache:
kernel = self._dispatch_cache[dispatch_key]
assert not isinstance(kernel, DispatchKey)
return kernel(*args, **kwargs)
if dispatch_key == DispatchKey.FuncTorchDynamicLayerFrontMode:
return dispatch_functorch(self, args, kwargs)
if dispatch_key == DispatchKey.Python:
# Keep the following 1:1 with handle_torch_function_no_python_arg_parser
# in torch/csrc/utils/python_arg_parser.cpp
overloaded_args_list = []
def has_python_key(tensor):
return torch._C._dispatch_keys(tensor).has("Python")
def check_overloaded(arg):
if isinstance(arg, torch.Tensor) and has_python_key(arg):
overloaded_args_list.append(arg)
for arg in (*args, *kwargs.values()):
check_overloaded(arg)
if isinstance(arg, (list, tuple)):
for a in arg:
check_overloaded(a)
overloaded_args = tuple(overloaded_args_list)
overloaded_types = tuple(type(arg) for arg in overloaded_args)
# Step 1: dispatch on any user TorchDispatchModes
from torch.utils._python_dispatch import _pop_mode_temporarily
curr_mode = _get_current_dispatch_mode()
if curr_mode is not None:
if type(curr_mode) in self.python_key_table:
handler = self.python_key_table[type(curr_mode)]
with _pop_mode_temporarily() as mode:
# "natural" calling convention: (mode, *args, **kwargs)
# TODO(rzou): we should support torch_dispatch calling convention too.
result = handler(mode, *args, **kwargs)
else:
raise NotImplementedError(
f"There was no rule registered for HOP {self._name} and mode {curr_mode}. "
f"We recommend filing an issue."
)
if result is not NotImplemented:
return result
# Step 2: dispatch on any subclasses
for arg in overloaded_args:
subclass_type = type(arg)
if (
subclass_type.__torch_dispatch__
== torch._C._disabled_torch_dispatch_impl
):
continue
if subclass_type in self.python_key_table:
handler = self.python_key_table[subclass_type]
# "natural" calling convention: (*args, **kwargs)
# TODO(rzou): we should support torch_dispatch calling convention too.
result = handler(*args, **kwargs)
else:
raise NotImplementedError(
f"There was no rule registered for HOP {self._name} and subclass {subclass_type}. "
f"We recommend filing an issue."
)
if result is not NotImplemented:
return result
# All handlers returned NotImplemented
raise TypeError(
f"Multiple dispatch failed for {self._name}. There was no registered that "
f"did not return NotImplemented. Use HOP.py_impl to register some. "
f"Tried mode: {curr_mode}) and subclasses: "
f"{[type(a) for a in overloaded_args]}"
)
functionality_key = torch._C._to_functionality_key(dispatch_key) # type: ignore[attr-defined]
if functionality_key == DispatchKey.PreDispatch:
from torch.utils._python_dispatch import _pop_mode_temporarily
# The check for Python in the exclude set is so we properly respect `with no_dispatch()`
# calls inside of a mode.
if (
_len_torch_dispatch_stack_pre_dispatch() > 0
) and not torch._C._dispatch_tls_is_dispatch_key_excluded(
DispatchKey.Python
):
curr_mode = _get_current_dispatch_mode_pre_dispatch()
assert (
curr_mode is not None
), "Illegal invocation of dispatch on torch._C.DispatchKey.PreDispatch without a mode."
assert (
type(curr_mode) in self.python_key_table
), f"Current active mode {curr_mode} not registered"
handler = self.python_key_table[type(curr_mode)]
with _pop_mode_temporarily(functionality_key) as mode:
return handler(mode, *args, **kwargs)
final_key = resolve_key(self, dispatch_key)
# This can current fail due to backend fallbacks. You just have to
# register them by hand for HigherOrderOperator.
if final_key not in self.py_kernels:
raise NotImplementedError(
f"could not find kernel for HigherOrderOperator {self._name} "
f"at dispatch key {final_key} (resolved from {dispatch_key})"
)
# [NOTE] We shouldn't cache PreDispatch kernel here because depending
# on what modes are active, predispatch behaviour is different.
# Also we do same thing for normal ops:
# See Note [Not Caching Per-Dispatch-Key Mode Handlers]
if dispatch_key != DispatchKey.PreDispatch:
self._dispatch_cache[dispatch_key] = self.py_kernels[final_key]
kernel = self.py_kernels[final_key]
# It's illegal to register DispatchKey to py_kernels, since there's no
# C++ kernel to call into
assert not isinstance(kernel, DispatchKey)
return kernel(*args, **kwargs)
@abc.abstractmethod
def __call__(self, /, *args, **kwargs):
# Dynamo already traces the body of HigherOrderOp beforehand when it
# so no need to trace into it.
from torch._dynamo import disable
@disable
def wrapper():
flat_args = _to_flat_tuple(args, kwargs)
if torch.overrides.has_torch_function(flat_args):
return torch.overrides.handle_torch_function(
self, flat_args, *args, **kwargs
)
dispatch_key_set = _compute_keyset(args, kwargs, self.non_fallthrough_keys)
return self.dispatch(
dispatch_key_set.highestPriorityTypeId(), *args, **kwargs
)
return wrapper()
def __str__(self):
return f"{self.name()}"
def name(self):
return self._name
def _to_flat_tuple(args, kwargs):
return pytree.arg_tree_leaves(*args, **kwargs)
def _compute_keyset(args, kwargs, non_fallthrough_keys):
tensors = _get_tensors(args, kwargs)
return key_extractor(tensors, non_fallthrough_keys)
def _get_tensors(args, kwargs):
flat_all = _to_flat_tuple(args, kwargs)
tensor_args = [t for t in flat_all if isinstance(t, torch.Tensor)]
return tuple(tensor_args)
# Note - this should maintain identical impl to the C++ dispatcher key extraction logic
# at ATen/core/dispatch/DispatchKeyExtractor.h
def key_extractor(tensors, key_mask):
key_set = torch._C._dispatch_tls_local_include_set()
for tensor in tensors:
key_set = key_set | torch._C._dispatch_keys(tensor)
key_set = key_set - torch._C._dispatch_tls_local_exclude_set()
key_set = key_set & key_mask
return key_set
# Mode stack for PreDispatchKey
# it should always have three keys with
# priority given to FunctionalTensorMode and
# then ProxyTorchDispatchMode. It means that
# slot 0 belongs to ProxyTorchDispatchMode and
# slot 1 belongs to FunctionalTensorMode.
#
# SchemaCheckMode is separate from the other 2,
# and is only valid when the stack is empty.
# SchemaCheckMode is for testing purposes, and
# is meant to run in eager mode on concrete inputs,
# checking for incorrect schemas in regards to
# aliasing or mutating ops.
class _ModeStackStateForPreDispatch:
def __init__(self):
self.__infra_modes = [None, None]
self._schema_check_mode = None
def set(self, index, mode):
assert index < len(self.__infra_modes)
self.__infra_modes[index] = mode
def get(self, index):
assert index < len(self.__infra_modes)
return self.__infra_modes[index]
def count(self):
return len([i for i in self.__infra_modes if i is not None]) + int(
self._schema_check_mode is not None
)
_mode_stack_state_for_pre_dispatch = _ModeStackStateForPreDispatch()
def unset_mode_pre_dispatch(mode_key, schema_check=False):
current_mode_stack_pre_dispatch = mode_stack_state_for_pre_dispatch()
assert mode_key is None or mode_key in (
torch._C._TorchDispatchModeKey.PROXY,
torch._C._TorchDispatchModeKey.FUNCTIONAL,
)
if schema_check:
assert mode_key is None
def _unset_mode():
if mode_key == torch._C._TorchDispatchModeKey.PROXY:
current_mode = current_mode_stack_pre_dispatch.get(0)
mode_stack_state_for_pre_dispatch().set(0, None)
return current_mode
elif mode_key == torch._C._TorchDispatchModeKey.FUNCTIONAL:
current_mode = current_mode_stack_pre_dispatch.get(1)
mode_stack_state_for_pre_dispatch().set(1, None)
return current_mode
else:
current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode
mode_stack_state_for_pre_dispatch()._schema_check_mode = None
return current_mode
current_mode = _unset_mode()
new_pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch()
# When we are unsetting a mode, we need to check if there is
# active mode left on the PreDispatch key. If there is nothing
# active, we need to remove PreDispatch key from local dispatch include
# set.
if new_pre_dispatch_len == 0:
torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, False)
return current_mode
def _set_mode_pre_dispatch(mode):
from torch._subclasses.functional_tensor import FunctionalTensorMode
from torch._subclasses.schema_check_mode import SchemaCheckMode
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
assert isinstance(
mode,
(
FunctionalTensorMode,
ProxyTorchDispatchMode,
SchemaCheckMode,
),
)
previous_mode_stack_len = _len_torch_dispatch_stack_pre_dispatch()
if isinstance(mode, SchemaCheckMode):
current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode
if previous_mode_stack_len > 0:
raise AssertionError(
"SchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stack"
)
mode_stack_state_for_pre_dispatch()._schema_check_mode = mode
elif isinstance(mode, FunctionalTensorMode):
current_mode = mode_stack_state_for_pre_dispatch().get(1)
assert current_mode is None
mode_stack_state_for_pre_dispatch().set(1, mode)
else:
current_mode = mode_stack_state_for_pre_dispatch().get(0)
assert current_mode is None
mode_stack_state_for_pre_dispatch().set(0, mode)
# When we are setting a mode, we need to check if there is
# active mode left on the PreDispatch key. If there was nothing
# active before setting this mode, it means that PreDispatch key
# was turned off. So we need to turn it on again.
if previous_mode_stack_len == 0:
torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, True)
def _pop_mode_from_pre_dispatch():
mode_stack = mode_stack_state_for_pre_dispatch()
pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch()
if pre_dispatch_len == 0:
raise AssertionError("Trying to pop empty mode stack")
if mode_stack._schema_check_mode is not None:
return unset_mode_pre_dispatch(None, schema_check=True)
if mode_stack.get(1) is not None:
return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.FUNCTIONAL)
if mode_stack.get(0) is not None:
return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY)
def _len_torch_dispatch_stack_pre_dispatch():
return mode_stack_state_for_pre_dispatch().count()
def _get_dispatch_mode_pre_dispatch(mode_key):
assert mode_key in (
torch._C._TorchDispatchModeKey.PROXY,
torch._C._TorchDispatchModeKey.FUNCTIONAL,
)
if mode_key == torch._C._TorchDispatchModeKey.PROXY:
return mode_stack_state_for_pre_dispatch().get(0)
else:
return mode_stack_state_for_pre_dispatch().get(1)
def _get_current_dispatch_mode_pre_dispatch():
if mode_stack_state_for_pre_dispatch()._schema_check_mode is not None:
return mode_stack_state_for_pre_dispatch()._schema_check_mode
else:
stack_len = mode_stack_state_for_pre_dispatch().count()
if stack_len == 2:
return mode_stack_state_for_pre_dispatch().get(1)
if stack_len == 1:
return (
mode_stack_state_for_pre_dispatch().get(1)
if mode_stack_state_for_pre_dispatch().get(1) is not None
else mode_stack_state_for_pre_dispatch().get(0)
)
return None
def mode_stack_state_for_pre_dispatch():
global _mode_stack_state_for_pre_dispatch
return _mode_stack_state_for_pre_dispatch
cached_ops: Set["OpOverload"] = set()
def add_cached_op(op_overload):
global cached_ops
cached_ops.add(op_overload)
def reset_cached_ops():
global cached_ops
cached_ops.clear()
def get_cached_ops():
global cached_ops
return cached_ops
# Each OpOverload object contains pointer to a a specific operator overload, a pointer to the parent `OpOverloadPacket` object.
# You can obtain an OpOverload object through attribute query on OpOverloadPacket.
class OpOverload(OperatorBase):
def __init__(self, overloadpacket, op, op_dk, schema, tags):
super().__init__()
self._op = op
self._op_dk = op_dk
self._schema = schema
self._overloadpacket = overloadpacket
self._tags = tags
self._overloadname = (
"default" if schema.overload_name == "" else schema.overload_name
)
self._name = self._schema.name
if schema.overload_name:
self._name += "." + schema.overload_name
self.__name__ = f"{self._schema.name.split('::')[1]}.{self._overloadname}"
self.__module__ = overloadpacket.__module__
op.__module__ = overloadpacket.__module__
self.__qualname__ = self._name
self.__annotations__ = {}
# Only compute the OperatorHandle when we need it. Not all OpOverloads have
# OperatorHandles (the TorchScript ones don't...)
self._lazy_handle = None
# If the OpOverload was constructed from a Library.def in Python.
self._defined_in_python = self.__qualname__ in torch.library._defs
# Logic replicated from aten/src/ATen/native/MathBitsFallback.h
is_write = None
for a in self._schema.arguments:
if a.alias_info is None:
continue
if is_write is None:
is_write = a.alias_info.is_write
else:
# We will conservatively call mixed mutable/non-mutable
# aliased inputs as NOT a view
is_write = a.alias_info.is_write or is_write
self.is_view = is_write is not None and not is_write
@property
def _namespace(self):
return self._schema.name.split("::")[0]
@property
def _opname(self):
return self._schema.name.split("::")[1]
@property
def _handle(self):
if self._lazy_handle is None:
self._lazy_handle = torch._C._dispatch_find_schema_or_throw(
self._schema.name, self._schema.overload_name
)
return self._lazy_handle
# it's a no-op since OpOverload object is immutable and must be unique for a given op overload.
def __deepcopy__(self, memo=None):
return self
def __repr__(self):
return "<OpOverload(op='{}.{}', overload='{}')>".format(
*self._schema.name.split("::"), self._overloadname
)
# Use positional-only argument to avoid naming collision with aten ops arguments
# that are named "self". This way, all the aten ops can be called by kwargs.
def __call__(self, /, *args, **kwargs):
return self._op(*args, **kwargs)
# Use positional-only argument to avoid naming collision with aten ops arguments
# that are named "self". This way, all the aten ops can be called by kwargs.
def redispatch(self, /, keyset, *args, **kwargs):
return self._handle.redispatch_boxed(keyset, *args, **kwargs)
def __hash__(self):
return hash(self._op)
# `my_namespace.my_op_name.overload_name`
def __str__(self):
return "{}.{}.{}".format(*self._schema.name.split("::"), self._overloadname)
def has_kernel_for_dispatch_key(self, k):
return super().has_kernel_for_dispatch_key(
k
) or torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), k)
def has_kernel_for_any_dispatch_key(self, ks):
return torch._C._dispatch_has_kernel_for_any_dispatch_key(
self.name(), ks
) or super().has_kernel_for_any_dispatch_key(ks)
@property
def namespace(self):
return self._schema.name.split("::")[0]
def _can_decompose(self):
dk = DispatchKey.CompositeImplicitAutograd
return dk in self.py_kernels or torch._C._dispatch_has_kernel_for_dispatch_key(
self.name(), dk
)
def decompose(self, *args, **kwargs):
dk = DispatchKey.CompositeImplicitAutograd
if dk in self.py_kernels:
# NB: This branch is not too necessary anymore, because we can
# apply Python CompositeImplicitAutograd *before* tracing
# using Python dispatcher (also taking advantage of the autograd
# formula). But it's included for completeness
return self.py_kernels[dk](*args, **kwargs)
elif torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), dk):
return self._op_dk(dk, *args, **kwargs)
else:
return NotImplemented
# Remove a dispatch key from the dispatch cache. This will force it to get
# recomputed the next time. Does nothing
# WARNING: if you register a dispatch key to py_kernels of an OpOverload,
# calling _del_dispatch on that key is NOT sufficient to apply your change,
# because a single registration may affect MULTIPLE dispatch keys (e.g.,
# registering Autograd affects AutogradCPU). del_dispatch is to be used
# only if you are specifically modifying how get_dispatch handles a
# particular input 'key'.
def _uncache_dispatch(self, key):
self._dispatch_cache.pop(key, None)
# This implements the pre-computation logic for the Python dispatcher.
def _get_dispatch(self, key):
# This is only called upon a cache miss
assert key not in self._dispatch_cache, f"{self} {key}"
if key == DispatchKey.Python:
if not isinstance(self, TorchBindOpOverload) and not self.python_key_table:
self._dispatch_cache[key] = key
add_cached_op(self)
return key
def handler(*args, **kwargs):
from torch.utils._python_dispatch import _get_current_dispatch_mode
# TODO: We also need to handle tensor subclasses here
# TODO(voz): We should walk all the nodes here / turn it into a list, topmode is ok for now.
curr_mode = type(_get_current_dispatch_mode())
assert (
curr_mode is not None
), "Illegal invocation of dispatch on torch._C.DispatchKey.Python without a mode."
if curr_mode not in self.python_key_table:
if isinstance(self, TorchBindOpOverload):
with torch.utils._python_dispatch._pop_mode_temporarily() as mode:
return torch._library.utils.handle_dispatch_mode(
mode, self, *args, **kwargs
)
else:
return self._op_dk(key, *args, **kwargs)
with torch.utils._python_dispatch._pop_mode_temporarily() as mode:
return self.python_key_table[curr_mode](mode, *args, **kwargs)
self._dispatch_cache[key] = handler
add_cached_op(self)
return handler
functionality_key = torch._C._to_functionality_key(key) # type: ignore[attr-defined]
if functionality_key == DispatchKey.PreDispatch:
curr_stack_len = _len_torch_dispatch_stack_pre_dispatch()
# The check for Python in the exclude set is so we properly respect `with no_dispatch()`
# calls inside of a mode.
if (
curr_stack_len > 0
and not torch._C._dispatch_tls_is_dispatch_key_excluded(
DispatchKey.Python
)
):
def handler(*args, **kwargs):
@contextlib.contextmanager
def _temporarily_pop_modes_from_pre_dispatch():
top_mode = _pop_mode_from_pre_dispatch()
try:
yield top_mode
finally:
_set_mode_pre_dispatch(top_mode)
with _temporarily_pop_modes_from_pre_dispatch() as curr_mode:
return torch._library.utils.handle_dispatch_mode(
curr_mode, self, *args, **kwargs
)
# Note [Not Caching Per-Dispatch-Key Mode Handlers]
# Note that we're not caching this handler. There isn't really a point, since the slow bit
# is the handler itself (in python).
# Also, not caching means that we don't have to reset the cache when any existing
# modes go out of scope (which in of itself takes time to loop through all operators).
return handler
final_key = resolve_key(self, key)
# See Note [Not Caching Per-Dispatch-Key Mode Handlers]
cache_result = key != DispatchKey.PreDispatch
# TODO: We could potentially have lots of debugging wrappers against
# dispatch keys; design some general registration mechanism instead of
# having if statement for each of them
if key == DispatchKey.Functionalize:
import torch._dispatch.python as pydispatch
if pydispatch.CROSSREF_FUNCTIONALIZE:
handler = pydispatch.make_crossref_functionalize(self, final_key)
if cache_result:
self._dispatch_cache[key] = handler
add_cached_op(self)
return handler
r = self.py_kernels.get(final_key, final_key)
if cache_result:
self._dispatch_cache[key] = r
add_cached_op(self)
return r
def name(self):
return self._name
@property
def overloadpacket(self):
return self._overloadpacket
@property
def op(self):
return self._op
@property
def tags(self):
return self._tags
# TODO: add more methods to expose information about input and output arguments
# TorchBindOpOverload are those custom ops which have at least one overload's
# schema consists of torch.ScriptObject (i.e. custom class) input.
# TorchBindOpOverload will skip C++ dispatcher and purely dispatched in python
# when its inputs contain FakeScriptObject in a similar way as higher order ops.
class TorchBindOpOverload(OpOverload):
def _fallthrough_keys(self) -> List[DispatchKey]:
# TODO: we should be calling the fallback for these, but a fallthrough is almost close
# enough to the fallback in most cases that we care about.
_DEFAULT_FALLTHROUGH_KEYS = [
DispatchKey.Autograd,
DispatchKey.AutogradCPU,
DispatchKey.AutogradCUDA,
DispatchKey.ADInplaceOrView,
DispatchKey.BackendSelect,
DispatchKey.PythonTLSSnapshot,
DispatchKey.PythonDispatcher,
]
def _may_use_fallthrough_instead_of_fallback(key: DispatchKey):
if torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), key):
return torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough(
self.name(), key
)
return (
key not in self.py_kernels
or self.py_kernels[key] is torch.library.fallthrough_kernel
)
return [
key
for key in _DEFAULT_FALLTHROUGH_KEYS
if _may_use_fallthrough_instead_of_fallback(key)
]
@contextlib.contextmanager
def _register_as_effectful_op_temporarily(self):
from torch._higher_order_ops.effects import (
_EffectType,
_register_effectful_op,
SIDE_EFFECTS,
)
try:
if self not in SIDE_EFFECTS:
_register_effectful_op(self, _EffectType.ORDERED)
yield
finally:
if self in SIDE_EFFECTS:
del SIDE_EFFECTS[self]
# Use positional-only argument to avoid naming collision with aten ops arguments
# that are named "self". This way, all the aten ops can be called by kwargs.
def __call__(self, /, *args, **kwargs):
if _must_dispatch_in_python(args, kwargs):
# When any inputs are FakeScriptObject, we need to
# skip c++ dispatcher and dispatch in python through _get_dispatch of python_dispatcher
# because C++ dispatcher will check the schema and cannot recognize FakeScriptObject.
#
# Note:
# 1. We only register the torchbind op temporarily as effectful op because we only want
# the effect token functionalization logic to be applied during tracing. Otherwise, the behavior
# of the eagerly executing the op might change after tracing.
# 2. We don't want to register the op as effectful for all torchbind ops in ctor because this might
# cause unexpected behavior for some autograd.profiler ops e.g. profiler._record_function_exit._RecordFunction.
with self._register_as_effectful_op_temporarily():
return self._dispatch_in_python(args, kwargs, self._fallthrough_keys())
return self._op(*args, **kwargs)
def _dispatch_in_python(self, args, kwargs, fallthrough_keys):
non_fallthrough_keys = torch._C._dispatch_keyset_full()
for key in fallthrough_keys:
non_fallthrough_keys = non_fallthrough_keys.remove(key)
dispatch_key_set = _compute_keyset(args, kwargs, non_fallthrough_keys)
dispatch_key = dispatch_key_set.highestPriorityTypeId()
handler = (
self._get_dispatch(dispatch_key)
if dispatch_key not in self._dispatch_cache
else self._dispatch_cache[dispatch_key]
)
if isinstance(handler, DispatchKey):
# fallthrough keys can be registered at runtime via torch.library.impl
# so need to add it to fallthrough_keys and re-dispatch.
if torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough(
self.name(), dispatch_key
):
return self._dispatch_in_python(
args, kwargs, fallthrough_keys + [dispatch_key]
)
raise RuntimeError(
f"Torchbind op {self} received a FakeScriptObject input when dispatching {handler}."
f" but no python implementation is found."
f" Please file an issue on this when you encounter this error."
f" This error can happen when you export or compile the model."
f" It can still happpen even if a C++ implementation for {dispatch_key}. "
f" has been registered. That's because FakeScriptObject purely lives in python and cannot work "
f" with a C++ implementation."
)
assert isinstance(handler, Callable) # type: ignore[arg-type]
return handler(*args, **kwargs)
def _must_dispatch_in_python(args, kwargs):