_ops.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. # mypy: allow-untyped-defs
  2. import abc
  3. import contextlib
  4. import ctypes
  5. import importlib
  6. import inspect
  7. import sys
  8. import types
  9. from collections.abc import Iterator
  10. from functools import cached_property
  11. from typing import (
  12. Any,
  13. Callable,
  14. ClassVar,
  15. final,
  16. Generic,
  17. Optional,
  18. TYPE_CHECKING,
  19. Union,
  20. )
  21. from typing_extensions import Concatenate, ParamSpec, TypeVar
  22. import torch
  23. import torch.utils._pytree as pytree
  24. from torch import _utils_internal
  25. from torch._C import _dispatch_is_included_in_alias as is_included_in_alias, DispatchKey
  26. from torch._functorch.pyfunctorch import dispatch_functorch, TransformType
  27. from torch.utils._python_dispatch import TorchDispatchMode
  28. if TYPE_CHECKING:
  29. from torch._subclasses.functional_tensor import BaseFunctionalizeAPI
  30. _T = TypeVar("_T", default=Any)
  31. _P = ParamSpec("_P", default=...)
  32. # Query `hasattr` only once.
  33. _SET_GLOBAL_FLAGS = hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags")
  34. @contextlib.contextmanager
  35. def dl_open_guard():
  36. """
  37. Context manager to set the RTLD_GLOBAL dynamic linker flag while we open a
  38. shared library to load custom operators.
  39. """
  40. if not _SET_GLOBAL_FLAGS:
  41. yield
  42. return
  43. old_flags = sys.getdlopenflags()
  44. sys.setdlopenflags(old_flags | ctypes.RTLD_GLOBAL)
  45. try:
  46. yield
  47. finally:
  48. sys.setdlopenflags(old_flags)
  49. class OperatorBase:
  50. """
  51. Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator
  52. (which represents Python-only operators that are unrepresentable in TorchScript).
  53. """
  54. def __init__(self):
  55. # The dispatch cache precomputes a mapping of dispatch key that the
  56. # dispatcher wants to dispatch to, to an actual implementation of the
  57. # dispatch key. Confusingly, the actual implementation could *also* be a
  58. # dispatch key, but in this case, this refers to the C++ kernel that
  59. # was registered to some dispatch key. Aliases are permitted in the
  60. # latter but not the former; for example, you might lookup the
  61. # entry for AutogradCPU, and this maps you to the Autograd key for
  62. # the generic autograd kernel that works for all devices. Since this
  63. # is the Python dispatcher, you can also put an arbitrary Python
  64. # callable to call instead. This handler gets precisely the
  65. # args/kwargs that the operator was __call__'ed with.
  66. # NB: This name is hard-coded in torch/csrc/autograd/python_variable.cpp
  67. # for use with OpOverload; cache lookup is done entirely from C++
  68. # for speed.
  69. # TODO: The cache is NOT currently used by HigherOrderOperator, but it should!
  70. self._dispatch_cache: dict[
  71. DispatchKey, Union[DispatchKey, Callable[..., Any]]
  72. ] = {}
  73. # This table allows you to override the behavior of a particular
  74. # dispatch key to call a custom Python function, rather than the
  75. # ordinary C++ configured behavior. This is the raison d'etre of # codespell:ignore
  76. # Python dispatcher: to let you program the dispatcher from Python
  77. # in case you need something unusual, and don't want to clobber
  78. # the existing registrations using the Python operator registration
  79. # API.
  80. self.py_kernels: dict[DispatchKey, Callable[..., Any]] = {}
  81. # This table allows you to override the behavior of a particular
  82. # operator for a particular TorchDispatchMode. In practice,
  83. # we are using this mostly for ProxyTensorMode. Modes can be
  84. # thought of as an open world extension of dispatch keys, so it
  85. # makes sense that you should be able to register them, the same
  86. # way you can register dispatch keys.
  87. self.python_key_table: dict[
  88. type[Union[TorchDispatchMode, torch.Tensor]], Callable[..., Any]
  89. ] = {}
  90. # This table allows you to override the behavior of functorch
  91. # transformations. NB: this currently only does something for
  92. # HigherOrderOperator
  93. self.functorch_table = {}
  94. def __call__(self, *args, **kwargs):
  95. raise NotImplementedError
  96. def has_kernel_for_dispatch_key(self, k):
  97. return k in self.py_kernels
  98. def has_kernel_for_any_dispatch_key(self, ks):
  99. for k in self.py_kernels:
  100. if not torch._C._dispatch_is_alias_key(k) and ks.has(k):
  101. return True
  102. return False
  103. def py_impl(
  104. self,
  105. k: Union[
  106. type[TorchDispatchMode],
  107. type[torch.Tensor],
  108. TransformType,
  109. DispatchKey,
  110. ],
  111. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  112. def inner(fn: Callable[_P, _T]) -> Callable[_P, _T]:
  113. if inspect.isclass(k) and (
  114. issubclass(k, TorchDispatchMode) or issubclass(k, torch.Tensor)
  115. ):
  116. assert k not in self.python_key_table
  117. # TODO(voz): Should we replace setting DispatchKey.Python entirely with setting mode keys?
  118. self.python_key_table[k] = fn
  119. self._dispatch_cache.clear()
  120. return fn
  121. if isinstance(k, TransformType):
  122. assert k not in self.functorch_table
  123. self.functorch_table[k] = fn
  124. return fn
  125. assert isinstance(k, DispatchKey)
  126. assert k != DispatchKey.Python, (
  127. "Please register a mode for the DispatchKey.Python key instead."
  128. )
  129. if k in self.py_kernels:
  130. raise RuntimeError(
  131. f"Trying to override a python impl for {k} on operator {self.name()}"
  132. )
  133. self.py_kernels[k] = fn
  134. self._dispatch_cache.clear()
  135. return fn
  136. return inner
  137. # Registers an implementation to all **3** variants of functionalization that we have:
  138. # - DispatchKey.Functionalize
  139. # - functorch.TransformType.Functionalize
  140. # - FunctionalTensorMode
  141. # Example:
  142. # @py_functionalize_impl
  143. # def functionalize_rule(ctx, inner_f, *args):
  144. # args_unwrapped = ctx.unwrap_tensors(args)
  145. # with ctx.redispatch_to_next():
  146. # out = ctx.functionalize(inner_f)(*args_unwrapped)
  147. # return ctx.wrap_tensors(out)
  148. def py_functionalize_impl(
  149. self, fn: Callable[Concatenate["BaseFunctionalizeAPI", _P], _T]
  150. ) -> Callable[Concatenate["BaseFunctionalizeAPI", _P], _T]:
  151. from torch._subclasses.functional_tensor import (
  152. CppFunctionalizeAPI,
  153. FunctionalTensorMode,
  154. FunctorchFunctionalizeAPI,
  155. PythonFunctionalizeAPI,
  156. )
  157. # Construct our three flavors of functionalization,
  158. # each of which have slightly different wrap/unwrap/redispatch policies
  159. def functionalize_dk_fn(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  160. return fn(CppFunctionalizeAPI(), *args, **kwargs)
  161. def functionalize_dispatch_mode_fn(
  162. mode: Optional[FunctionalTensorMode], *args: _P.args, **kwargs: _P.kwargs
  163. ) -> _T:
  164. return fn(PythonFunctionalizeAPI(mode), *args, **kwargs)
  165. def functionalize_functorch_fn(
  166. interpreter, *args: _P.args, **kwargs: _P.kwargs
  167. ) -> _T:
  168. return fn(FunctorchFunctionalizeAPI(interpreter), *args, **kwargs)
  169. self.py_impl(DispatchKey.Functionalize)(functionalize_dk_fn)
  170. self.py_impl(FunctionalTensorMode)(functionalize_dispatch_mode_fn)
  171. self.py_impl(TransformType.Functionalize)(functionalize_functorch_fn)
  172. return fn
  173. def name(self):
  174. raise NotImplementedError
  175. # Equivalent to computeDispatchTableEntryWithDebug
  176. def resolve_key(op: OperatorBase, k: DispatchKey): # type: ignore[valid-type]
  177. # 1. (Direct) operator registration
  178. if op.has_kernel_for_dispatch_key(k):
  179. return k
  180. # 2.1 Use CompositeExplicitAutogradNonFunctional kernel if available
  181. cand = DispatchKey.CompositeExplicitAutogradNonFunctional
  182. if (
  183. k == DispatchKey.Undefined or is_included_in_alias(k, cand)
  184. ) and op.has_kernel_for_dispatch_key(cand):
  185. return cand
  186. # 2.2 Use CompositeExplicitAutograd kernel if available
  187. cand = DispatchKey.CompositeExplicitAutograd
  188. if (
  189. k == DispatchKey.Undefined or is_included_in_alias(k, cand)
  190. ) and op.has_kernel_for_dispatch_key(cand):
  191. return cand
  192. has_backend_kernel = op.has_kernel_for_any_dispatch_key(
  193. torch._C._dispatch_get_backend_keyset_from_autograd(k)
  194. ) or op.has_kernel_for_dispatch_key(DispatchKey.CompositeExplicitAutograd)
  195. # 2.3. Use CompositeImplicitAutograd kernel if available
  196. cand = DispatchKey.CompositeImplicitAutogradNestedTensor
  197. if (
  198. (k != DispatchKey.Undefined and is_included_in_alias(k, cand))
  199. and op.has_kernel_for_dispatch_key(cand)
  200. and not has_backend_kernel
  201. ):
  202. return cand
  203. cand = DispatchKey.CompositeImplicitAutograd
  204. if (
  205. k == DispatchKey.Undefined or is_included_in_alias(k, cand)
  206. ) and op.has_kernel_for_dispatch_key(cand):
  207. if k == DispatchKey.AutogradOther and op.has_kernel_for_any_dispatch_key(
  208. torch._C._dispatch_autogradother_backends
  209. ):
  210. raise RuntimeError("ambiguous autogradother kernel")
  211. elif not has_backend_kernel:
  212. return cand
  213. # 2.4. For autograd backend keys, use kernel from DispatchKey::Autograd if available
  214. cand = DispatchKey.Autograd
  215. if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand):
  216. return cand
  217. # 2.5 Use kernel from DispatchKey::FuncTorchBatchedDecomposition if available
  218. cand = DispatchKey.FuncTorchBatchedDecomposition
  219. if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand):
  220. return cand
  221. # Backend fallback
  222. if torch._C._dispatch_has_backend_fallback(k):
  223. # The dispatch key itself will implicitly route to backend fallback.
  224. # This is probably not great for the pure Python implementation.
  225. return k
  226. raise NotImplementedError(f"could not find kernel for {op} at dispatch key {k}")
  227. _higher_order_ops: dict[str, "HigherOrderOperator"] = {}
  228. _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS = [
  229. DispatchKey.PythonDispatcher, # type: ignore[attr-defined]
  230. DispatchKey.PythonTLSSnapshot, # type: ignore[attr-defined]
  231. DispatchKey.ADInplaceOrView,
  232. DispatchKey.BackendSelect,
  233. DispatchKey.AutocastCPU, # type: ignore[attr-defined]
  234. DispatchKey.AutocastCUDA, # type: ignore[attr-defined]
  235. DispatchKey.AutocastXPU, # type: ignore[attr-defined]
  236. ]
  237. class HigherOrderOperator(OperatorBase, abc.ABC):
  238. # The HigherOrderOperator will appear as torch.ops.higher_order.{name}
  239. #
  240. # If you're creating a new HigherOrderOperator, please do not change the
  241. # default. Adding operators to the global torch.ops namespace is a bad
  242. # practice due to name collisions.
  243. def __init__(self, name, *, cacheable=False):
  244. super().__init__()
  245. if type(self) is HigherOrderOperator:
  246. raise RuntimeError(
  247. "Direct instantiation of HigherOrderOperator is not allowed. Please subclass it."
  248. )
  249. self._name = name
  250. # Make _OPNamespace not scream, this whole name based association needs a good hard look
  251. self.__name__ = name
  252. _higher_order_ops[name] = self
  253. self._ns = "higher_order"
  254. self.__module__ = "torch.ops.higher_order"
  255. self._cacheable = cacheable
  256. self.non_fallthrough_keys = torch._C._dispatch_keyset_full()
  257. for dispatch_key in _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS:
  258. self.fallthrough(dispatch_key)
  259. # [NOTE] We have to register pre-dispatch key implementation
  260. # because sometimes HOP use aot-dispatch tracing to detect certain
  261. # mutations. This is problematic when we are functionalizing HOP
  262. # during pre-dispatch because when the inner tracer starts, it will see
  263. # that PreDispatch key is still active. In that case, we just redispatch
  264. # it to next key. This is only safe to do when PreDispatch key stack has no
  265. # active modes.
  266. def py_impl(
  267. self,
  268. k: Union[
  269. type[TorchDispatchMode],
  270. type[torch.Tensor],
  271. TransformType,
  272. DispatchKey,
  273. ],
  274. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  275. if isinstance(k, DispatchKey) and not self.non_fallthrough_keys.has(k):
  276. self.non_fallthrough_keys = self.non_fallthrough_keys.add(k)
  277. return super().py_impl(k)
  278. def py_autograd_impl(
  279. self,
  280. fn: Callable[_P, _T],
  281. ) -> Callable[_P, _T]:
  282. def maybe_run_autograd(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  283. if not torch.is_grad_enabled() or pytree.tree_all_only(
  284. torch.Tensor,
  285. lambda t: not t.requires_grad, # type: ignore[union-attr]
  286. (*args, kwargs),
  287. ):
  288. with torch._C._AutoDispatchBelowAutograd():
  289. return self(*args, **kwargs)
  290. from torch._higher_order_ops.utils import _has_gen_schema
  291. if _has_gen_schema(self):
  292. schema = self.gen_schema(*args, **kwargs)
  293. if any(arg.is_write for arg in schema.arguments):
  294. raise RuntimeError(
  295. f"The {self.name()} HigherOrderOperator does not currently support training "
  296. "with in-place input or buffer mutations "
  297. "If you require this feature, please submit an issue to PyTorch. "
  298. "Alternatively, consider creating your own custom autograd.Function. "
  299. )
  300. return fn(*args, **kwargs)
  301. self.py_impl(DispatchKey.Autograd)(maybe_run_autograd)
  302. return fn
  303. @property
  304. def namespace(self):
  305. return self._ns
  306. @final
  307. def cacheable(self) -> bool:
  308. from torch._functorch.autograd_function import AutogradFunctionApply
  309. return (
  310. self._cacheable
  311. or f"{self.__module__}.{self.__name__}"
  312. in torch._inductor.config.unsafe_marked_cacheable_functions
  313. or (
  314. isinstance(self, AutogradFunctionApply)
  315. and torch._functorch.config.autograd_cache_allow_custom_autograd_functions
  316. )
  317. )
  318. def fallthrough(self, dispatch_key):
  319. self.non_fallthrough_keys = self.non_fallthrough_keys.remove(dispatch_key)
  320. # Use positional-only argument to avoid naming collide with custom ops arguments
  321. # that are named "self".
  322. def dispatch(self, /, dispatch_key, *args, **kwargs):
  323. from torch.utils._python_dispatch import _get_current_dispatch_mode
  324. if dispatch_key in self._dispatch_cache:
  325. kernel = self._dispatch_cache[dispatch_key]
  326. assert not isinstance(kernel, DispatchKey)
  327. return kernel(*args, **kwargs)
  328. if dispatch_key == DispatchKey.FuncTorchDynamicLayerFrontMode:
  329. return dispatch_functorch(self, args, kwargs)
  330. if dispatch_key == DispatchKey.Python:
  331. # Keep the following 1:1 with handle_torch_function_no_python_arg_parser
  332. # in torch/csrc/utils/python_arg_parser.cpp
  333. overloaded_args_list = []
  334. def has_python_key(tensor):
  335. return torch._C._dispatch_keys(tensor).has("Python")
  336. def check_overloaded(arg):
  337. if isinstance(arg, torch.Tensor) and has_python_key(arg):
  338. overloaded_args_list.append(arg)
  339. for arg in (*args, *kwargs.values()):
  340. check_overloaded(arg)
  341. if isinstance(arg, (list, tuple)):
  342. for a in arg:
  343. check_overloaded(a)
  344. overloaded_args = tuple(overloaded_args_list)
  345. # Step 1: dispatch on any user TorchDispatchModes
  346. from torch.utils._python_dispatch import _pop_mode_temporarily
  347. curr_mode = _get_current_dispatch_mode()
  348. if curr_mode is not None:
  349. if type(curr_mode) in self.python_key_table:
  350. handler = self.python_key_table[type(curr_mode)]
  351. with _pop_mode_temporarily() as mode:
  352. # "natural" calling convention: (mode, *args, **kwargs)
  353. # TODO(rzou): we should support torch_dispatch calling convention too.
  354. result = handler(mode, *args, **kwargs)
  355. else:
  356. if curr_mode.supports_higher_order_operators:
  357. with _pop_mode_temporarily() as mode:
  358. return curr_mode.__torch_dispatch__(self, [], args, kwargs)
  359. else:
  360. raise NotImplementedError(
  361. f"There was no rule registered for HigherOrderOperator {self._name} and mode {curr_mode}."
  362. f"Hint: set {curr_mode}'s supports_higher_order_operators to True."
  363. f" This causes all higher order operators to pass through {curr_mode}'s __torch_dispatch__,"
  364. f" so handle them accordingly by"
  365. f" adding support for HigerOrderOperators (in this case, {self._name}) in"
  366. f" {curr_mode}.__torch_dispatch__ or"
  367. f" returning NotImplemented when not supported."
  368. )
  369. if result is not NotImplemented:
  370. return result
  371. # Step 2: dispatch on any subclasses
  372. for arg in overloaded_args:
  373. subclass_type = type(arg)
  374. if (
  375. subclass_type.__torch_dispatch__
  376. == torch._C._disabled_torch_dispatch_impl
  377. ):
  378. continue
  379. # In some case, people are using FakeTensor without a FakeTensorMode.
  380. # For example, some sparse arch model has a mix of FakeTensor and real
  381. # tensor for weights during lowering, and ppl tends to run eager evaluation
  382. # on the model without setting up the FakeTensorMode.
  383. # In this case, we pull FakeTensorMode impl.
  384. if subclass_type is torch._subclasses.fake_tensor.FakeTensor:
  385. subclass_type = torch._subclasses.fake_tensor.FakeTensorMode # type: ignore[assignment]
  386. handler = self.python_key_table[subclass_type]
  387. result = handler(arg.fake_mode, *args, **kwargs) # type: ignore[attr-defined]
  388. return result
  389. if subclass_type in self.python_key_table:
  390. handler = self.python_key_table[subclass_type]
  391. # "natural" calling convention: (*args, **kwargs)
  392. # TODO(rzou): we should support torch_dispatch calling convention too.
  393. result = handler(*args, **kwargs)
  394. else:
  395. raise NotImplementedError(
  396. f"There was no rule registered for HOP {self._name} and subclass {subclass_type}. "
  397. f"We recommend filing an issue."
  398. )
  399. if result is not NotImplemented:
  400. return result
  401. # All handlers returned NotImplemented
  402. raise TypeError(
  403. f"HigherOrderOperator '{self._name}' is not supported for the given input types. "
  404. f"This typically happens when using custom tensor types or dispatch modes that don't "
  405. f"have implementations for this operation.\n\n"
  406. f"Current mode: {curr_mode}\n"
  407. f"Input types: {[type(a).__name__ for a in overloaded_args]}\n\n"
  408. f"To fix this, can add support for '{self._name}' in {curr_mode}'s __torch_dispatch__\n"
  409. )
  410. functionality_key = torch._C._to_functionality_key(dispatch_key) # type: ignore[attr-defined]
  411. if functionality_key == DispatchKey.PreDispatch:
  412. from torch.utils._python_dispatch import _pop_mode_temporarily
  413. # The check for Python in the exclude set is so we properly respect `with no_dispatch()`
  414. # calls inside of a mode.
  415. if (
  416. _len_torch_dispatch_stack_pre_dispatch() > 0
  417. ) and not torch._C._dispatch_tls_is_dispatch_key_excluded(
  418. DispatchKey.Python
  419. ):
  420. curr_mode = _get_current_dispatch_mode_pre_dispatch()
  421. assert curr_mode is not None, (
  422. "Illegal invocation of dispatch on DispatchKey.PreDispatch without a mode."
  423. )
  424. assert type(curr_mode) in self.python_key_table, (
  425. f"Current active mode {curr_mode} not registered"
  426. )
  427. handler = self.python_key_table[type(curr_mode)]
  428. with _pop_mode_temporarily(functionality_key) as mode:
  429. return handler(mode, *args, **kwargs)
  430. final_key = resolve_key(self, dispatch_key)
  431. # This can current fail due to backend fallbacks. You just have to
  432. # register them by hand for HigherOrderOperator.
  433. if final_key not in self.py_kernels:
  434. raise NotImplementedError(
  435. f"could not find kernel for HigherOrderOperator {self._name} "
  436. f"at dispatch key {final_key} (resolved from {dispatch_key})"
  437. )
  438. # [NOTE] We shouldn't cache PreDispatch kernel here because depending
  439. # on what modes are active, predispatch behaviour is different.
  440. # Also we do same thing for normal ops:
  441. # See Note [Not Caching Per-Dispatch-Key Mode Handlers]
  442. if dispatch_key != DispatchKey.PreDispatch:
  443. self._dispatch_cache[dispatch_key] = self.py_kernels[final_key]
  444. kernel = self.py_kernels[final_key]
  445. # It's illegal to register DispatchKey to py_kernels, since there's no
  446. # C++ kernel to call into
  447. assert not isinstance(kernel, DispatchKey)
  448. return kernel(*args, **kwargs)
  449. @abc.abstractmethod
  450. def __call__(self, /, *args, **kwargs):
  451. def wrapper():
  452. flat_args = _to_flat_tuple(args, kwargs)
  453. if torch.overrides.has_torch_function(flat_args):
  454. return torch.overrides.handle_torch_function(
  455. self, flat_args, *args, **kwargs
  456. )
  457. dispatch_key_set = _compute_keyset(args, kwargs, self.non_fallthrough_keys)
  458. return self.dispatch(
  459. dispatch_key_set.highestPriorityTypeId(), *args, **kwargs
  460. )
  461. return wrapper()
  462. # NOTE [HigherOrderOprator Schema]
  463. # Each invocation of a HigherOrderOperator (hop) should have its own schema because
  464. # the subgraphs and the arguments can be different even for the same hop.
  465. #
  466. # Each hop should implement its own gen_schema method, which should
  467. # take the same input as the __call__ method and returns a FunctionSchema.
  468. # The schema provides a unified way to check if the hop mutates its inputs,
  469. # which can be useful in implementing optimizations.
  470. #
  471. # If the hop doesn't implement the gen_schema method,
  472. # we expect it to be functional. It should not mutate its inputs and there
  473. # are no input, output aliasing via views or direct referencing.
  474. def gen_schema(self, *args, **kwargs):
  475. raise NotImplementedError(
  476. f"HigherOrderOperator {self._name} does not implement a gen_schema. "
  477. f"This is OK as long as the hop is functional. "
  478. f"e.g. it should not mutate its inputs and there are no input, output aliasing "
  479. f"via views or direct referencing."
  480. )
  481. def __str__(self):
  482. return f"{self.name()}"
  483. def name(self):
  484. return self._name
  485. def _to_flat_tuple(args, kwargs):
  486. return pytree.arg_tree_leaves(*args, **kwargs)
  487. def _compute_keyset(args, kwargs, non_fallthrough_keys):
  488. tensors = _get_tensors(args, kwargs)
  489. return key_extractor(tensors, non_fallthrough_keys)
  490. def _get_tensors(args, kwargs):
  491. flat_all = _to_flat_tuple(args, kwargs)
  492. tensor_args = [t for t in flat_all if isinstance(t, torch.Tensor)]
  493. return tuple(tensor_args)
  494. # Note - this should maintain identical impl to the C++ dispatcher key extraction logic
  495. # at ATen/core/dispatch/DispatchKeyExtractor.h
  496. def key_extractor(tensors, key_mask):
  497. key_set = torch._C._dispatch_tls_local_include_set()
  498. for tensor in tensors:
  499. key_set = key_set | torch._C._dispatch_keys(tensor)
  500. key_set = key_set - torch._C._dispatch_tls_local_exclude_set()
  501. key_set = key_set & key_mask
  502. return key_set
  503. # Mode stack for PreDispatchKey
  504. # it should always have three keys with
  505. # priority given to FunctionalTensorMode and
  506. # then ProxyTorchDispatchMode. It means that
  507. # slot 0 belongs to ProxyTorchDispatchMode and
  508. # slot 1 belongs to FunctionalTensorMode.
  509. #
  510. # SchemaCheckMode is separate from the other 2,
  511. # and is only valid when the stack is empty.
  512. # SchemaCheckMode is for testing purposes, and
  513. # is meant to run in eager mode on concrete inputs,
  514. # checking for incorrect schemas in regards to
  515. # aliasing or mutating ops.
  516. class _ModeStackStateForPreDispatch:
  517. def __init__(self):
  518. self.__infra_modes = [None, None]
  519. self._schema_check_mode = None
  520. def set(self, index, mode):
  521. assert index < len(self.__infra_modes)
  522. self.__infra_modes[index] = mode
  523. def get(self, index):
  524. assert index < len(self.__infra_modes)
  525. return self.__infra_modes[index]
  526. def count(self):
  527. return len([i for i in self.__infra_modes if i is not None]) + int(
  528. self._schema_check_mode is not None
  529. )
  530. _mode_stack_state_for_pre_dispatch = _ModeStackStateForPreDispatch()
  531. def unset_mode_pre_dispatch(mode_key, schema_check=False):
  532. current_mode_stack_pre_dispatch = mode_stack_state_for_pre_dispatch()
  533. assert mode_key is None or mode_key in (
  534. torch._C._TorchDispatchModeKey.PROXY,
  535. torch._C._TorchDispatchModeKey.FUNCTIONAL,
  536. )
  537. if schema_check:
  538. assert mode_key is None
  539. def _unset_mode():
  540. if mode_key == torch._C._TorchDispatchModeKey.PROXY:
  541. current_mode = current_mode_stack_pre_dispatch.get(0)
  542. mode_stack_state_for_pre_dispatch().set(0, None)
  543. return current_mode
  544. elif mode_key == torch._C._TorchDispatchModeKey.FUNCTIONAL:
  545. current_mode = current_mode_stack_pre_dispatch.get(1)
  546. mode_stack_state_for_pre_dispatch().set(1, None)
  547. return current_mode
  548. else:
  549. current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode
  550. mode_stack_state_for_pre_dispatch()._schema_check_mode = None
  551. return current_mode
  552. current_mode = _unset_mode()
  553. new_pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch()
  554. # When we are unsetting a mode, we need to check if there is
  555. # active mode left on the PreDispatch key. If there is nothing
  556. # active, we need to remove PreDispatch key from local dispatch include
  557. # set.
  558. if new_pre_dispatch_len == 0:
  559. torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, False)
  560. return current_mode
  561. def _set_mode_pre_dispatch(mode):
  562. from torch._subclasses.functional_tensor import FunctionalTensorMode
  563. from torch._subclasses.schema_check_mode import SchemaCheckMode
  564. from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
  565. assert isinstance(
  566. mode,
  567. (
  568. FunctionalTensorMode,
  569. ProxyTorchDispatchMode,
  570. SchemaCheckMode,
  571. ),
  572. )
  573. previous_mode_stack_len = _len_torch_dispatch_stack_pre_dispatch()
  574. if isinstance(mode, SchemaCheckMode):
  575. current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode
  576. if previous_mode_stack_len > 0:
  577. raise AssertionError(
  578. "SchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stack"
  579. )
  580. mode_stack_state_for_pre_dispatch()._schema_check_mode = mode
  581. elif isinstance(mode, FunctionalTensorMode):
  582. current_mode = mode_stack_state_for_pre_dispatch().get(1)
  583. assert current_mode is None
  584. mode_stack_state_for_pre_dispatch().set(1, mode)
  585. else:
  586. current_mode = mode_stack_state_for_pre_dispatch().get(0)
  587. assert current_mode is None
  588. mode_stack_state_for_pre_dispatch().set(0, mode)
  589. # When we are setting a mode, we need to check if there is
  590. # active mode left on the PreDispatch key. If there was nothing
  591. # active before setting this mode, it means that PreDispatch key
  592. # was turned off. So we need to turn it on again.
  593. if previous_mode_stack_len == 0:
  594. torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, True)
  595. def _pop_mode_from_pre_dispatch():
  596. mode_stack = mode_stack_state_for_pre_dispatch()
  597. pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch()
  598. if pre_dispatch_len == 0:
  599. raise AssertionError("Trying to pop empty mode stack")
  600. if mode_stack._schema_check_mode is not None:
  601. return unset_mode_pre_dispatch(None, schema_check=True)
  602. if mode_stack.get(1) is not None:
  603. return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.FUNCTIONAL)
  604. if mode_stack.get(0) is not None:
  605. return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY)
  606. def _len_torch_dispatch_stack_pre_dispatch():
  607. return mode_stack_state_for_pre_dispatch().count()
  608. def _get_dispatch_mode_pre_dispatch(mode_key):
  609. assert mode_key in (
  610. torch._C._TorchDispatchModeKey.PROXY,
  611. torch._C._TorchDispatchModeKey.FUNCTIONAL,
  612. )
  613. if mode_key == torch._C._TorchDispatchModeKey.PROXY:
  614. return mode_stack_state_for_pre_dispatch().get(0)
  615. else:
  616. return mode_stack_state_for_pre_dispatch().get(1)
  617. def _get_current_dispatch_mode_pre_dispatch():
  618. if mode_stack_state_for_pre_dispatch()._schema_check_mode is not None:
  619. return mode_stack_state_for_pre_dispatch()._schema_check_mode
  620. else:
  621. stack_len = mode_stack_state_for_pre_dispatch().count()
  622. if stack_len == 2:
  623. return mode_stack_state_for_pre_dispatch().get(1)
  624. if stack_len == 1:
  625. return (
  626. mode_stack_state_for_pre_dispatch().get(1)
  627. if mode_stack_state_for_pre_dispatch().get(1) is not None
  628. else mode_stack_state_for_pre_dispatch().get(0)
  629. )
  630. return None
  631. def mode_stack_state_for_pre_dispatch():
  632. global _mode_stack_state_for_pre_dispatch
  633. return _mode_stack_state_for_pre_dispatch
  634. cached_ops: set["OpOverload"] = set()
  635. def add_cached_op(op_overload):
  636. global cached_ops
  637. cached_ops.add(op_overload)
  638. def reset_cached_ops():
  639. global cached_ops
  640. cached_ops.clear()
  641. def get_cached_ops():
  642. global cached_ops
  643. return cached_ops
  644. # Each OpOverload object contains pointer to a specific operator overload, a pointer to the parent `OpOverloadPacket` object.
  645. # You can obtain an OpOverload object through attribute query on OpOverloadPacket.
  646. class OpOverload(OperatorBase, Generic[_P, _T]):
  647. def __init__(
  648. self,
  649. overloadpacket: "OpOverloadPacket",
  650. op: Callable[_P, _T],
  651. op_dk: Callable[Concatenate[DispatchKey, _P], _T],
  652. schema: torch._C.FunctionSchema,
  653. tags: list[Any],
  654. ) -> None:
  655. super().__init__()
  656. self._op = op
  657. self._op_dk = op_dk
  658. self._schema = schema
  659. self._overloadpacket = overloadpacket
  660. self._tags = tags
  661. self._overloadname = (
  662. "default" if schema.overload_name == "" else schema.overload_name
  663. )
  664. if tags:
  665. self._nondeterministic_seeded = torch.Tag.nondeterministic_seeded in tags
  666. self._name = self._schema.name
  667. if schema.overload_name:
  668. self._name += "." + schema.overload_name
  669. self.__name__ = f"{self._schema.name.split('::')[1]}.{self._overloadname}"
  670. self.__module__ = overloadpacket.__module__
  671. op.__module__ = overloadpacket.__module__
  672. self.__qualname__ = self._name
  673. self.__annotations__ = {}
  674. # If the OpOverload was constructed from a Library.def in Python.
  675. self._defined_in_python = self.__qualname__ in torch.library._defs
  676. # Logic replicated from aten/src/ATen/native/MathBitsFallback.h
  677. is_write = None
  678. for a in self._schema.arguments:
  679. if a.alias_info is None:
  680. continue
  681. if is_write is None:
  682. is_write = a.alias_info.is_write
  683. else:
  684. # We will conservatively call mixed mutable/non-mutable
  685. # aliased inputs as NOT a view
  686. is_write = a.alias_info.is_write or is_write
  687. self.is_view = is_write is not None and not is_write
  688. @cached_property
  689. def _namespace(self) -> str:
  690. return self._schema.name.split("::", maxsplit=1)[0]
  691. @cached_property
  692. def _opname(self) -> str:
  693. return self._schema.name.split("::", maxsplit=1)[1]
  694. @cached_property
  695. def _handle(self) -> torch._C._DispatchOperatorHandle:
  696. return torch._C._dispatch_find_schema_or_throw(
  697. self._schema.name, self._schema.overload_name
  698. )
  699. # it's a no-op since OpOverload object is immutable and must be unique for a given op overload.
  700. def __deepcopy__(self, memo=None):
  701. return self
  702. def __repr__(self):
  703. return f"<OpOverload(op='{self._namespace}.{self._opname}', overload='{self._overloadname}')>"
  704. # Use positional-only argument to avoid naming collision with aten ops arguments
  705. # that are named "self". This way, all the aten ops can be called by kwargs.
  706. def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  707. return self._op(*args, **kwargs)
  708. # Use positional-only argument to avoid naming collision with aten ops arguments
  709. # that are named "self". This way, all the aten ops can be called by kwargs.
  710. def redispatch(
  711. self, /, keyset: torch._C.DispatchKeySet, *args: _P.args, **kwargs: _P.kwargs
  712. ) -> _T:
  713. return self._handle.redispatch_boxed(keyset, *args, **kwargs) # type: ignore[return-value]
  714. def __hash__(self):
  715. return hash(self._op)
  716. # `my_namespace.my_op_name.overload_name`
  717. def __str__(self):
  718. return "{}.{}.{}".format(*self._schema.name.split("::"), self._overloadname)
  719. def has_kernel_for_dispatch_key(self, k: DispatchKey) -> bool:
  720. return super().has_kernel_for_dispatch_key(
  721. k
  722. ) or torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), k)
  723. def has_kernel_for_any_dispatch_key(self, ks: torch._C.DispatchKeySet) -> bool:
  724. return torch._C._dispatch_has_kernel_for_any_dispatch_key(
  725. self.name(), ks
  726. ) or super().has_kernel_for_any_dispatch_key(ks)
  727. @property
  728. def namespace(self) -> str:
  729. return self._namespace
  730. def _can_decompose(self) -> bool:
  731. dk = DispatchKey.CompositeImplicitAutograd
  732. return dk in self.py_kernels or torch._C._dispatch_has_kernel_for_dispatch_key(
  733. self.name(), dk
  734. )
  735. def decompose(self, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  736. dk = DispatchKey.CompositeImplicitAutograd
  737. if dk in self.py_kernels:
  738. # NB: This branch is not too necessary anymore, because we can
  739. # apply Python CompositeImplicitAutograd *before* tracing
  740. # using Python dispatcher (also taking advantage of the autograd
  741. # formula). But it's included for completeness
  742. return self.py_kernels[dk](*args, **kwargs)
  743. elif torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), dk):
  744. return self._op_dk(dk, *args, **kwargs)
  745. else:
  746. return NotImplemented
  747. # Remove a dispatch key from the dispatch cache. This will force it to get
  748. # recomputed the next time. Does nothing
  749. # WARNING: if you register a dispatch key to py_kernels of an OpOverload,
  750. # calling _del_dispatch on that key is NOT sufficient to apply your change,
  751. # because a single registration may affect MULTIPLE dispatch keys (e.g.,
  752. # registering Autograd affects AutogradCPU). del_dispatch is to be used
  753. # only if you are specifically modifying how get_dispatch handles a
  754. # particular input 'key'.
  755. def _uncache_dispatch(self, key: DispatchKey) -> None:
  756. self._dispatch_cache.pop(key, None)
  757. # This implements the pre-computation logic for the Python dispatcher.
  758. def _get_dispatch(self, key: DispatchKey) -> Union[DispatchKey, Callable[_P, _T]]:
  759. # This is only called upon a cache miss
  760. assert key not in self._dispatch_cache, f"{self} {key}"
  761. if key == DispatchKey.Python:
  762. if not isinstance(self, TorchBindOpOverload) and not self.python_key_table:
  763. self._dispatch_cache[key] = key
  764. add_cached_op(self)
  765. return key
  766. def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  767. from torch.utils._python_dispatch import _get_current_dispatch_mode
  768. # TODO: We also need to handle tensor subclasses here
  769. # TODO(voz): We should walk all the nodes here / turn it into a list, topmode is ok for now.
  770. curr_mode = type(_get_current_dispatch_mode())
  771. assert curr_mode is not None, (
  772. "Illegal invocation of dispatch on DispatchKey.Python without a mode."
  773. )
  774. if curr_mode not in self.python_key_table:
  775. if isinstance(self, TorchBindOpOverload):
  776. with (
  777. torch.utils._python_dispatch._pop_mode_temporarily() as mode
  778. ):
  779. return torch._library.utils.handle_dispatch_mode(
  780. mode, self, *args, **kwargs
  781. )
  782. else:
  783. return self._op_dk(key, *args, **kwargs)
  784. with torch.utils._python_dispatch._pop_mode_temporarily() as mode:
  785. return self.python_key_table[curr_mode](mode, *args, **kwargs)
  786. self._dispatch_cache[key] = handler
  787. add_cached_op(self)
  788. return handler
  789. functionality_key = torch._C._to_functionality_key(key) # type: ignore[attr-defined]
  790. if functionality_key == DispatchKey.PreDispatch:
  791. curr_stack_len = _len_torch_dispatch_stack_pre_dispatch()
  792. # The check for Python in the exclude set is so we properly respect `with no_dispatch()`
  793. # calls inside of a mode.
  794. if (
  795. curr_stack_len > 0
  796. and not torch._C._dispatch_tls_is_dispatch_key_excluded(
  797. DispatchKey.Python
  798. )
  799. ):
  800. def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  801. @contextlib.contextmanager
  802. def _temporarily_pop_modes_from_pre_dispatch():
  803. top_mode = _pop_mode_from_pre_dispatch()
  804. try:
  805. yield top_mode
  806. finally:
  807. _set_mode_pre_dispatch(top_mode)
  808. with _temporarily_pop_modes_from_pre_dispatch() as curr_mode:
  809. return torch._library.utils.handle_dispatch_mode(
  810. curr_mode, self, *args, **kwargs
  811. )
  812. # Note [Not Caching Per-Dispatch-Key Mode Handlers]
  813. # Note that we're not caching this handler. There isn't really a point, since the slow bit
  814. # is the handler itself (in python).
  815. # Also, not caching means that we don't have to reset the cache when any existing
  816. # modes go out of scope (which in of itself takes time to loop through all operators).
  817. return handler
  818. final_key = resolve_key(self, key)
  819. # See Note [Not Caching Per-Dispatch-Key Mode Handlers]
  820. cache_result = key != DispatchKey.PreDispatch
  821. # TODO: We could potentially have lots of debugging wrappers against
  822. # dispatch keys; design some general registration mechanism instead of
  823. # having if statement for each of them
  824. if key == DispatchKey.Functionalize:
  825. import torch._dispatch.python as pydispatch
  826. if pydispatch.CROSSREF_FUNCTIONALIZE:
  827. handler = pydispatch.make_crossref_functionalize(self, final_key) # type: ignore[assignment]
  828. if cache_result:
  829. self._dispatch_cache[key] = handler
  830. add_cached_op(self)
  831. return handler
  832. r = self.py_kernels.get(final_key, final_key)
  833. if cache_result:
  834. self._dispatch_cache[key] = r
  835. add_cached_op(self)
  836. return r
  837. def name(self):
  838. return self._name
  839. @property
  840. def overloadpacket(self):
  841. return self._overloadpacket
  842. @property
  843. def op(self):
  844. return self._op
  845. @property
  846. def tags(self):
  847. return self._tags
  848. # TODO: add more methods to expose information about input and output arguments
  849. # TorchBindOpOverload are those custom ops which have at least one overload's
  850. # schema consists of torch.ScriptObject (i.e. custom class) input.
  851. # TorchBindOpOverload will skip C++ dispatcher and purely dispatched in python
  852. # when its inputs contain FakeScriptObject in a similar way as higher order ops.
  853. class TorchBindOpOverload(OpOverload[_P, _T]):
  854. def _fallthrough_keys(self) -> list[DispatchKey]:
  855. # TODO: we should be calling the fallback for these, but a fallthrough is almost close
  856. # enough to the fallback in most cases that we care about.
  857. _DEFAULT_FALLTHROUGH_KEYS = [
  858. DispatchKey.Autograd,
  859. DispatchKey.AutogradCPU,
  860. DispatchKey.AutogradCUDA,
  861. DispatchKey.ADInplaceOrView,
  862. DispatchKey.BackendSelect,
  863. DispatchKey.PythonTLSSnapshot,
  864. DispatchKey.PythonDispatcher,
  865. ]
  866. def _may_use_fallthrough_instead_of_fallback(key: DispatchKey):
  867. if torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), key):
  868. return torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough(
  869. self.name(), key
  870. )
  871. return (
  872. key not in self.py_kernels
  873. or self.py_kernels[key] is torch.library.fallthrough_kernel
  874. )
  875. return [
  876. key
  877. for key in _DEFAULT_FALLTHROUGH_KEYS
  878. if _may_use_fallthrough_instead_of_fallback(key)
  879. ]
  880. @contextlib.contextmanager
  881. def _register_as_effectful_op_temporarily(self):
  882. from torch._higher_order_ops.effects import (
  883. _EffectType,
  884. _register_effectful_op,
  885. SIDE_EFFECTS,
  886. )
  887. try:
  888. if self not in SIDE_EFFECTS:
  889. _register_effectful_op(self, _EffectType.ORDERED)
  890. yield
  891. finally:
  892. if self in SIDE_EFFECTS:
  893. del SIDE_EFFECTS[self]
  894. # Use positional-only argument to avoid naming collision with aten ops arguments
  895. # that are named "self". This way, all the aten ops can be called by kwargs.
  896. def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  897. if _must_dispatch_in_python(args, kwargs):
  898. # When any inputs are FakeScriptObject, we need to
  899. # skip c++ dispatcher and dispatch in python through _get_dispatch of python_dispatcher
  900. # because C++ dispatcher will check the schema and cannot recognize FakeScriptObject.
  901. #
  902. # Note:
  903. # 1. We only register the torchbind op temporarily as effectful op because we only want
  904. # the effect token functionalization logic to be applied during tracing. Otherwise, the behavior
  905. # of the eagerly executing the op might change after tracing.
  906. # 2. We don't want to register the op as effectful for all torchbind ops in ctor because this might
  907. # cause unexpected behavior for some autograd.profiler ops e.g. profiler._record_function_exit._RecordFunction.
  908. with self._register_as_effectful_op_temporarily():
  909. return self._dispatch_in_python(
  910. self._fallthrough_keys(), *args, **kwargs
  911. )
  912. return self._op(*args, **kwargs)
  913. def _dispatch_in_python(
  914. self, fallthrough_keys: list[DispatchKey], *args: _P.args, **kwargs: _P.kwargs
  915. ) -> _T:
  916. non_fallthrough_keys = torch._C._dispatch_keyset_full()
  917. for key in fallthrough_keys:
  918. non_fallthrough_keys = non_fallthrough_keys.remove(key)
  919. dispatch_key_set = _compute_keyset(args, kwargs, non_fallthrough_keys)
  920. dispatch_key = dispatch_key_set.highestPriorityTypeId()
  921. handler = (
  922. self._get_dispatch(dispatch_key)
  923. if dispatch_key not in self._dispatch_cache
  924. else self._dispatch_cache[dispatch_key]
  925. )
  926. if isinstance(handler, DispatchKey):
  927. # fallthrough keys can be registered at runtime via torch.library.impl
  928. # so need to add it to fallthrough_keys and re-dispatch.
  929. if torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough(
  930. self.name(), dispatch_key
  931. ):
  932. return self._dispatch_in_python(
  933. fallthrough_keys + [dispatch_key],
  934. *args,
  935. **kwargs,
  936. )
  937. raise RuntimeError(
  938. f"Torchbind op {self} received a FakeScriptObject input when dispatching {handler}."
  939. f" but no python implementation is found."
  940. f" Please file an issue on this when you encounter this error."
  941. f" This error can happen when you export or compile the model."
  942. f" It can still happen even if a C++ implementation for {dispatch_key}. "
  943. f" has been registered. That's because FakeScriptObject purely lives in python and cannot work "
  944. f" with a C++ implementation."
  945. )
  946. assert isinstance(handler, Callable) # type: ignore[arg-type]
  947. return handler(*args, **kwargs)
  948. def _must_dispatch_in_python(args, kwargs):
  949. return pytree.tree_any(
  950. lambda obj: isinstance(
  951. obj, torch._library.fake_class_registry.FakeScriptObject
  952. ),
  953. (args, kwargs),
  954. )
  955. def _has_script_object_arg(schema: torch.FunctionSchema) -> bool:
  956. return any(isinstance(arg.type, torch.ClassType) for arg in schema.arguments)
  957. # OpOverloadPacket class contains pointer to a base unresolved operator that doesn't correspond to a specific operator
  958. # You can obtain an OpOverload object through attribute query.
  959. class OpOverloadPacket(Generic[_P, _T]):
  960. __file__: ClassVar[str] = "torch.ops"
  961. def __init__(
  962. self,
  963. qualified_op_name: str,
  964. op_name: str,
  965. op: Callable[_P, _T],
  966. overload_names: list[str],
  967. ) -> None:
  968. # These attributes are accessible on the object through the properties
  969. # defined below but are immutable
  970. self._qualified_op_name = qualified_op_name
  971. self.__name__ = op_name
  972. self._op = op
  973. self._overload_names = overload_names
  974. self._dir: list[str] = []
  975. self._has_torchbind_op_overload = any(
  976. _has_script_object_arg(schema) for schema in self._schemas.values()
  977. )
  978. # it's a no-op since OpOverloadPacket object is immutable and must be unique for a given op.
  979. def __deepcopy__(self, memo=None):
  980. return self
  981. def __repr__(self):
  982. return "<OpOverloadPacket(op='{}.{}')>".format(
  983. *self._qualified_op_name.split("::")
  984. )
  985. def __hash__(self):
  986. return hash(self._op)
  987. def __str__(self):
  988. return "{}.{}".format(*self._qualified_op_name.split("::"))
  989. @property
  990. def op(self):
  991. return self._op
  992. @property
  993. def _schemas(self):
  994. return {
  995. overload_name: torch._C._get_schema(self._qualified_op_name, overload_name)
  996. for overload_name in self._overload_names
  997. }
  998. def __getattr__(self, key: str) -> OpOverload[_P, _T]:
  999. # ensure that query for dunder attributes that does not exist on
  1000. # opoverloadpacket but instead exists on the self._op object does not unnecessarily call
  1001. # `_get_operation_overload` (which is an expensive operation).
  1002. # This is done to prevent any potential slowdown. This list can be extended
  1003. # if there exists other attributes like `__name__` that only exist on self._op and not on the
  1004. # opoverloadpacket.
  1005. # This is ok since we are guaranteed that an overload name for an aten op can't start with '__'
  1006. try:
  1007. if key.startswith("__"):
  1008. return getattr(self._op, key)
  1009. except AttributeError:
  1010. # for consistency because it seems weird to
  1011. # throw an attribute error with a message containing
  1012. # an object name different from the one the attribute
  1013. # query was performed on.
  1014. raise AttributeError(
  1015. f"'{str(self)}' can't have an overload name beginning with '__' and the "
  1016. f"underlying op {str(self._op)} has no attribute {key} either."
  1017. ) from None
  1018. try:
  1019. # This is ok since we are guaranteed that an overload name for an aten op can't be 'default'
  1020. use_key = "" if key == "default" else key
  1021. # TODO: disallow access to overloads registered by JIT
  1022. op_dk_tags = torch._C._get_operation_overload(
  1023. self._qualified_op_name, use_key
  1024. )
  1025. if op_dk_tags is None:
  1026. raise AttributeError(
  1027. f"The underlying op of '{str(self)}' has no overload name '{key}'"
  1028. )
  1029. op_, op_dk_, tags = op_dk_tags
  1030. schema = torch._C._get_schema(self._qualified_op_name, use_key)
  1031. overload: OpOverload[_P, _T] = (
  1032. OpOverload(self, op_, op_dk_, schema, tags)
  1033. if not _has_script_object_arg(schema)
  1034. else TorchBindOpOverload(self, op_, op_dk_, schema, tags)
  1035. )
  1036. # cache the overload object
  1037. setattr(self, key, overload)
  1038. self._dir.append(key)
  1039. return overload
  1040. except RuntimeError:
  1041. raise AttributeError(
  1042. f"The underlying op of '{str(self)}' has no overload name '{key}'"
  1043. ) from None
  1044. def __iter__(self) -> Iterator[str]:
  1045. return iter(self._dir)
  1046. # Use positional-only argument to avoid naming collision with aten ops arguments
  1047. # that are named "self". This way, all the aten ops can be called by kwargs.
  1048. def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  1049. # overloading __call__ to ensure torch.ops.foo.bar()
  1050. # is still callable from JIT
  1051. # We save the function ptr as the `op` attribute on
  1052. # OpOverloadPacket to access it here.
  1053. # Directly calling OverloadPacket goes into C++, which will check
  1054. # the schema and cause an error for torchbind op when inputs consist of FakeScriptObject so we
  1055. # intercept it here and call TorchBindOpverload instead.
  1056. if self._has_torchbind_op_overload and _must_dispatch_in_python(args, kwargs):
  1057. return _call_overload_packet_from_python(self, *args, **kwargs)
  1058. return self._op(*args, **kwargs)
  1059. # TODO: use this to make a __dir__
  1060. def overloads(self):
  1061. return [n if n else "default" for n in self._overload_names]
  1062. # Note - this mirrors the logic of the cpp_function defined in jit/python/init.cpp
  1063. # _jit_get_operations, which calls _get_operation_for_overload_or_packet.
  1064. def _call_overload_packet_from_python(
  1065. op: OpOverloadPacket[_P, _T], *args: _P.args, **kwargs: _P.kwargs
  1066. ) -> _T:
  1067. # Reuse the torch function handling logic in cpp
  1068. torch_function_called, ret = torch._C._maybe_call_torch_function_for_op_packet(
  1069. op, *args, **kwargs
  1070. )
  1071. if torch_function_called:
  1072. return ret
  1073. # The following mirrors getOpWithStack.
  1074. # In cpp, we do a schema matching for the arguments, and call ToIValue to
  1075. # to check whether the arguments are valid. But need to do similar things here
  1076. # and check the schema whether the FakeScriptObject is the corresponding fake class
  1077. # of the actual class used in schema.
  1078. exceptions = {}
  1079. found_op = None
  1080. for overload_name in op.overloads():
  1081. op_overload = getattr(op, overload_name)
  1082. try:
  1083. _ = torch._C._check_schema_allow_fake_script_object(
  1084. op_overload._schema, *args, **kwargs
  1085. )
  1086. found_op = op_overload
  1087. break
  1088. except RuntimeError as e:
  1089. exceptions[overload_name] = e
  1090. if found_op:
  1091. return found_op(*args, **kwargs)
  1092. err_msg = (
  1093. f"Fail to match any TorchBindOverload of {op} with following exceptions:\n"
  1094. )
  1095. for key, msg in exceptions.items():
  1096. err_msg += f"Overload name {key}:\n {msg}\n"
  1097. raise RuntimeError(err_msg)
  1098. # Resolution of torch.fn is different from torch.ops.aten.fn
  1099. # torch.fn uses the Python argparser, matches with the
  1100. # appropriate schema, and calls into the unboxed version of the method
  1101. # torch.ops.aten.fn resolution is done via the mechanism defined in JIT.
  1102. # JIT creates a stack of all the overloads and then tries to match the
  1103. # correct one at runtime and always calls into the boxed version of the method
  1104. # Autograd codegen creates VariableType, TracerType,
  1105. # inplace or view type and python bindings.
  1106. # Aten codegen generates tensor methods for the tensor class.
  1107. # _OpNamespace is a subclass of ModuleType because the torch script
  1108. # allows attribute lookups on modules only. Since we want torch.ops.foo.bar()
  1109. # to work from script, we need to ensure ops and foo are modules
  1110. class _OpNamespace(types.ModuleType):
  1111. """
  1112. An op namespace to dynamically bind Operators into Python.
  1113. Say a user has created a custom Operator called "my_namespace::my_op". To
  1114. call this op, the user will write torch.ops.my_namespace.my_op(...).
  1115. At startup, this operation will not yet be bound into Python. Instead, the
  1116. following sequence of magic tricks will occur:
  1117. 1. `torch.ops.my_namespace` will invoke the `__getattr__` magic method
  1118. on the `torch.ops` object, which will create a new `_OpNamespace`
  1119. object called `my_namespace` and set it as an attribute on the `ops`
  1120. object.
  1121. 2. `torch.ops.my_namespace.my_op` will then invoke `__getattr__` on
  1122. the `my_namespace` object, which will retrieve the operation via
  1123. `torch.get_operation`, a function bound from C++, and then in a similar
  1124. fashion bind this new object onto the `my_namespace` object.
  1125. 3. `torch.ops.my_namespace.my_op(...)` then calls this new operation
  1126. and subsequent accesses will incur no further lookup (the namespace and
  1127. operation will already exist).
  1128. """
  1129. __file__ = "torch.ops"
  1130. def __init__(self, name: str) -> None:
  1131. super().__init__("torch.ops." + name)
  1132. self.name = name
  1133. self._dir: list[str] = []
  1134. def __iter__(self) -> Iterator[str]:
  1135. return iter(self._dir)
  1136. def __getattr__(self, op_name: str) -> OpOverloadPacket:
  1137. if op_name in ("__origin__", "__self__"):
  1138. raise AttributeError(
  1139. f"Invalid attribute '{op_name}' for '_OpNamespace' '{self.name}'"
  1140. )
  1141. # Get the op `my_namespace::my_op` if available. This will also check
  1142. # for overloads and raise an exception if there are more than one.
  1143. namespace_name = self.name
  1144. qualified_op_name = f"{namespace_name}::{op_name}"
  1145. module_name = self.__module__ + "." + namespace_name
  1146. try:
  1147. op, overload_names = _get_packet(qualified_op_name, module_name)
  1148. if op is None:
  1149. raise AttributeError(
  1150. f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'"
  1151. )
  1152. except RuntimeError as e:
  1153. # Turn this into AttributeError so getattr(obj, key, default)
  1154. # works (this is called by TorchScript with __origin__)
  1155. raise AttributeError(
  1156. f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'"
  1157. ) from e
  1158. op.__module__ = module_name
  1159. opoverloadpacket = OpOverloadPacket(
  1160. qualified_op_name, op_name, op, overload_names
  1161. )
  1162. opoverloadpacket.__module__ = self.__module__ + "." + namespace_name
  1163. # cache the opoverloadpacket to ensure that each op corresponds to
  1164. # a unique OpOverloadPacket object
  1165. setattr(self, op_name, opoverloadpacket)
  1166. self._dir.append(op_name)
  1167. return opoverloadpacket
  1168. def _get_packet(qualname, op_module):
  1169. op, overload_names = torch._C._jit_get_operation(qualname)
  1170. if op is not None:
  1171. # let the script frontend know that op is identical to the builtin op
  1172. # with qualified_op_name
  1173. torch.jit._builtins._register_builtin(op, qualname)
  1174. op.__module__ = op_module
  1175. return op, overload_names
  1176. def _refresh_packet(packet):
  1177. op, overload_names = _get_packet(packet._qualified_op_name, packet._op.__module__)
  1178. assert op is not None
  1179. packet._op = op
  1180. packet._overload_names = overload_names
  1181. class _HigherOrderNamespace(types.ModuleType):
  1182. __file__ = "torch.ops"
  1183. def __init__(self) -> None:
  1184. super().__init__("torch.ops.higher_order")
  1185. self._dir: list[str] = []
  1186. def __iter__(self) -> Iterator[str]:
  1187. return iter(self._dir)
  1188. def __getattr__(self, name: str) -> HigherOrderOperator:
  1189. # Following _OpNamespace.__getattr__, we cache the op on this object.
  1190. op = _higher_order_ops.get(name, None)
  1191. if op is None:
  1192. raise AttributeError(
  1193. f"'_HigherOrderNamespace' 'torch.ops.higher_order' object has no attribute '{name}'"
  1194. )
  1195. setattr(self, name, op)
  1196. self._dir.append(name)
  1197. return op
  1198. class _Ops(types.ModuleType):
  1199. __file__ = "_ops.py"
  1200. def __init__(self):
  1201. super().__init__("torch.ops")
  1202. self.loaded_libraries = set()
  1203. self.higher_order = _HigherOrderNamespace()
  1204. self._dir = []
  1205. def __getattr__(self, name: str) -> _OpNamespace:
  1206. # Here we are creating `torch.ops.my_namespace`
  1207. namespace = _OpNamespace(name)
  1208. setattr(self, name, namespace)
  1209. self._dir.append(name)
  1210. return namespace
  1211. def __iter__(self) -> Iterator[str]:
  1212. return iter(self._dir)
  1213. def import_module(self, module):
  1214. """
  1215. Imports a Python module that has torch.library registrations.
  1216. Generally, to extend PyTorch with custom operators, a user will
  1217. create a Python module whose import triggers registration of
  1218. the custom operators via a torch.ops.load_library call or a call
  1219. to one or more torch.library.* APIs.
  1220. It is unexpected for Python modules to have side effects, so some
  1221. linters and formatters will complain. Use this API to import Python
  1222. modules that contain these torch.library side effects.
  1223. Args:
  1224. module (str): The name of the Python module to import
  1225. """
  1226. importlib.import_module(module)
  1227. def load_library(self, path):
  1228. """
  1229. Loads a shared library from the given path into the current process.
  1230. The library being loaded may run global initialization code to register
  1231. custom operators with the PyTorch JIT runtime. This allows dynamically
  1232. loading custom operators. For this, you should compile your operator
  1233. and the static registration code into a shared library object, and then
  1234. call ``torch.ops.load_library('path/to/libcustom.so')`` to load the
  1235. shared object.
  1236. After the library is loaded, it is added to the
  1237. ``torch.ops.loaded_libraries`` attribute, a set that may be inspected
  1238. for the paths of all libraries loaded using this function.
  1239. Args:
  1240. path (str): A path to a shared library to load.
  1241. """
  1242. path = _utils_internal.resolve_library_path(path)
  1243. with dl_open_guard():
  1244. # Import the shared library into the process, thus running its
  1245. # static (global) initialization code in order to register custom
  1246. # operators with the JIT.
  1247. try:
  1248. ctypes.CDLL(path)
  1249. except Exception as e:
  1250. raise OSError(f"Could not load this library: {path}") from e
  1251. self.loaded_libraries.add(path)
  1252. # The ops "namespace"
  1253. ops: _Ops = _Ops()