_ops.py 62 KB

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