custom_ops.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # mypy: allow-untyped-defs
  2. import inspect
  3. import weakref
  4. from typing import (
  5. Any,
  6. Callable,
  7. Dict,
  8. Iterable,
  9. Iterator,
  10. List,
  11. Optional,
  12. Sequence,
  13. Tuple,
  14. Union,
  15. )
  16. from torch.utils._exposed_in import exposed_in
  17. from .. import _C, _library, _ops, autograd, library, Tensor
  18. from . import utils
  19. device_types_t = Optional[Union[str, Sequence[str]]]
  20. @exposed_in("torch.library")
  21. def custom_op(
  22. name: str,
  23. fn: Optional[Callable] = None,
  24. /,
  25. *,
  26. mutates_args: Iterable[str],
  27. device_types: device_types_t = None,
  28. schema: Optional[str] = None,
  29. ) -> Callable:
  30. """Wraps a function into custom operator.
  31. Reasons why you may want to create a custom op include:
  32. - Wrapping a third-party library or custom kernel to work with PyTorch
  33. subsystems like Autograd.
  34. - Preventing torch.compile/export/FX tracing from peeking inside your function.
  35. This API is used as a decorator around a function (please see examples).
  36. The provided function must have type hints; these are needed to interface
  37. with PyTorch's various subsystems.
  38. Args:
  39. name (str): A name for the custom op that looks like "{namespace}::{name}",
  40. e.g. "mylib::my_linear". The name is used as the op's stable identifier
  41. in PyTorch subsystems (e.g. torch.export, FX graphs).
  42. To avoid name collisions, please use your project name as the namespace;
  43. e.g. all custom ops in pytorch/fbgemm use "fbgemm" as the namespace.
  44. mutates_args (Iterable[str]): The names of args that the function mutates.
  45. This MUST be accurate, otherwise, the behavior is undefined.
  46. device_types (None | str | Sequence[str]): The device type(s) the function
  47. is valid for. If no device type is provided, then the function
  48. is used as the default implementation for all device types.
  49. Examples: "cpu", "cuda".
  50. schema (None | str): A schema string for the operator. If None
  51. (recommended) we'll infer a schema for the operator from its type
  52. annotations. We recommend letting us infer a schema unless you
  53. have a specific reason not to.
  54. Example: "(Tensor x, int y) -> (Tensor, Tensor)".
  55. .. note::
  56. We recommend not passing in a ``schema`` arg and instead letting us infer
  57. it from the type annotations. It is error-prone to write your own schema.
  58. You may wish to provide your own schema if our interpretation of
  59. the type annotation is not what you want.
  60. For more info on how to write a schema string, see
  61. `here <https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/README.md#func>`_
  62. Examples::
  63. >>> import torch
  64. >>> from torch import Tensor
  65. >>> from torch.library import custom_op
  66. >>> import numpy as np
  67. >>>
  68. >>> @custom_op("mylib::numpy_sin", mutates_args=())
  69. >>> def numpy_sin(x: Tensor) -> Tensor:
  70. >>> x_np = x.cpu().numpy()
  71. >>> y_np = np.sin(x_np)
  72. >>> return torch.from_numpy(y_np).to(device=x.device)
  73. >>>
  74. >>> x = torch.randn(3)
  75. >>> y = numpy_sin(x)
  76. >>> assert torch.allclose(y, x.sin())
  77. >>>
  78. >>> # Example of a custom op that only works for one device type.
  79. >>> @custom_op("mylib::numpy_sin_cpu", mutates_args=(), device_types="cpu")
  80. >>> def numpy_sin_cpu(x: Tensor) -> Tensor:
  81. >>> x_np = x.numpy()
  82. >>> y_np = np.sin(x_np)
  83. >>> return torch.from_numpy(y_np)
  84. >>>
  85. >>> x = torch.randn(3)
  86. >>> y = numpy_sin_cpu(x)
  87. >>> assert torch.allclose(y, x.sin())
  88. >>>
  89. >>> # Example of a custom op that mutates an input
  90. >>> @custom_op("mylib::numpy_sin_inplace", mutates_args={"x"}, device_types="cpu")
  91. >>> def numpy_sin_inplace(x: Tensor) -> None:
  92. >>> x_np = x.numpy()
  93. >>> np.sin(x_np, out=x_np)
  94. >>>
  95. >>> x = torch.randn(3)
  96. >>> expected = x.sin()
  97. >>> numpy_sin_inplace(x)
  98. >>> assert torch.allclose(x, expected)
  99. """
  100. def inner(fn):
  101. import torch
  102. if schema is None:
  103. import torch._custom_op.impl
  104. schema_str = torch._custom_op.impl.infer_schema(fn, mutates_args)
  105. else:
  106. schema_str = schema
  107. namespace, opname = name.split("::")
  108. result = CustomOpDef(namespace, opname, schema_str, fn)
  109. if schema is not None:
  110. # Check that schema's alias annotations match those of `mutates_args`.
  111. expected = set()
  112. for arg in result._opoverload._schema.arguments:
  113. if arg.alias_info is not None and arg.alias_info.is_write:
  114. expected.add(arg.name)
  115. if expected != set(mutates_args):
  116. raise ValueError(
  117. f"Attempted to create a custom op with `mutates_args={mutates_args}` "
  118. f"and `schema={schema}. The schema suggests that the op mutates {expected}"
  119. f"which is different from what was provided to us in `mutates_args`. "
  120. f"Please make these consistent."
  121. )
  122. result.register_kernel(device_types)(fn)
  123. return result
  124. if fn is None:
  125. return inner
  126. return inner(fn)
  127. class CustomOpDef:
  128. """CustomOpDef is a wrapper around a function that turns it into a custom op.
  129. It has various methods for registering additional behavior for this
  130. custom op.
  131. You should not instantiate CustomOpDef directly; instead, use the
  132. :func:`torch.library.custom_op` API.
  133. """
  134. def __init__(self, namespace: str, name: str, schema: str, fn: Callable) -> None:
  135. # Fields used to interface with the PyTorch dispatcher
  136. self._namespace = namespace
  137. self._name = name
  138. self._schema = schema
  139. self._init_fn = fn
  140. self._backend_fns: Dict[Union[str, None], Callable] = {}
  141. self._abstract_fn: Optional[Callable] = None
  142. self._setup_context_fn: Optional[Callable] = None
  143. self._backward_fn: Optional[Callable] = None
  144. self._lib = get_library_allowing_overwrite(self._namespace, self._name)
  145. self._register_to_dispatcher()
  146. OPDEFS[self._qualname] = self
  147. @property
  148. def _qualname(self) -> str:
  149. return f"{self._namespace}::{self._name}"
  150. def __repr__(self) -> str:
  151. return f"<CustomOpDef({self._qualname})>"
  152. def register_kernel(
  153. self, device_types: device_types_t, fn: Optional[Callable] = None, /
  154. ) -> Callable:
  155. """Register an implementation for a device type for this operator.
  156. Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".
  157. This API may be used as a decorator.
  158. Args:
  159. fn (Callable): The function to register as the implementation for
  160. the given device types.
  161. device_types (str | Sequence[str]): The device device_types to register an impl to.
  162. Examples::
  163. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  164. >>> import torch
  165. >>> from torch import Tensor
  166. >>> from torch.library import custom_op
  167. >>> import numpy as np
  168. >>>
  169. >>> # Create a custom op that works on cpu
  170. >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu")
  171. >>> def numpy_sin(x: Tensor) -> Tensor:
  172. >>> x_np = x.numpy()
  173. >>> y_np = np.sin(x_np)
  174. >>> return torch.from_numpy(y_np)
  175. >>>
  176. >>> # Add implementations for the cuda device
  177. >>> @numpy_sin.register_kernel("cuda")
  178. >>> def _(x):
  179. >>> x_np = x.cpu().numpy()
  180. >>> y_np = np.sin(x_np)
  181. >>> return torch.from_numpy(y_np).to(device=x.device)
  182. >>>
  183. >>> x_cpu = torch.randn(3)
  184. >>> x_cuda = x_cpu.cuda()
  185. >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin())
  186. >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin())
  187. """
  188. def inner(fn):
  189. if device_types is None or isinstance(device_types, str):
  190. dtypes: List[Union[str, None]] = [device_types]
  191. else:
  192. dtypes = list(device_types)
  193. for device_type in dtypes:
  194. if device_type not in self._backend_fns:
  195. def backend_impl(*args, **kwargs):
  196. # Checks the assumption that outputs cannot alias
  197. # inputs or other outputs.
  198. storages = {
  199. id(tensor.untyped_storage())
  200. for tensor in iter_tensors(args, kwargs)
  201. }
  202. result = self._backend_fns[device_type](*args, **kwargs)
  203. tuple_result = result
  204. if not isinstance(result, tuple):
  205. tuple_result = (result,)
  206. for tensor in iter_tensors(tuple_result, {}):
  207. key = id(tensor.untyped_storage())
  208. if id(tensor.untyped_storage()) in storages:
  209. fn = self._backend_fns[device_type]
  210. module = inspect.getmodule(fn)
  211. raise RuntimeError(
  212. f"Tensors returned from custom ops (1) must not "
  213. f"be inputs to the custom op and (2) may not alias "
  214. f"any inputs or other returns. Please clone the "
  215. f"the offending output tensors (e.g. output.clone()) "
  216. f"or refactor your code. "
  217. f"Offending op: {self._name} (with implementation in {module})"
  218. )
  219. storages.add(key)
  220. return result
  221. if device_type is None:
  222. self._lib.impl(
  223. self._name, backend_impl, "CompositeExplicitAutograd"
  224. )
  225. else:
  226. self._lib.impl(
  227. self._name,
  228. backend_impl,
  229. _C._dispatch_key_for_device(device_type),
  230. )
  231. self._backend_fns[device_type] = fn
  232. return fn
  233. # See NOTE: [Supporting decorator and non-decorator usage]
  234. if fn is None:
  235. return inner
  236. return inner(fn)
  237. def register_fake(self, fn: Callable, /) -> Callable:
  238. r"""Register a FakeTensor implementation for this custom op.
  239. This is necessary to get the operator to work efficiently with torch.compile.
  240. The Fake impl (sometimes also known as a meta kernel or abstract impl)
  241. specifies the behavior of this operator on Tensors that carry no data.
  242. Given some input Tensors with certain properties
  243. (sizes/strides/storage_offset/device), it specifies what the properties of
  244. the output Tensors are.
  245. Please see :func:`torch.library.impl_abstract` for more details.
  246. Args:
  247. fn (Callable): The function to register as the FakeTensor
  248. implementation.
  249. Examples:
  250. >>> import torch
  251. >>> import numpy as np
  252. >>> from torch import Tensor
  253. >>>
  254. >>> # Example 1: an operator without data-dependent output shape
  255. >>> @torch.library.custom_op("mylib::linear", mutates_args=())
  256. >>> def linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
  257. >>> return (x @ weight.t()) + bias
  258. >>>
  259. >>> @linear.register_fake
  260. >>> def _(x, weight, bias):
  261. >>> assert x.dim() == 2
  262. >>> assert weight.dim() == 2
  263. >>> assert bias.dim() == 1
  264. >>> assert x.shape[1] == weight.shape[1]
  265. >>> assert weight.shape[0] == bias.shape[0]
  266. >>> assert x.device == weight.device
  267. >>> return x.new_empty(x.size(0), weight.size(0))
  268. >>>
  269. >>> x = torch.randn(2, 2)
  270. >>> weight = torch.randn(2, 2)
  271. >>> bias = torch.randn(2)
  272. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  273. >>> out = torch.compile(linear, fullgraph=True)(x, weight, bias)
  274. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  275. >>> assert torch.allclose(out, torch.nn.functional.linear(x, weight, bias))
  276. >>>
  277. >>> # Example 2: an operator with data-dependent output shape
  278. >>> @torch.library.custom_op("mylib::nonzero", mutates_args=())
  279. >>> def nonzero(x: Tensor) -> Tensor:
  280. >>> x_np = x.cpu().numpy()
  281. >>> res = np.stack(np.nonzero(x_np), axis=1)
  282. >>> return torch.tensor(res, device=x.device)
  283. >>>
  284. >>> @nonzero.register_fake
  285. >>> def _(x):
  286. >>> # Number of nonzero-elements is data-dependent.
  287. >>> # Since we cannot peek at the data in an abstract impl,
  288. >>> # we use the ctx object to construct a new symint that
  289. >>> # represents the data-dependent size.
  290. >>> ctx = torch.library.get_ctx()
  291. >>> nnz = ctx.new_dynamic_size()
  292. >>> shape = [nnz, x.dim()]
  293. >>> result = x.new_empty(shape, dtype=torch.int64)
  294. >>> return result
  295. >>>
  296. >>> x = torch.tensor([0, 1, 2, 0, 0, 1])
  297. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  298. >>> out = torch.compile(nonzero, fullgraph=True)(x)
  299. >>> # xdoctest: +SKIP("Requires Python <= 3.11")
  300. >>> assert torch.allclose(out, x.nonzero())
  301. """
  302. self._abstract_fn = fn
  303. return fn
  304. def register_autograd(
  305. self,
  306. backward: Callable,
  307. /,
  308. *,
  309. setup_context: Optional[Callable] = None,
  310. ) -> None:
  311. r"""Register a backward formula for this custom op.
  312. In order for an operator to work with autograd, you need to register
  313. a backward formula:
  314. 1. You must tell us how to compute gradients during the backward pass
  315. by providing us a "backward" function.
  316. 2. If you need any values from the forward to compute gradients, you can
  317. use `setup_context` to save values for backward.
  318. ``backward_fn`` runs during the backward pass. It accepts ``(ctx, *grads)``:
  319. - ``grads`` is one or more gradients. The number of gradients matches
  320. the number of outputs of the operator.
  321. The ``ctx`` object is `the same ctx object <context_method_mixins>`_ used by
  322. :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the
  323. same as :meth:`torch.autograd.Function.backward`.
  324. ``setup_context(ctx, inputs, output)`` runs during the forward pass.
  325. Please save quantities needed for backward onto the ``ctx`` object via
  326. either :meth:`torch.autograd.function.FunctionCtx.save_for_backward`
  327. or assigning them as attributes of ``ctx``. If your custom op has
  328. kwarg-only arguments, we expect the signature of ``setup_context``
  329. to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``.
  330. Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is,
  331. they may not directly access :meth:`torch.Tensor.data_ptr` and they must
  332. not depend on or mutate global state. If you need a non-traceable backward,
  333. you can make it a separate custom_op that you call inside ``backward_fn``.
  334. Examples:
  335. >>> import torch
  336. >>> import numpy as np
  337. >>> from torch import Tensor
  338. >>>
  339. >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=())
  340. >>> def numpy_sin(x: Tensor) -> Tensor:
  341. >>> x_np = x.cpu().numpy()
  342. >>> y_np = np.sin(x_np)
  343. >>> return torch.from_numpy(y_np).to(device=x.device)
  344. >>>
  345. >>> def setup_context(ctx, inputs, output) -> Tensor:
  346. >>> x, = inputs
  347. >>> ctx.save_for_backward(x)
  348. >>>
  349. >>> def backward(ctx, grad):
  350. >>> x, = ctx.saved_tensors
  351. >>> return grad * x.cos()
  352. >>>
  353. >>> numpy_sin.register_autograd(backward, setup_context=setup_context)
  354. >>>
  355. >>> x = torch.randn(3, requires_grad=True)
  356. >>> y = numpy_sin(x)
  357. >>> grad_x, = torch.autograd.grad(y, x, torch.ones_like(y))
  358. >>> assert torch.allclose(grad_x, x.cos())
  359. >>>
  360. >>> # Example with a keyword-only arg
  361. >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
  362. >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor:
  363. >>> x_np = x.cpu().numpy()
  364. >>> y_np = x_np * val
  365. >>> return torch.from_numpy(y_np).to(device=x.device)
  366. >>>
  367. >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor:
  368. >>> ctx.val = keyword_only_inputs["val"]
  369. >>>
  370. >>> def backward(ctx, grad):
  371. >>> return grad * ctx.val
  372. >>>
  373. >>> numpy_mul.register_autograd(backward, setup_context=setup_context)
  374. >>>
  375. >>> x = torch.randn(3, requires_grad=True)
  376. >>> y = numpy_mul(x, val=3.14)
  377. >>> grad_x, = torch.autograd.grad(y, x, torch.ones_like(y))
  378. >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14))
  379. """
  380. schema = self._opoverload._schema
  381. if not _library.utils.is_functional_schema(schema):
  382. raise RuntimeError(
  383. f"Cannot register autograd formula for non-functional operator "
  384. f"{self} with schema {schema}. Please create "
  385. f"a functional operator and register an autograd formula for that."
  386. )
  387. self._backward_fn = backward
  388. self._setup_context_fn = setup_context
  389. def _register_to_dispatcher(self) -> None:
  390. lib = self._lib
  391. schema_str = self._name + self._schema
  392. cpp_schema = _C.parse_schema(schema_str)
  393. if utils.has_kwarg_only_tensors(cpp_schema):
  394. # If you want to support this, the progression is:
  395. # - supporting kwarg-only Tensors that are non-differentiable
  396. # - supporting kwarg-only Tensors (regardless of differentiability)
  397. raise NotImplementedError(
  398. f"custom_op with kwarg-only Tensor args. Please make your "
  399. f"tensors not kwarg-only. Got: {schema_str}"
  400. )
  401. lib.define(
  402. schema_str,
  403. tags=[_C.Tag.pt2_compliant_tag, _C.Tag.needs_fixed_stride_order],
  404. )
  405. self._opoverload = _library.utils.lookup_op(self._qualname)
  406. def fake_impl(*args, **kwargs):
  407. if self._abstract_fn is None:
  408. if _library.utils.can_generate_trivial_fake_impl(self._opoverload):
  409. return None
  410. raise RuntimeError(
  411. f"There was no fake impl registered for {self}. "
  412. f"This is necessary for torch.compile/export/fx tracing to work. "
  413. f"Please use `{self._init_fn.__name__}.register_fake` to add an "
  414. f"fake impl."
  415. )
  416. return self._abstract_fn(*args, **kwargs)
  417. lib._register_fake(self._name, fake_impl, _stacklevel=4)
  418. autograd_impl = _library.autograd.make_autograd_impl(self._opoverload, self)
  419. lib.impl(self._name, autograd_impl, "Autograd", with_keyset=True)
  420. schema = self._opoverload._schema
  421. if schema.is_mutable:
  422. def adinplaceorview_impl(keyset, *args, **kwargs):
  423. for arg, val in _library.utils.zip_schema(schema, args, kwargs):
  424. if not arg.alias_info:
  425. continue
  426. if not arg.alias_info.is_write:
  427. continue
  428. if isinstance(val, Tensor):
  429. autograd.graph.increment_version(val)
  430. elif isinstance(val, (tuple, list)):
  431. for v in val:
  432. if isinstance(v, Tensor):
  433. autograd.graph.increment_version(v)
  434. with _C._AutoDispatchBelowADInplaceOrView():
  435. return self._opoverload.redispatch(
  436. keyset & _C._after_ADInplaceOrView_keyset, *args, **kwargs
  437. )
  438. lib.impl(
  439. self._name,
  440. adinplaceorview_impl,
  441. "ADInplaceOrView",
  442. with_keyset=True,
  443. )
  444. def __call__(self, *args, **kwargs):
  445. return self._opoverload(*args, **kwargs)
  446. # NOTE: [Supporting decorator and non-decorator usage]
  447. #
  448. # Some APIs may be both used as a decorator and not as a decorator.
  449. # For example:
  450. #
  451. # >>> def fn(x):
  452. # >>> return x.sin()
  453. # >>>
  454. # >>> # Usage 1: not as a decorator
  455. # >>> numpy_sin.register_kernel("cuda", fn)
  456. # >>>
  457. # >>> # Usage 2: as a decorator
  458. # >>> @numpy_sin.register_kernel("cuda")
  459. # >>> def fn2(x):
  460. # >>> return x.sin
  461. #
  462. # The way we support this is that `register_kernel` accepts an optional `fn`.
  463. # If `fn` is provided (Usage 1), then we know that the user is using it not
  464. # as a decorator.
  465. # If `fn` is not provided (Usage 2), then `register_kernel` needs to return a
  466. # decorator.
  467. OPDEF_TO_LIB: Dict[str, "library.Library"] = {}
  468. OPDEFS: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
  469. def get_library_allowing_overwrite(namespace: str, name: str) -> "library.Library":
  470. qualname = f"{namespace}::{name}"
  471. if qualname in OPDEF_TO_LIB:
  472. OPDEF_TO_LIB[qualname]._destroy()
  473. del OPDEF_TO_LIB[qualname]
  474. lib = library.Library(namespace, "FRAGMENT")
  475. OPDEF_TO_LIB[qualname] = lib
  476. return lib
  477. def iter_tensors(
  478. args: Tuple[Any], kwargs: Dict[str, Any], allowed_nesting: int = 1
  479. ) -> Iterator[Tensor]:
  480. def check(arg):
  481. if isinstance(arg, Tensor):
  482. yield arg
  483. elif allowed_nesting > 0 and isinstance(arg, (tuple, list)):
  484. yield from iter_tensors(tuple(arg), {}, allowed_nesting - 1)
  485. for arg in args:
  486. yield from check(arg)
  487. for kwarg in kwargs.values():
  488. yield from check(kwarg)
  489. def _maybe_get_opdef(
  490. op: Union[CustomOpDef, _ops.OpOverload, str]
  491. ) -> Optional[CustomOpDef]:
  492. if isinstance(op, CustomOpDef):
  493. return op
  494. if isinstance(op, _ops.OpOverload):
  495. op = op._name
  496. assert isinstance(op, str)
  497. if op in OPDEFS:
  498. return OPDEFS[op]
  499. return None