library.py 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import functools
  4. import inspect
  5. import re
  6. import sys
  7. import traceback
  8. import weakref
  9. from collections.abc import Callable, Sequence
  10. from typing import Any, overload, TYPE_CHECKING, TypeVar, Union
  11. from typing_extensions import deprecated, ParamSpec
  12. import torch
  13. import torch._library as _library
  14. from torch._library.custom_ops import (
  15. _cast,
  16. _maybe_get_opdef,
  17. custom_op,
  18. CustomOpDef,
  19. device_types_t,
  20. )
  21. from torch._library.effects import EffectType
  22. from torch._library.infer_schema import infer_schema # noqa: F401
  23. from torch._library.triton import triton_op, wrap_triton
  24. from torch._ops import OpOverload
  25. from torch.types import _dtype
  26. __all__ = [
  27. "Library",
  28. "impl",
  29. "define",
  30. "fallthrough_kernel",
  31. "impl_abstract",
  32. "register_autocast",
  33. "register_fake",
  34. "register_torch_dispatch",
  35. "register_vmap",
  36. "get_ctx",
  37. "get_kernel",
  38. "custom_op",
  39. "triton_op",
  40. "wrap_triton",
  41. "infer_schema",
  42. ]
  43. _T = TypeVar("_T")
  44. _P = ParamSpec("_P")
  45. # Set containing the combination of (namespace, operator, DispatchKey) for which a new kernel has been registered
  46. # The keys in the set are of the form `namespace + "/" + op_name + "/" + dispatch_key`.
  47. # This set is maintained to ensure that two libraries don't try to override the exact same functionality to avoid
  48. # libraries calling into kernels not intended to be called.
  49. _impls: set[str] = set()
  50. _defs: set[str] = set()
  51. # prim is reserved by TorchScript interpreter
  52. _reserved_namespaces = ["prim"]
  53. def fallthrough_kernel():
  54. """
  55. A dummy function to pass to ``Library.impl`` in order to register a fallthrough.
  56. """
  57. raise NotImplementedError("fallthrough_kernel() should never be called.")
  58. class Library:
  59. """
  60. A class to create libraries that can be used to register new operators or
  61. override operators in existing libraries from Python.
  62. A user can optionally pass in a dispatch keyname if they only want to register
  63. kernels corresponding to only one specific dispatch key.
  64. To create a library to override operators in an existing library (with name ns), set the kind to "IMPL".
  65. To create a new library (with name ns) to register new operators, set the kind to "DEF".
  66. To create a fragment of a possibly existing library to register operators (and bypass
  67. the limitation that there is only one library for a given namespace), set the kind to
  68. "FRAGMENT".
  69. Args:
  70. ns: library name
  71. kind: "DEF", "IMPL", "FRAGMENT"
  72. dispatch_key: PyTorch dispatch key (default: "")
  73. """
  74. def __init__(self, ns, kind, dispatch_key=""):
  75. from torch.fx.operator_schemas import _SCHEMA_TO_SIGNATURE_CACHE
  76. if kind not in ("IMPL", "DEF", "FRAGMENT"):
  77. raise ValueError("Unsupported kind: ", kind)
  78. if ns in _reserved_namespaces and (kind == "DEF" or kind == "FRAGMENT"):
  79. raise ValueError(
  80. ns,
  81. " is a reserved namespace. Please try creating a library with another name.",
  82. )
  83. frame = traceback.extract_stack(limit=2)[0]
  84. filename, lineno = frame.filename, frame.lineno
  85. self.m: Any | None = torch._C._dispatch_library(
  86. kind, ns, dispatch_key, filename, lineno
  87. )
  88. self.ns = ns
  89. self._op_defs: set[str] = set()
  90. self._op_impls: set[str] = set()
  91. self._registration_handles: list[torch._library.utils.RegistrationHandle] = []
  92. self.kind = kind
  93. self.dispatch_key = dispatch_key
  94. # Use a finalizer to setup the "destructor" instead of __del__.
  95. # Python __del__ can lead to weird things (globals and locals may already
  96. # be gone when __del__ actually gets called!). finalizers help the
  97. # situation because it lets us capture references and keeps them alive
  98. weakref.finalize(
  99. self,
  100. _del_library,
  101. _impls,
  102. self._op_impls,
  103. _defs,
  104. self._op_defs,
  105. self._registration_handles,
  106. self.m,
  107. _SCHEMA_TO_SIGNATURE_CACHE,
  108. )
  109. def __repr__(self):
  110. return f"Library(kind={self.kind}, ns={self.ns}, dispatch_key={self.dispatch_key})>"
  111. def define(self, schema, alias_analysis="", *, tags=()):
  112. r"""Defines a new operator and its semantics in the ns namespace.
  113. Args:
  114. schema: function schema to define a new operator.
  115. alias_analysis (optional): Indicates if the aliasing properties of the operator arguments can be
  116. inferred from the schema (default behavior) or not ("CONSERVATIVE").
  117. tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this
  118. operator. Tagging an operator changes the operator's behavior
  119. under various PyTorch subsystems; please read the docs for the
  120. torch.Tag carefully before applying it.
  121. Returns:
  122. name of the operator as inferred from the schema.
  123. Example::
  124. >>> my_lib = Library("mylib", "DEF")
  125. >>> my_lib.define("sum(Tensor self) -> Tensor")
  126. """
  127. # This is added because we also want to disallow PURE_FUNCTION alias analysis which is a valid
  128. # AliasAnalysis type in C++
  129. if alias_analysis not in ["", "FROM_SCHEMA", "CONSERVATIVE"]:
  130. raise RuntimeError(f"Invalid alias_analysis type {alias_analysis}")
  131. if self.m is None:
  132. raise AssertionError("Library object has been destroyed")
  133. if isinstance(tags, torch.Tag):
  134. tags = (tags,)
  135. name = schema.split("(")[0]
  136. packet_name = name.split(".")[0] if "." in name else name
  137. has_preexisting_packet = hasattr(torch.ops, self.ns) and hasattr(
  138. getattr(torch.ops, self.ns), packet_name
  139. )
  140. result = self.m.define(schema, alias_analysis, tuple(tags))
  141. name = schema.split("(")[0]
  142. qualname = self.ns + "::" + name
  143. # If the OpOverloadPacket exists already, then this means we're adding a
  144. # new OpOverload for it. Refresh the packet to include the new OpOverload.
  145. if has_preexisting_packet:
  146. ns = getattr(torch.ops, self.ns)
  147. packet = getattr(ns, packet_name)
  148. torch._ops._refresh_packet(packet)
  149. self._op_defs.add(qualname)
  150. _defs.add(qualname)
  151. return result
  152. def _register_fake(self, op_name, fn, _stacklevel=1, *, allow_override=False):
  153. r"""Registers the fake impl for an operator defined in the library."""
  154. source = torch._library.utils.get_source(_stacklevel + 1)
  155. frame = sys._getframe(_stacklevel)
  156. caller_module = inspect.getmodule(frame)
  157. # Can be none if you call register_fake from somewhere there isn't a module
  158. # (e.g. __main__)
  159. caller_module_name = None if caller_module is None else caller_module.__name__
  160. # TODO(rzou): We're gonna need to stage this change with torchvision,
  161. # since torchvision is github first.
  162. if caller_module_name is not None and caller_module_name.startswith(
  163. "torchvision."
  164. ):
  165. caller_module_name = None
  166. qualname = f"{self.ns}::{op_name}"
  167. entry = torch._library.simple_registry.singleton.find(qualname)
  168. if caller_module_name is not None:
  169. func_to_register = _check_pystubs_once(fn, qualname, caller_module_name)
  170. else:
  171. func_to_register = fn
  172. handle = entry.fake_impl.register(
  173. func_to_register, source, lib=self, allow_override=allow_override
  174. )
  175. self._registration_handles.append(handle)
  176. def _register_torch_dispatch_rule(self, op_name, torch_dispatch_class, fn):
  177. r"""Registers a torch_dispatch rule for the given operator and torch_dispatch_class.
  178. This allows for open registration to specify the behavior between the operator
  179. and the torch_dispatch_class without needing to modify the torch_dispatch_class
  180. or the operator directly.
  181. The torch_dispatch_class is either a Tensor subclass with `__torch_dispatch__` or a
  182. TorchDispatchMode.
  183. If it is a Tensor subclass, we expect fn to have the following signature:
  184. (cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any
  185. If it is a TorchDispatchMode, we expect fn to have the following signature:
  186. (mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any
  187. """
  188. qualname = f"{self.ns}::{op_name}"
  189. entry = torch._library.simple_registry.singleton.find(qualname)
  190. handle = entry.torch_dispatch_rules.register(torch_dispatch_class, fn)
  191. self._registration_handles.append(handle)
  192. def _impl_with_aoti_compile(self, op_name, dispatch_key=""):
  193. r"""Register the operator to use the AOTI-compiled implementation.
  194. Args:
  195. op_name: operator name (along with the overload) or OpOverload object.
  196. dispatch_key: dispatch key that the input function should be registered for. By default, it uses
  197. the dispatch key that the library was created with.
  198. Example::
  199. >>> my_lib = Library("aten", "IMPL")
  200. >>> my_lib._impl_with_aoti_compile("div.Tensor", "CPU")
  201. """
  202. if dispatch_key == "":
  203. dispatch_key = self.dispatch_key
  204. # pyrefly: ignore [bad-argument-type]
  205. if not torch.DispatchKeySet(dispatch_key).has(torch._C.DispatchKey.Dense):
  206. raise AssertionError(
  207. f"dispatch_key {dispatch_key} does not have Dense in its keyset"
  208. )
  209. if isinstance(op_name, str):
  210. name = op_name
  211. elif isinstance(op_name, OpOverload):
  212. name = op_name._schema.name
  213. overload_name = op_name._schema.overload_name
  214. if overload_name != "":
  215. name = name + "." + overload_name
  216. else:
  217. raise RuntimeError(
  218. "_impl_with_aoti_compile should be passed either a name or an OpOverload object "
  219. "as the first argument"
  220. )
  221. key = self.ns + "/" + name.split("::")[-1] + "/" + dispatch_key
  222. if key in _impls:
  223. # TODO: in future, add more info about where the existing function is registered (this info is
  224. # today already returned by the C++ warning when _impl_with_aoti_compile is called but we error out before that)
  225. raise RuntimeError(
  226. "This is not allowed since there's already a kernel registered from python overriding {}"
  227. "'s behavior for {} dispatch key and {} namespace.".format(
  228. name.split("::")[-1], dispatch_key, self.ns
  229. )
  230. )
  231. if self.m is None:
  232. raise AssertionError("Library object has been destroyed")
  233. impl_fn: Callable = self.m.impl_with_aoti_compile
  234. impl_fn(self.ns, name.split("::")[-1], dispatch_key)
  235. _impls.add(key)
  236. self._op_impls.add(key)
  237. def impl(
  238. self, op_name, fn, dispatch_key="", *, with_keyset=False, allow_override=False
  239. ):
  240. r"""Registers the function implementation for an operator defined in the library.
  241. Args:
  242. op_name: operator name (along with the overload) or OpOverload object.
  243. fn: function that's the operator implementation for the input dispatch key or :func:`~fallthrough_kernel`
  244. to register a fallthrough.
  245. dispatch_key: dispatch key that the input function should be registered for. By default, it uses
  246. the dispatch key that the library was created with.
  247. with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument
  248. to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls.
  249. allow_override: Flag controlling if we want to override an
  250. existing registered kernel implementation. This is by
  251. default off, and will error you're trying to register a
  252. kernel to a dispatch key with a kernel already
  253. registered.
  254. Example::
  255. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  256. >>> my_lib = Library("aten", "IMPL")
  257. >>> def div_cpu(self, other):
  258. >>> return self * (1 / other)
  259. >>> my_lib.impl("div.Tensor", div_cpu, "CPU")
  260. """
  261. if not callable(fn):
  262. raise TypeError(
  263. f"Input function is required to be a callable but found type {type(fn)}"
  264. )
  265. if dispatch_key == "":
  266. dispatch_key = self.dispatch_key
  267. if isinstance(op_name, str):
  268. name = op_name
  269. elif isinstance(op_name, OpOverload):
  270. name = op_name._schema.name
  271. overload_name = op_name._schema.overload_name
  272. if overload_name != "":
  273. name = name + "." + overload_name
  274. else:
  275. raise RuntimeError(
  276. "impl should be passed either a name or an OpOverload object as the first argument"
  277. )
  278. key = self.ns + "/" + name.split("::")[-1] + "/" + dispatch_key
  279. if (not allow_override) and key in _impls:
  280. # TODO: in future, add more info about where the existing function is registered (this info is
  281. # today already returned by the C++ warning when impl is called but we error out before that)
  282. raise RuntimeError(
  283. "This is not allowed since there's already a kernel registered from python overriding {}"
  284. "'s behavior for {} dispatch key and {} namespace.".format(
  285. name.split("::")[-1], dispatch_key, self.ns
  286. )
  287. )
  288. if dispatch_key == "Meta":
  289. dispatcher_op_name = name
  290. if "::" not in dispatcher_op_name:
  291. dispatcher_op_name = f"{self.ns}::{dispatcher_op_name}"
  292. # Internally, we shouldn't be registering meta kernels for any operators that
  293. # have CompositeImplicitAutograd kernels.
  294. # Instead, we should be letting those decompositions run, and writing meta kernels
  295. # only for the base operators.
  296. if torch._C._dispatch_has_kernel_for_dispatch_key(
  297. dispatcher_op_name, "CompositeImplicitAutograd"
  298. ):
  299. raise RuntimeError(
  300. f"We should not register a meta kernel directly to the operator '{name}',"
  301. " because it has a CompositeImplicitAutograd kernel in core."
  302. " Instead we should let the operator decompose, and ensure that we have meta kernels"
  303. " for the base ops that it decomposes into."
  304. )
  305. if self.m is None:
  306. raise AssertionError("Library object has been destroyed")
  307. self.m.impl(
  308. name,
  309. dispatch_key if dispatch_key != "" else "CompositeImplicitAutograd",
  310. fn,
  311. with_keyset,
  312. )
  313. _impls.add(key)
  314. self._op_impls.add(key)
  315. def fallback(self, fn, dispatch_key="", *, with_keyset=False):
  316. r"""Registers the function implementation as the fallback for the given key.
  317. This function only works for a library with global namespace ("_").
  318. Args:
  319. fn: function used as fallback for the given dispatch key or :func:`~fallthrough_kernel`
  320. to register a fallthrough.
  321. dispatch_key: dispatch key that the input function should be registered for. By default, it uses
  322. the dispatch key that the library was created with.
  323. with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument
  324. to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls.
  325. Example::
  326. >>> my_lib = Library("_", "IMPL")
  327. >>> def fallback_kernel(op, *args, **kwargs):
  328. >>> # Handle all autocast ops generically
  329. >>> # ...
  330. >>> my_lib.fallback(fallback_kernel, "Autocast")
  331. """
  332. if dispatch_key == "":
  333. dispatch_key = self.dispatch_key
  334. if self.ns != "_":
  335. raise RuntimeError(
  336. f"""Fallback can only be registered using library fragment on the global namespace "_" but it is {self.ns}"""
  337. )
  338. if dispatch_key == "":
  339. raise AssertionError("dispatch_key must not be empty for fallback")
  340. if self.m is None:
  341. raise AssertionError("Library object has been destroyed")
  342. self.m.fallback(dispatch_key, fn, with_keyset)
  343. def _register_effectful_op(self, op_name: str, effect: EffectType | None):
  344. """
  345. Registers an effect to an operator. This is used to register an op that
  346. has side effects that is not capturable by the schema.
  347. Args:
  348. op_name: operator name (along with the overload) or OpOverload object.
  349. effect: The effect of the op.
  350. """
  351. from torch._higher_order_ops.effects import (
  352. _register_effectful_op as hoo_register_effect,
  353. )
  354. handle = hoo_register_effect(op_name, effect)
  355. self._registration_handles.append(handle)
  356. def _destroy(self):
  357. if self.m is not None:
  358. self.m.reset()
  359. self.m = None
  360. for handle in self._registration_handles:
  361. handle.destroy()
  362. self._registration_handles.clear()
  363. global _impls
  364. _impls -= self._op_impls
  365. for name in self._op_defs:
  366. # Delete the cached torch.ops.ns.foo if it was registered.
  367. # Otherwise, accessing it leads to a segfault.
  368. # It's possible that we only registered an overload in this Library
  369. # and another library owns an alive overload.
  370. # That's OK - the next time torch.ops.ns.foo gets called, it'll be
  371. # recomputed to point at the right collection of overloads.
  372. ns, name_with_overload = name.split("::")
  373. name = name_with_overload.split(".")[0]
  374. if not hasattr(torch.ops, ns):
  375. continue
  376. namespace = getattr(torch.ops, ns)
  377. if not hasattr(namespace, name):
  378. continue
  379. delattr(namespace, name)
  380. namespace._dir.remove(name)
  381. def _del_library(
  382. captured_impls,
  383. op_impls,
  384. captured_defs,
  385. op_defs,
  386. registration_handles,
  387. m,
  388. schema_to_signature_cache,
  389. ):
  390. for op_def in op_defs:
  391. name = op_def
  392. overload_name = ""
  393. if "." in op_def:
  394. name, overload_name = op_def.split(".")
  395. if (
  396. name,
  397. overload_name,
  398. ) in schema_to_signature_cache:
  399. del schema_to_signature_cache[(name, overload_name)]
  400. captured_impls -= op_impls
  401. captured_defs -= op_defs
  402. for handle in registration_handles:
  403. handle.destroy()
  404. if m is not None:
  405. m.reset()
  406. @contextlib.contextmanager
  407. def _scoped_library(*args, **kwargs):
  408. try:
  409. lib = Library(*args, **kwargs)
  410. yield lib
  411. finally:
  412. lib._destroy()
  413. _keep_alive: list[Library] = []
  414. NAMELESS_SCHEMA = re.compile(r"\(.*\) -> .*")
  415. @functools.singledispatch
  416. def define(qualname, schema, *, lib=None, tags=()):
  417. r"""Defines a new operator.
  418. In PyTorch, defining an op (short for "operator") is a two step-process:
  419. - we need to define the op (by providing an operator name and schema)
  420. - we need to implement behavior for how the operator interacts with
  421. various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc.
  422. This entrypoint defines the custom operator (the first step)
  423. you must then perform the second step by calling various
  424. ``impl_*`` APIs, like :func:`torch.library.impl` or
  425. :func:`torch.library.register_fake`.
  426. Args:
  427. qualname (str): The qualified name for the operator. Should be
  428. a string that looks like "namespace::name", e.g. "aten::sin".
  429. Operators in PyTorch need a namespace to
  430. avoid name collisions; a given operator may only be created once.
  431. If you are writing a Python library, we recommend the namespace to
  432. be the name of your top-level module.
  433. schema (str): The schema of the operator. E.g. "(Tensor x) -> Tensor"
  434. for an op that accepts one Tensor and returns one Tensor. It does
  435. not contain the operator name (that is passed in ``qualname``).
  436. lib (Optional[Library]): If provided, the lifetime of this operator
  437. will be tied to the lifetime of the Library object.
  438. tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this
  439. operator. Tagging an operator changes the operator's behavior
  440. under various PyTorch subsystems; please read the docs for the
  441. torch.Tag carefully before applying it.
  442. Example::
  443. >>> import torch
  444. >>> import numpy as np
  445. >>>
  446. >>> # Define the operator
  447. >>> torch.library.define("mylib::sin", "(Tensor x) -> Tensor")
  448. >>>
  449. >>> # Add implementations for the operator
  450. >>> @torch.library.impl("mylib::sin", "cpu")
  451. >>> def f(x):
  452. >>> return torch.from_numpy(np.sin(x.numpy()))
  453. >>>
  454. >>> # Call the new operator from torch.ops.
  455. >>> x = torch.randn(3)
  456. >>> y = torch.ops.mylib.sin(x)
  457. >>> assert torch.allclose(y, x.sin())
  458. """
  459. if not isinstance(qualname, str):
  460. raise ValueError(
  461. f"define(qualname, schema): expected qualname "
  462. f"to be instance of str, got {type(qualname)}"
  463. )
  464. namespace, name = torch._library.utils.parse_namespace(qualname)
  465. if lib is None:
  466. lib = Library(namespace, "FRAGMENT")
  467. _keep_alive.append(lib)
  468. if not NAMELESS_SCHEMA.fullmatch(schema):
  469. raise ValueError(
  470. f"define(qualname, schema, ...): expected schema "
  471. f'to look like e.g. "(Tensor x) -> Tensor" but '
  472. f'got "{schema}"'
  473. )
  474. lib.define(name + schema, alias_analysis="", tags=tags)
  475. @define.register
  476. def _(lib: Library, schema, alias_analysis=""):
  477. """The old torch.library.define.
  478. We're keeping this around for BC reasons
  479. """
  480. def wrap(f):
  481. name = lib.define(schema, alias_analysis)
  482. lib.impl(name, f)
  483. return f
  484. return wrap
  485. @overload
  486. def impl(
  487. qualname: str,
  488. types: str | Sequence[str],
  489. func: None = None,
  490. *,
  491. lib: Library | None = None,
  492. ) -> Callable[[Callable[..., object]], None]: ...
  493. @overload
  494. def impl(
  495. qualname: str,
  496. types: str | Sequence[str],
  497. func: Callable[..., object],
  498. *,
  499. lib: Library | None = None,
  500. ) -> None: ...
  501. # Deprecated BC API
  502. @overload
  503. def impl(
  504. lib: Library,
  505. name: str,
  506. dispatch_key: str = "",
  507. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ...
  508. @functools.singledispatch
  509. def impl(
  510. qualname: str,
  511. types: str | Sequence[str],
  512. func: Callable[_P, _T] | None = None,
  513. *,
  514. lib: Library | None = None,
  515. ) -> object:
  516. """Register an implementation for a device type for this operator.
  517. You may pass "default" for ``types`` to register this implementation as the
  518. default implementation for ALL device types.
  519. Please only use this if the implementation truly supports all device types;
  520. for example, this is true if it is a composition of built-in PyTorch operators.
  521. This API may be used as a decorator. You can use nested decorators
  522. with this API provided they return a function and are placed inside
  523. this API (see Example 2).
  524. Some valid types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".
  525. Args:
  526. qualname (str): Should be a string that looks like "namespace::operator_name".
  527. types (str | Sequence[str]): The device types to register an impl to.
  528. lib (Optional[Library]): If provided, the lifetime of this registration
  529. will be tied to the lifetime of the Library object.
  530. Examples:
  531. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  532. >>> import torch
  533. >>> import numpy as np
  534. >>> # Example 1: Register function.
  535. >>> # Define the operator
  536. >>> torch.library.define("mylib::mysin", "(Tensor x) -> Tensor")
  537. >>>
  538. >>> # Add implementations for the cpu device
  539. >>> @torch.library.impl("mylib::mysin", "cpu")
  540. >>> def f(x):
  541. >>> return torch.from_numpy(np.sin(x.numpy()))
  542. >>>
  543. >>> x = torch.randn(3)
  544. >>> y = torch.ops.mylib.mysin(x)
  545. >>> assert torch.allclose(y, x.sin())
  546. >>>
  547. >>> # Example 2: Register function with decorator.
  548. >>> def custom_decorator(func):
  549. >>> def wrapper(*args, **kwargs):
  550. >>> return func(*args, **kwargs) + 1
  551. >>> return wrapper
  552. >>>
  553. >>> # Define the operator
  554. >>> torch.library.define("mylib::sin_plus_one", "(Tensor x) -> Tensor")
  555. >>>
  556. >>> # Add implementations for the operator
  557. >>> @torch.library.impl("mylib::sin_plus_one", "cpu")
  558. >>> @custom_decorator
  559. >>> def f(x):
  560. >>> return torch.from_numpy(np.sin(x.numpy()))
  561. >>>
  562. >>> # Call the new operator from torch.ops.
  563. >>> x = torch.randn(3)
  564. >>>
  565. >>> y1 = torch.ops.mylib.sin_plus_one(x)
  566. >>> y2 = torch.sin(x) + 1
  567. >>> assert torch.allclose(y1, y2)
  568. """
  569. return _impl(qualname, types, func, lib=lib, disable_dynamo=False)
  570. if not TYPE_CHECKING:
  571. @impl.register
  572. def _(
  573. lib: Library, name: str, dispatch_key: str = ""
  574. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  575. """Legacy torch.library.impl API. Kept around for BC"""
  576. def wrap(f: Callable[_P, _T]) -> Callable[_P, _T]:
  577. lib.impl(name, f, dispatch_key)
  578. return f
  579. return wrap
  580. @overload
  581. def _impl(
  582. qualname: str,
  583. types: str | Sequence[str],
  584. func: None = None,
  585. *,
  586. lib: Library | None = None,
  587. disable_dynamo: bool = False,
  588. ) -> Callable[[Callable[..., object]], None]: ...
  589. @overload
  590. def _impl(
  591. qualname: str,
  592. types: str | Sequence[str],
  593. func: Callable[..., object],
  594. *,
  595. lib: Library | None = None,
  596. disable_dynamo: bool = False,
  597. ) -> None: ...
  598. def _impl(
  599. qualname: str,
  600. types: str | Sequence[str],
  601. func: Callable[..., object] | None = None,
  602. *,
  603. lib: Library | None = None,
  604. disable_dynamo: bool = False,
  605. ) -> Callable[[Callable[..., object]], None] | None:
  606. # See impl()
  607. if isinstance(types, str):
  608. types = (types,)
  609. keys = set({})
  610. for typ in types:
  611. is_dispatch_key = torch._C._parse_dispatch_key(typ)
  612. if is_dispatch_key:
  613. # We also support passing a DispatchKey to impl. Please prefer using
  614. # the higher-level torch.library APIs and only pass DispatchKey to
  615. # torch.library.impl with caution (or even better, don't use this
  616. # option and file an issue on GitHub for what you need).
  617. # We don't advertise this to users because
  618. # it is very easy to shoot yourself in the foot.
  619. keys.add(typ)
  620. else:
  621. keys.add(_device_type_to_key(typ))
  622. def register_(func: Callable[..., object]) -> None:
  623. namespace, _ = torch._library.utils.parse_namespace(qualname)
  624. if lib is None:
  625. use_lib = Library(namespace, "FRAGMENT")
  626. _keep_alive.append(use_lib)
  627. else:
  628. use_lib = lib
  629. if disable_dynamo:
  630. @torch._disable_dynamo
  631. def func_no_dynamo(*args, **kwargs):
  632. return func(*args, **kwargs)
  633. for key in keys:
  634. use_lib.impl(qualname, func_no_dynamo, key)
  635. else:
  636. for key in keys:
  637. use_lib.impl(qualname, func, key)
  638. if func is None:
  639. return register_
  640. else:
  641. register_(func)
  642. return None
  643. def _device_type_to_key(device_type: str) -> str:
  644. if device_type == "default":
  645. # This is technically not correct, because although all device_type
  646. # DispatchKeys are included in CompositeExplicitAutograd,
  647. # not everything in CompositeExplicitAutograd is associated with a
  648. # device_type. I don't really care that much about the difference.
  649. return "CompositeExplicitAutograd"
  650. return torch._C._dispatch_key_for_device(device_type)
  651. @deprecated(
  652. "`torch.library.impl_abstract` was renamed to `torch.library.register_fake`. Please use that "
  653. "instead; we will remove `torch.library.impl_abstract` in a future version of PyTorch.",
  654. category=FutureWarning,
  655. )
  656. def impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1):
  657. r"""This API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4.
  658. Please use that instead.
  659. """
  660. if func is not None:
  661. _stacklevel = _stacklevel + 1
  662. return register_fake(qualname, func, lib=lib, _stacklevel=_stacklevel)
  663. _op_identifier = Union[
  664. str, "torch._ops.OpOverload", "torch._library.custom_ops.CustomOpDef"
  665. ]
  666. def register_kernel(
  667. op: _op_identifier,
  668. device_types: device_types_t,
  669. func: Callable | None = None,
  670. /,
  671. *,
  672. lib: Library | None = None,
  673. ):
  674. """Register an implementation for a device type for this operator.
  675. Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".
  676. This API may be used as a decorator.
  677. Args:
  678. op (str | OpOverload): The operator to register an impl to.
  679. device_types (str | None | Sequence[str]): The device_types to register an impl to.
  680. If None, we will register to all device types -- please only use
  681. this option if your implementation is truly device-type-agnostic.
  682. func (Callable): The function to register as the implementation for
  683. the given device types.
  684. lib (Optional[Library]): If provided, the lifetime of this registration
  685. Examples::
  686. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  687. >>> import torch
  688. >>> from torch import Tensor
  689. >>> from torch.library import custom_op
  690. >>> import numpy as np
  691. >>>
  692. >>> # Create a custom op that works on cpu
  693. >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu")
  694. >>> def numpy_sin(x: Tensor) -> Tensor:
  695. >>> x_np = x.numpy()
  696. >>> y_np = np.sin(x_np)
  697. >>> return torch.from_numpy(y_np)
  698. >>>
  699. >>> # Add implementations for the cuda device
  700. >>> @torch.library.register_kernel("mylib::numpy_sin", "cuda")
  701. >>> def _(x):
  702. >>> x_np = x.cpu().numpy()
  703. >>> y_np = np.sin(x_np)
  704. >>> return torch.from_numpy(y_np).to(device=x.device)
  705. >>>
  706. >>> x_cpu = torch.randn(3)
  707. >>> x_cuda = x_cpu.cuda()
  708. >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin())
  709. >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin())
  710. """
  711. if not isinstance(
  712. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  713. ):
  714. raise ValueError(
  715. f"register_kernel({op}): got unexpected type for op: {type(op)}"
  716. )
  717. if isinstance(op, torch._ops.OpOverload):
  718. op = op._name
  719. opdef = _maybe_get_opdef(op)
  720. if opdef is not None:
  721. return opdef.register_kernel(device_types, func)
  722. if not isinstance(op, str):
  723. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  724. if device_types is None:
  725. device_types = "CompositeExplicitAutograd"
  726. return _impl(op, device_types, func, lib=lib, disable_dynamo=True)
  727. def register_autocast(
  728. op: _op_identifier,
  729. device_type: str,
  730. cast_inputs: _dtype,
  731. /,
  732. *,
  733. lib: Library | None = None,
  734. ):
  735. r"""Register an autocast dispatch rule for this custom op.
  736. Valid `device_type` include: "cpu" and "cuda".
  737. Args:
  738. op (str | OpOverload): The operator to register an autocast dispatch rule to.
  739. device_type(str): Device type to use. 'cuda' or 'cpu'.
  740. The type is the same as the `type` attribute of a :class:`torch.device`.
  741. Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
  742. cast_inputs (:class:`torch.dtype`): When custom op runs in an autocast-enabled region,
  743. casts incoming floating-point Tensors to the target dtype (non-floating-point Tensors
  744. are not affected), then executes custom op with autocast disabled.
  745. lib (Optional[Library]): If provided, the lifetime of this registration
  746. Examples::
  747. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  748. >>> import torch
  749. >>> from torch import Tensor
  750. >>> from torch.library import custom_op
  751. >>>
  752. >>> # Create a custom op that works on cuda
  753. >>> @torch.library.custom_op("mylib::my_sin", mutates_args=())
  754. >>> def my_sin(x: Tensor) -> Tensor:
  755. >>> return torch.sin(x)
  756. >>>
  757. >>> # Register autocast dispatch rule for the cuda device
  758. >>> torch.library.register_autocast("mylib::my_sin", "cuda", torch.float16)
  759. >>>
  760. >>> x = torch.randn(3, dtype=torch.float32, device="cuda")
  761. >>> with torch.autocast("cuda", dtype=torch.float16):
  762. >>> y = torch.ops.mylib.my_sin(x)
  763. >>> assert y.dtype == torch.float16
  764. """
  765. if not isinstance(
  766. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  767. ):
  768. raise ValueError(
  769. f"register_autocast({op}): got unexpected type for op: {type(op)}"
  770. )
  771. if device_type not in ["cpu", "cuda"]:
  772. raise ValueError(f"Unknown device type: {device_type}")
  773. if isinstance(op, torch._ops.OpOverload):
  774. op = op._name
  775. opdef = _maybe_get_opdef(op)
  776. if opdef is not None:
  777. return opdef.register_autocast(device_type, cast_inputs)
  778. if not isinstance(op, str):
  779. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  780. qualname = op
  781. _op = torch._library.utils.lookup_op(qualname)
  782. namespace, opname = torch._library.utils.parse_namespace(qualname)
  783. if lib is None:
  784. lib = Library(namespace, "FRAGMENT")
  785. _keep_alive.append(lib)
  786. def _maybe_override_py_impl(op: torch._ops.OpOverload, dispatch_key):
  787. def inner(kernel):
  788. if op.has_kernel_for_dispatch_key(dispatch_key):
  789. op.py_kernels.pop(dispatch_key)
  790. return op.py_impl(dispatch_key)(kernel)
  791. return inner
  792. @_maybe_override_py_impl(_op, torch._C.DispatchKey.AutocastCPU)
  793. @_maybe_override_py_impl(_op, torch._C.DispatchKey.AutocastCUDA)
  794. def _autocast_py_impl(*args, **kwargs):
  795. if len(kwargs) != 0:
  796. raise AssertionError("Custom ops do not support kwargs yet.")
  797. autocast_keyset = torch._C.DispatchKeySet(
  798. torch._C.DispatchKey.AutocastCPU
  799. ) | torch._C.DispatchKeySet(torch._C.DispatchKey.AutocastCUDA)
  800. with torch._C._ExcludeDispatchKeyGuard(autocast_keyset):
  801. return _op(*_cast(args, device_type, cast_inputs))
  802. def kernel(_, *args, **kwargs):
  803. if len(kwargs) != 0:
  804. raise AssertionError("Custom ops do not support kwargs yet.")
  805. return _autocast_py_impl(*args, **kwargs)
  806. if device_type == "cuda":
  807. return lib.impl(opname, kernel, "AutocastCUDA", with_keyset=True)
  808. else:
  809. # device_type is "cpu"
  810. return lib.impl(opname, kernel, "AutocastCPU", with_keyset=True)
  811. def register_fake(
  812. op: _op_identifier,
  813. func: Callable | None = None,
  814. /,
  815. *,
  816. lib: Library | None = None,
  817. _stacklevel: int = 1,
  818. allow_override: bool = False,
  819. ):
  820. r"""Register a FakeTensor implementation ("fake impl") for this operator.
  821. Also sometimes known as a "meta kernel", "abstract impl".
  822. An "FakeTensor implementation" specifies the behavior of this operator on
  823. Tensors that carry no data ("FakeTensor"). Given some input Tensors with
  824. certain properties (sizes/strides/storage_offset/device), it specifies
  825. what the properties of the output Tensors are.
  826. The FakeTensor implementation has the same signature as the operator.
  827. It is run for both FakeTensors and meta tensors. To write a FakeTensor
  828. implementation, assume that all Tensor inputs to the operator are
  829. regular CPU/CUDA/Meta tensors, but they do not have storage, and
  830. you are trying to return regular CPU/CUDA/Meta tensor(s) as output.
  831. The FakeTensor implementation must consist of only PyTorch operations
  832. (and may not directly access the storage or data of any input or
  833. intermediate Tensors).
  834. This API may be used as a decorator (see examples).
  835. For a detailed guide on custom ops, please see
  836. https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html
  837. Args:
  838. op_name: Operator name (along with the overload) or OpOverload object.
  839. func: Fake tensor implementation.
  840. lib (Optional[Library]): Library to register the fake tensor to.
  841. allow_override: Flag controlling if we want to override an
  842. existing registered fake impl. This is by default off,
  843. and will error you're trying to register a fake impl to
  844. an operator that already has a fake impl. This also only
  845. applies if the custom operator was not created via
  846. torch.library.custom_op, as overriding and existing fake
  847. impl is already allowed.
  848. Examples:
  849. >>> import torch
  850. >>> import numpy as np
  851. >>> from torch import Tensor
  852. >>>
  853. >>> # Example 1: an operator without data-dependent output shape
  854. >>> @torch.library.custom_op("mylib::custom_linear", mutates_args=())
  855. >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
  856. >>> raise NotImplementedError("Implementation goes here")
  857. >>>
  858. >>> @torch.library.register_fake("mylib::custom_linear")
  859. >>> def _(x, weight, bias):
  860. >>> assert x.dim() == 2
  861. >>> assert weight.dim() == 2
  862. >>> assert bias.dim() == 1
  863. >>> assert x.shape[1] == weight.shape[1]
  864. >>> assert weight.shape[0] == bias.shape[0]
  865. >>> assert x.device == weight.device
  866. >>>
  867. >>> return (x @ weight.t()) + bias
  868. >>>
  869. >>> with torch._subclasses.fake_tensor.FakeTensorMode():
  870. >>> x = torch.randn(2, 3)
  871. >>> w = torch.randn(3, 3)
  872. >>> b = torch.randn(3)
  873. >>> y = torch.ops.mylib.custom_linear(x, w, b)
  874. >>>
  875. >>> assert y.shape == (2, 3)
  876. >>>
  877. >>> # Example 2: an operator with data-dependent output shape
  878. >>> @torch.library.custom_op("mylib::custom_nonzero", mutates_args=())
  879. >>> def custom_nonzero(x: Tensor) -> Tensor:
  880. >>> x_np = x.numpy(force=True)
  881. >>> res = np.stack(np.nonzero(x_np), axis=1)
  882. >>> return torch.tensor(res, device=x.device)
  883. >>>
  884. >>> @torch.library.register_fake("mylib::custom_nonzero")
  885. >>> def _(x):
  886. >>> # Number of nonzero-elements is data-dependent.
  887. >>> # Since we cannot peek at the data in an fake impl,
  888. >>> # we use the ctx object to construct a new symint that
  889. >>> # represents the data-dependent size.
  890. >>> ctx = torch.library.get_ctx()
  891. >>> nnz = ctx.new_dynamic_size()
  892. >>> shape = [nnz, x.dim()]
  893. >>> result = x.new_empty(shape, dtype=torch.int64)
  894. >>> return result
  895. >>>
  896. >>> from torch.fx.experimental.proxy_tensor import make_fx
  897. >>>
  898. >>> x = torch.tensor([0, 1, 2, 3, 4, 0])
  899. >>> trace = make_fx(torch.ops.mylib.custom_nonzero, tracing_mode="symbolic")(x)
  900. >>> trace.print_readable()
  901. >>>
  902. >>> assert torch.allclose(trace(x), torch.ops.mylib.custom_nonzero(x))
  903. """
  904. if not isinstance(
  905. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  906. ):
  907. raise ValueError(f"register_fake({op}): got unexpected type for op: {type(op)}")
  908. if isinstance(op, torch._ops.OpOverload):
  909. op = op._name
  910. opdef = _maybe_get_opdef(op)
  911. if opdef is not None:
  912. if func is None:
  913. return opdef.register_fake
  914. else:
  915. return opdef.register_fake(func)
  916. if not isinstance(op, str):
  917. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  918. stacklevel = _stacklevel
  919. def register(func):
  920. namespace, op_name = torch._library.utils.parse_namespace(op)
  921. if lib is None:
  922. use_lib = Library(namespace, "FRAGMENT")
  923. _keep_alive.append(use_lib)
  924. else:
  925. use_lib = lib
  926. use_lib._register_fake(
  927. op_name, func, _stacklevel=stacklevel + 1, allow_override=allow_override
  928. )
  929. return func
  930. if func is None:
  931. return register
  932. else:
  933. stacklevel += 1
  934. return register(func)
  935. def _register_effectful_op(
  936. op: _op_identifier,
  937. effect: EffectType | None,
  938. *,
  939. lib: Library | None = None,
  940. ) -> None:
  941. r"""
  942. To specify that an operator has side-effects, we must register an effect
  943. type for the operator. This will prevent graph passes in torch.compile from
  944. reordering operations with the same effect type.
  945. Args:
  946. op_name: Operator name (along with the overload) or OpOverload object.
  947. effect: Effect type to register. None means the operator is not effectful.
  948. """
  949. if not isinstance(
  950. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  951. ):
  952. raise ValueError(
  953. f"register_effectful_op({op}): got unexpected type for op: {type(op)}"
  954. )
  955. if isinstance(op, torch._ops.OpOverload):
  956. op = op._name
  957. opdef = _maybe_get_opdef(op)
  958. if opdef is not None:
  959. opdef.register_effect(effect)
  960. if not isinstance(op, str):
  961. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  962. namespace, _ = torch._library.utils.parse_namespace(op)
  963. if lib is None:
  964. use_lib = Library(namespace, "FRAGMENT")
  965. _keep_alive.append(use_lib)
  966. else:
  967. use_lib = lib
  968. use_lib._register_effectful_op(op, effect)
  969. def register_autograd(
  970. op: _op_identifier,
  971. backward: Callable,
  972. /,
  973. *,
  974. setup_context: Callable | None = None,
  975. lib=None,
  976. ) -> None:
  977. r"""Register a backward formula for this custom op.
  978. In order for an operator to work with autograd, you need to register
  979. a backward formula:
  980. 1. You must tell us how to compute gradients during the backward pass
  981. by providing us a "backward" function.
  982. 2. If you need any values from the forward to compute gradients, you can
  983. use `setup_context` to save values for backward.
  984. ``backward`` runs during the backward pass. It accepts ``(ctx, *grads)``:
  985. - ``grads`` is one or more gradients. The number of gradients matches
  986. the number of outputs of the operator.
  987. The ``ctx`` object is `the same ctx object <context_method_mixins>`_ used by
  988. :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the
  989. same as :meth:`torch.autograd.Function.backward`.
  990. ``setup_context(ctx, inputs, output)`` runs during the forward pass.
  991. Please save quantities needed for backward onto the ``ctx`` object via
  992. either :meth:`torch.autograd.function.FunctionCtx.save_for_backward`
  993. or assigning them as attributes of ``ctx``. If your custom op has
  994. kwarg-only arguments, we expect the signature of ``setup_context``
  995. to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``.
  996. Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is,
  997. they may not directly access :meth:`torch.Tensor.data_ptr` and they must
  998. not depend on or mutate global state. If you need a non-traceable backward,
  999. you can make it a separate custom_op that you call inside ``backward_fn``.
  1000. If you need different autograd behavior on different devices, then we
  1001. recommend creating two different custom operators, one for each device
  1002. that needs different behavior, and switching between them at runtime.
  1003. Examples:
  1004. >>> import torch
  1005. >>> import numpy as np
  1006. >>> from torch import Tensor
  1007. >>>
  1008. >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=())
  1009. >>> def numpy_sin(x: Tensor) -> Tensor:
  1010. >>> x_np = x.cpu().numpy()
  1011. >>> y_np = np.sin(x_np)
  1012. >>> return torch.from_numpy(y_np).to(device=x.device)
  1013. >>>
  1014. >>> def setup_context(ctx, inputs, output) -> Tensor:
  1015. >>> x, = inputs
  1016. >>> ctx.save_for_backward(x)
  1017. >>>
  1018. >>> def backward(ctx, grad):
  1019. >>> x, = ctx.saved_tensors
  1020. >>> return grad * x.cos()
  1021. >>>
  1022. >>> torch.library.register_autograd(
  1023. ... "mylib::numpy_sin", backward, setup_context=setup_context
  1024. ... )
  1025. >>>
  1026. >>> x = torch.randn(3, requires_grad=True)
  1027. >>> y = numpy_sin(x)
  1028. >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
  1029. >>> assert torch.allclose(grad_x, x.cos())
  1030. >>>
  1031. >>> # Example with a keyword-only arg
  1032. >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
  1033. >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor:
  1034. >>> x_np = x.cpu().numpy()
  1035. >>> y_np = x_np * val
  1036. >>> return torch.from_numpy(y_np).to(device=x.device)
  1037. >>>
  1038. >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor:
  1039. >>> ctx.val = keyword_only_inputs["val"]
  1040. >>>
  1041. >>> def backward(ctx, grad):
  1042. >>> return grad * ctx.val
  1043. >>>
  1044. >>> torch.library.register_autograd(
  1045. ... "mylib::numpy_mul", backward, setup_context=setup_context
  1046. ... )
  1047. >>>
  1048. >>> x = torch.randn(3, requires_grad=True)
  1049. >>> y = numpy_mul(x, val=3.14)
  1050. >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
  1051. >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14))
  1052. """
  1053. if not isinstance(
  1054. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  1055. ):
  1056. raise ValueError(
  1057. f"register_autograd({op}): got unexpected type for op: {type(op)}"
  1058. )
  1059. if isinstance(op, torch._ops.OpOverload):
  1060. op = op._name
  1061. opdef = _maybe_get_opdef(op)
  1062. if opdef is not None:
  1063. opdef.register_autograd(backward, setup_context=setup_context)
  1064. return
  1065. if not isinstance(op, str):
  1066. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  1067. qualname = op
  1068. op = torch._library.utils.lookup_op(qualname)
  1069. schema = op._schema
  1070. if not _library.utils.is_functional_schema(schema):
  1071. raise RuntimeError(
  1072. f"Cannot register autograd formula for non-functional operator "
  1073. f"{op} with schema {schema}. Please create "
  1074. f"a functional operator and register an autograd formula for that."
  1075. )
  1076. if _library.utils.has_kwarg_only_tensors(schema):
  1077. raise NotImplementedError(
  1078. f"register_autograd with kwarg-only Tensor args. In the original "
  1079. f"definition of the op, please make your tensors not kwarg-only. "
  1080. f"Got: {schema}"
  1081. )
  1082. info = _library.autograd.Info(backward, setup_context)
  1083. autograd_kernel = _library.autograd.make_autograd_impl(op, info)
  1084. namespace, opname = torch._library.utils.parse_namespace(qualname)
  1085. if lib is None:
  1086. lib = Library(namespace, "FRAGMENT")
  1087. _keep_alive.append(lib)
  1088. lib.impl(opname, autograd_kernel, "Autograd", with_keyset=True)
  1089. def register_torch_dispatch(
  1090. op: _op_identifier,
  1091. torch_dispatch_class: Any,
  1092. func: Callable | None = None,
  1093. /,
  1094. *,
  1095. lib: Library | None = None,
  1096. ):
  1097. r"""Registers a torch_dispatch rule for the given operator and ``torch_dispatch_class``.
  1098. This allows for open registration to specify the behavior between the operator
  1099. and the ``torch_dispatch_class`` without needing to modify the ``torch_dispatch_class``
  1100. or the operator directly.
  1101. The ``torch_dispatch_class`` is either a Tensor subclass with ``__torch_dispatch__`` or a
  1102. TorchDispatchMode.
  1103. If it is a Tensor subclass, we expect ``func`` to have the following signature:
  1104. ``(cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any``
  1105. If it is a TorchDispatchMode, we expect ``func`` to have the following signature:
  1106. ``(mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any``
  1107. ``args`` and ``kwargs`` will have been normalized the same way they are
  1108. in ``__torch_dispatch__`` (see :ref:`torch-dispatch-calling-convention`).
  1109. Examples:
  1110. >>> import torch
  1111. >>>
  1112. >>> @torch.library.custom_op("mylib::foo", mutates_args={})
  1113. >>> def foo(x: torch.Tensor) -> torch.Tensor:
  1114. >>> return x.clone()
  1115. >>>
  1116. >>> class MyMode(torch.utils._python_dispatch.TorchDispatchMode):
  1117. >>> def __torch_dispatch__(self, func, types, args=(), kwargs=None):
  1118. >>> return func(*args, **kwargs)
  1119. >>>
  1120. >>> @torch.library.register_torch_dispatch("mylib::foo", MyMode)
  1121. >>> def _(mode, func, types, args, kwargs):
  1122. >>> x, = args
  1123. >>> return x + 1
  1124. >>>
  1125. >>> x = torch.randn(3)
  1126. >>> y = foo(x)
  1127. >>> assert torch.allclose(y, x)
  1128. >>>
  1129. >>> with MyMode():
  1130. >>> y = foo(x)
  1131. >>> assert torch.allclose(y, x + 1)
  1132. """
  1133. if not isinstance(
  1134. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  1135. ):
  1136. raise ValueError(
  1137. f"register_torch_dispatch({op}): got unexpected type for op: {type(op)}"
  1138. )
  1139. if isinstance(op, torch._ops.OpOverload):
  1140. op = op._name
  1141. opdef = _maybe_get_opdef(op)
  1142. if opdef is not None:
  1143. return opdef.register_torch_dispatch(torch_dispatch_class, func)
  1144. if not isinstance(op, str):
  1145. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  1146. def register(func):
  1147. namespace, op_name = torch._library.utils.parse_namespace(op)
  1148. if lib is None:
  1149. use_lib = Library(namespace, "FRAGMENT")
  1150. _keep_alive.append(use_lib)
  1151. else:
  1152. use_lib = lib
  1153. use_lib._register_torch_dispatch_rule(op_name, torch_dispatch_class, func)
  1154. return func
  1155. if func is None:
  1156. return register
  1157. else:
  1158. return register(func)
  1159. def register_vmap(
  1160. op: _op_identifier,
  1161. func: Callable | None = None,
  1162. /,
  1163. *,
  1164. lib=None,
  1165. ):
  1166. r"""Register a vmap implementation to support :func:`torch.vmap` for this custom op.
  1167. This API may be used as a decorator (see examples).
  1168. In order for an operator to work with :func:`torch.vmap`, you may need to register a
  1169. vmap implementation in the following signature:
  1170. ``vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)``,
  1171. where ``*args`` and ``**kwargs`` are the arguments and kwargs for ``op``.
  1172. We do not support kwarg-only Tensor args.
  1173. It specifies how do we compute the batched version of ``op`` given inputs with an additional
  1174. dimension (specified by ``in_dims``).
  1175. For each arg in ``args``, ``in_dims`` has a corresponding ``Optional[int]``. It is ``None``
  1176. if the arg is not a Tensor or if the arg is not being vmapped over, otherwise, it is an integer
  1177. specifying what dimension of the Tensor is being vmapped over.
  1178. ``info`` is a collection of additional metadata that may be helpful:
  1179. ``info.batch_size`` specifies the size of the dimension being vmapped over, while
  1180. ``info.randomness`` is the ``randomness`` option that was passed to :func:`torch.vmap`.
  1181. The return of the function ``func`` is a tuple of ``(output, out_dims)``. Similar to ``in_dims``,
  1182. ``out_dims`` should be of the same structure as ``output`` and contain one ``out_dim``
  1183. per output that specifies if the output has the vmapped dimension and what index it is in.
  1184. Examples:
  1185. >>> import torch
  1186. >>> import numpy as np
  1187. >>> from torch import Tensor
  1188. >>> from typing import Tuple
  1189. >>>
  1190. >>> def to_numpy(tensor):
  1191. >>> return tensor.cpu().numpy()
  1192. >>>
  1193. >>> lib = torch.library.Library("mylib", "FRAGMENT")
  1194. >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=())
  1195. >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]:
  1196. >>> x_np = to_numpy(x)
  1197. >>> dx = torch.tensor(3 * x_np ** 2, device=x.device)
  1198. >>> return torch.tensor(x_np ** 3, device=x.device), dx
  1199. >>>
  1200. >>> def numpy_cube_vmap(info, in_dims, x):
  1201. >>> result = numpy_cube(x)
  1202. >>> return result, (in_dims[0], in_dims[0])
  1203. >>>
  1204. >>> torch.library.register_vmap(numpy_cube, numpy_cube_vmap)
  1205. >>>
  1206. >>> x = torch.randn(3)
  1207. >>> torch.vmap(numpy_cube)(x)
  1208. >>>
  1209. >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
  1210. >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor:
  1211. >>> return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device)
  1212. >>>
  1213. >>> @torch.library.register_vmap("mylib::numpy_mul")
  1214. >>> def numpy_mul_vmap(info, in_dims, x, y):
  1215. >>> x_bdim, y_bdim = in_dims
  1216. >>> x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
  1217. >>> y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
  1218. >>> result = x * y
  1219. >>> result = result.movedim(-1, 0)
  1220. >>> return result, 0
  1221. >>>
  1222. >>>
  1223. >>> x = torch.randn(3)
  1224. >>> y = torch.randn(3)
  1225. >>> torch.vmap(numpy_mul)(x, y)
  1226. .. note::
  1227. The vmap function should aim to preserve the semantics of the entire custom operator.
  1228. That is, ``grad(vmap(op))`` should be replaceable with a ``grad(map(op))``.
  1229. If your custom operator has any custom behavior in the backward pass, please
  1230. keep this in mind.
  1231. """
  1232. if not isinstance(
  1233. op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef)
  1234. ):
  1235. raise ValueError(f"register_vmap({op}): got unexpected type for op: {type(op)}")
  1236. if isinstance(op, torch._ops.OpOverload):
  1237. op = op._name
  1238. opdef = _maybe_get_opdef(op)
  1239. if opdef is not None:
  1240. return opdef.register_vmap(func)
  1241. if not isinstance(op, str):
  1242. raise AssertionError(f"op must be str at this point, got {type(op).__name__}")
  1243. qualname = op
  1244. op = torch._library.utils.lookup_op(qualname)
  1245. schema = op._schema
  1246. if _library.utils.has_kwarg_only_tensors(schema):
  1247. raise NotImplementedError(
  1248. f"register_vmap with kwarg-only Tensor args. In the original "
  1249. f"definition of the op, please make your tensors not kwarg-only. "
  1250. f"Got: {schema}"
  1251. )
  1252. def register(func):
  1253. nonlocal op, lib
  1254. namespace, opname = torch._library.utils.parse_namespace(qualname)
  1255. if lib is None:
  1256. lib = Library(namespace, "FRAGMENT")
  1257. _keep_alive.append(lib)
  1258. from torch._functorch.autograd_function import custom_function_call_vmap_helper
  1259. from torch._functorch.pyfunctorch import retrieve_current_functorch_interpreter
  1260. def wrapped_func(keyset, *args, **kwargs):
  1261. interpreter = retrieve_current_functorch_interpreter()
  1262. return custom_function_call_vmap_helper(
  1263. # pyrefly: ignore[bad-argument-type]
  1264. interpreter,
  1265. func,
  1266. op,
  1267. *args,
  1268. **kwargs,
  1269. )
  1270. lib.impl(opname, wrapped_func, "FuncTorchBatched", with_keyset=True)
  1271. if func is None:
  1272. return register
  1273. else:
  1274. return register(func)
  1275. # If the op was defined in C++, then we want to make sure there was an
  1276. # m.set_python_module(module, ...) call and that the module is the
  1277. # same as the module that called torch.library.register_fake.
  1278. def _check_pystubs_once(func, qualname, actual_module_name):
  1279. checked = False
  1280. def inner(*args, **kwargs):
  1281. nonlocal checked
  1282. if checked:
  1283. return func(*args, **kwargs)
  1284. op = torch._library.utils.lookup_op(qualname)
  1285. if op._defined_in_python:
  1286. checked = True
  1287. return func(*args, **kwargs)
  1288. maybe_pystub = torch._C._dispatch_pystub(
  1289. op._schema.name, op._schema.overload_name
  1290. )
  1291. if maybe_pystub is None:
  1292. if torch._library.utils.requires_set_python_module():
  1293. namespace = op.namespace
  1294. cpp_filename = op._handle.debug()
  1295. raise RuntimeError(
  1296. f"Operator '{qualname}' was defined in C++ and has a Python "
  1297. f"fake impl. In this situation, we require there to also be a "
  1298. f'companion C++ `m.set_python_module("{actual_module_name}")` '
  1299. f"call, but we could not find one. Please add that to "
  1300. f"to the top of the C++ TORCH_LIBRARY({namespace}, ...) block the "
  1301. f"operator was registered in ({cpp_filename})"
  1302. )
  1303. else:
  1304. pystub_module = maybe_pystub[0]
  1305. if actual_module_name != pystub_module:
  1306. cpp_filename = op._handle.debug()
  1307. raise RuntimeError(
  1308. f"Operator '{qualname}' specified that its python fake impl "
  1309. f"is in the Python module '{pystub_module}' but it was actually found "
  1310. f"in '{actual_module_name}'. Please either move the fake impl "
  1311. f"or correct the m.set_python_module call ({cpp_filename})"
  1312. )
  1313. checked = True
  1314. return func(*args, **kwargs)
  1315. return inner
  1316. # NOTE [ctx inside the fake implementation]
  1317. # If a user has an operator with data-dependent output shape, then when writing
  1318. # a fake implementation they must query the current ctx and use methods on the
  1319. # ctx to construct a new unbacked symint.
  1320. #
  1321. # This is done via us setting the global_ctx_getter function every time a fake
  1322. # implementation is invoked.
  1323. def get_ctx() -> "torch._library.fake_impl.FakeImplCtx":
  1324. """get_ctx() returns the current AbstractImplCtx object.
  1325. Calling ``get_ctx()`` is only valid inside of an fake impl
  1326. (see :func:`torch.library.register_fake` for more usage details.
  1327. """
  1328. return torch._library.fake_impl.global_ctx_getter()
  1329. def get_kernel(
  1330. op: _op_identifier, dispatch_key: str | torch.DispatchKey
  1331. ) -> torch._C._SafeKernelFunction:
  1332. """Returns the computed kernel for a given operator and dispatch key.
  1333. This function retrieves the kernel that would be executed for a given
  1334. operator and dispatch key combination. The returned SafeKernelFunction
  1335. can be used to call the kernel in a boxed fashion. The intended use
  1336. case for this function is to retrieve the original kernel for a given
  1337. dispatch key and then register another kernel to the same dispatch key
  1338. that calls into the original kernel for certain cases.
  1339. Args:
  1340. op: Operator name (along with the overload) or OpOverload object
  1341. Can be a string (e.g., "aten::add.Tensor"), an OpOverload, or a CustomOpDef.
  1342. dispatch_key (str | torch.DispatchKey): The dispatch key to get the kernel for.
  1343. Can be a string (e.g., "CPU", "CUDA") or a DispatchKey enum value.
  1344. Returns:
  1345. torch._C._SafeKernelFunction: A safe kernel function that can be used to
  1346. call the kernel.
  1347. Raises:
  1348. RuntimeError: If the operator does not exist.
  1349. Example:
  1350. >>> # Get the CPU kernel for torch.add
  1351. >>> kernel = torch.library.get_kernel("aten::add.Tensor", "CPU")
  1352. >>>
  1353. >>> # You can also use DispatchKey enum
  1354. >>> kernel = torch.library.get_kernel("aten::add.Tensor", torch.DispatchKey.CPU)
  1355. >>>
  1356. >>> # Or use an OpOverload directly
  1357. >>> kernel = torch.library.get_kernel(torch.ops.aten.add.Tensor, "CPU")
  1358. >>>
  1359. >>> # Example: Using get_kernel in a custom op with conditional dispatch
  1360. >>> # Get the original kernel for torch.sin
  1361. >>> original_sin_kernel = torch.library.get_kernel("aten::sin", "CPU")
  1362. >>>
  1363. >>> # If input has negative values, use original sin, otherwise return zeros
  1364. >>> def conditional_sin_impl(dispatch_keys, x):
  1365. >>> if (x < 0).any():
  1366. >>> return original_sin_kernel.call_boxed(dispatch_keys, x)
  1367. >>> else:
  1368. >>> return torch.zeros_like(x)
  1369. >>>
  1370. >>> lib = torch.library.Library("aten", "IMPL")
  1371. >>> # with_keyset=True so the first argument to the impl is the current DispatchKeySet
  1372. >>> which needs to be the first argument to ``kernel.call_boxed``
  1373. >>> lib.impl("sin", conditional_sin_impl, "CPU", with_keyset=True)
  1374. >>>
  1375. >>> # Test the conditional behavior
  1376. >>> x_positive = torch.tensor([1.0, 2.0])
  1377. >>> x_mixed = torch.tensor([-1.0, 2.0])
  1378. >>> torch.sin(x_positive)
  1379. tensor([0., 0.])
  1380. >>> torch.sin(x_mixed)
  1381. tensor([-0.8415, 0.9093])
  1382. """
  1383. if not isinstance(op, (str, torch._ops.OpOverload)):
  1384. raise ValueError(f"get_kernel({op}): got unexpected type for op: {type(op)}")
  1385. if isinstance(op, torch._ops.OpOverload):
  1386. op = op._name
  1387. if isinstance(dispatch_key, str):
  1388. try:
  1389. dispatch_key = torch._C.DispatchKey.__members__[dispatch_key]
  1390. except KeyError:
  1391. raise ValueError(f"Invalid dispatch key: {dispatch_key}") from None
  1392. return torch._C._dispatch_get_computed_kernel_for_dispatch_key(op, dispatch_key)
  1393. _OPCHECK_DEFAULT_UTILS = (
  1394. "test_schema",
  1395. "test_autograd_registration",
  1396. "test_faketensor",
  1397. "test_aot_dispatch_dynamic",
  1398. )
  1399. def opcheck(
  1400. op: torch._ops.OpOverload | torch._ops.OpOverloadPacket | CustomOpDef,
  1401. args: tuple[Any, ...],
  1402. kwargs: dict[str, Any] | None = None,
  1403. *,
  1404. test_utils: str | Sequence[str] = _OPCHECK_DEFAULT_UTILS,
  1405. raise_exception: bool = True,
  1406. atol=None,
  1407. rtol=None,
  1408. ) -> dict[str, str]:
  1409. """Given an operator and some sample arguments, tests if the operator is
  1410. registered correctly.
  1411. That is, when you use the torch.library/TORCH_LIBRARY APIs to create a
  1412. custom op, you specified metadata (e.g. mutability info) about the custom op
  1413. and these APIs require that the functions you pass them satisfy certain
  1414. properties (e.g. no data pointer access in the fake/meta/abstract kernel)
  1415. ``opcheck`` tests these metadata and properties.
  1416. Concretely, we test the following:
  1417. - test_schema: If the schema matches the implementation of
  1418. the operator. For example: if the schema specifies a Tensor is mutated,
  1419. then we check the implementation mutates the Tensor. If the schema
  1420. specifies that we return a new Tensor, then we check that the
  1421. implementation returns a new Tensor (instead of an existing one or
  1422. a view of an existing one).
  1423. - test_autograd_registration: If the operator supports training
  1424. (autograd): we check that its autograd formula is registered via
  1425. torch.library.register_autograd or a manual registration to one
  1426. or more DispatchKey::Autograd keys. Any other DispatchKey-based
  1427. registrations may lead to undefined behavior.
  1428. - test_faketensor: If the operator has a FakeTensor kernel
  1429. (and if it is correct). The FakeTensor kernel is necessary (
  1430. but not sufficient) for the operator to work with PyTorch compilation
  1431. APIs (torch.compile/export/FX). We check that a FakeTensor kernel
  1432. (also sometimes known as a meta kernel) was registered for the
  1433. operator and that it is correct. This test takes the result of
  1434. running the operator on real tensors and the result of running
  1435. the operator on FakeTensors and checks that they have the same
  1436. Tensor metadata (sizes/strides/dtype/device/etc).
  1437. - test_aot_dispatch_dynamic: If the operator has correct behavior
  1438. with PyTorch compilation APIs (torch.compile/export/FX).
  1439. This checks that the outputs (and gradients, if applicable) are the
  1440. same under eager-mode PyTorch and torch.compile.
  1441. This test is a superset of ``test_faketensor`` and is an e2e test;
  1442. other things it tests are that the operator supports
  1443. functionalization and that the backward pass (if it exists) also
  1444. supports FakeTensor and functionalization.
  1445. For best results, please call ``opcheck`` multiple times with a
  1446. representative set of inputs. If your operator supports
  1447. autograd, please use ``opcheck`` with inputs with ``requires_grad = True``;
  1448. if your operator supports multiple devices (e.g. CPU and CUDA), please
  1449. use ``opcheck`` with inputs on all supported devices.
  1450. Args:
  1451. op: The operator. Must either be a function decorated with
  1452. :func:`torch.library.custom_op` or an OpOverload/OpOverloadPacket
  1453. found in torch.ops.* (e.g. torch.ops.aten.sin, torch.ops.mylib.foo)
  1454. args: The args to the operator
  1455. kwargs: The kwargs to the operator
  1456. test_utils: Tests that we should run. Default: all of them.
  1457. Example: ("test_schema", "test_faketensor")
  1458. raise_exception: If we should raise an exception on the first
  1459. error. If False, we will return a dict with information
  1460. on if each test passed or not.
  1461. rtol (Optional[float]): Relative tolerance for floating point comparisons.
  1462. If specified ``atol`` must also be specified.
  1463. If omitted, default values based on the ``dtype`` are selected
  1464. (see the table in :func:`torch.testing.assert_close`).
  1465. atol (Optional[float]): Absolute tolerance for floating point comparisons.
  1466. If specified ``rtol`` must also be specified.
  1467. If omitted, default values based on the ``dtype`` are selected
  1468. (see the table in :func:`torch.testing.assert_close`).
  1469. .. warning::
  1470. opcheck and :func:`torch.autograd.gradcheck` test different things;
  1471. opcheck tests if your usage of torch.library APIs is correct while
  1472. :func:`torch.autograd.gradcheck` tests if your autograd formula is
  1473. mathematically correct. Use both to test custom ops that support
  1474. gradient computation.
  1475. Example:
  1476. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  1477. >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
  1478. >>> def numpy_mul(x: Tensor, y: float) -> Tensor:
  1479. >>> x_np = x.numpy(force=True)
  1480. >>> z_np = x_np * y
  1481. >>> return torch.from_numpy(z_np).to(x.device)
  1482. >>>
  1483. >>> @numpy_mul.register_fake
  1484. >>> def _(x, y):
  1485. >>> return torch.empty_like(x)
  1486. >>>
  1487. >>> def setup_context(ctx, inputs, output):
  1488. >>> y, = inputs
  1489. >>> ctx.y = y
  1490. >>>
  1491. >>> def backward(ctx, grad):
  1492. >>> return grad * ctx.y, None
  1493. >>>
  1494. >>> numpy_mul.register_autograd(backward, setup_context=setup_context)
  1495. >>>
  1496. >>> sample_inputs = [
  1497. >>> (torch.randn(3), 3.14),
  1498. >>> (torch.randn(2, 3, device='cuda'), 2.718),
  1499. >>> (torch.randn(1, 10, requires_grad=True), 1.234),
  1500. >>> (torch.randn(64, 64, device='cuda', requires_grad=True), 90.18),
  1501. >>> ]
  1502. >>>
  1503. >>> for args in sample_inputs:
  1504. >>> torch.library.opcheck(numpy_mul, args)
  1505. """
  1506. import torch.testing._internal.optests as optests
  1507. return optests.opcheck(
  1508. op,
  1509. args,
  1510. kwargs,
  1511. test_utils=test_utils,
  1512. raise_exception=raise_exception,
  1513. rtol=rtol,
  1514. atol=atol,
  1515. )