register a fake kernel for torch.compile and torch.export;
validate the operator with torch.library.opcheck.
Example: wrapping NumPy sin into a custom operator
Let’s say that we are using NumPy’s sin operation. This is an ordinary
Python function from PyTorch’s point of view: it converts the Tensor to a
NumPy array, calls NumPy, and returns a fresh Tensor.
importnumpyasnpimporttorchfromtorchimportTensordefnumpy_sin_impl(x:Tensor)->Tensor:result=torch.empty_like(x)np.sin(x.detach().numpy(),out=result.numpy())returnresultx=torch.randn(5)torch.testing.assert_close(numpy_sin_impl(x),x.sin())# This small example focuses on the custom-operator mechanics. More complex# Python or third-party library calls may not be handled effectively# out-of-the-box by ``torch.compile``: ``torch.compile`` may induce a# `"graph break" <https://pytorch.org/docs/stable/torch.compiler_faq.html#graph-breaks>`_# on functions it is unable to handle, and graph breaks are bad for performance.# A custom operator gives PyTorch an explicit boundary for such code.## To make ``numpy_sin_impl`` available as a custom operator that works with# ``torch.compile`` and ``torch.export``, we need to do two things:## 1. wrap the function into a PyTorch custom operator.# 2. add a "``FakeTensor`` kernel" (aka "meta kernel") to the operator.# Given some ``FakeTensors`` inputs (dummy Tensors that don't have storage),# this function should return dummy Tensors of your choice with the correct# Tensor metadata (shape/strides/``dtype``/device).@torch.library.custom_op("mylib_functional::numpy_sin",mutates_args=(),device_types="cpu",)defnumpy_sin(x:Tensor)->Tensor:result=torch.empty_like(x)np.sin(x.detach().numpy(),out=result.numpy())returnresult
Use register_fake to add a FakeTensor kernel for the operator.
numpy_sin returns one Tensor with the same shape, strides, dtype, device,
and storage offset as torch.empty_like(x), so the fake kernel can return
empty_like(x). In general, the fake kernel must match all output metadata,
including storage offset when relevant.
/usr/local/lib/python3.12/dist-packages/triton/knobs.py:504: UserWarning: TRITON_DEFAULT_FP_FUSION is unset: defaulting to FP fusion ENABLED for backward compatibility in Triton 3.9. The default will change to DISABLED in Triton 3.10; set TRITON_DEFAULT_FP_FUSION=1 to keep fusion enabled or =0 to adopt the new default early and silence this warning.
warn_once(FP_FUSION_DEFAULT_WARNING)
A PIL image transform, Python binding to a C++ extension, or another
third-party library call follows the same pattern. If it returns tensors,
write the fake kernel to match the real output metadata exactly: shape,
strides, dtype, device, layout, and storage offset when relevant.
Example: fake kernels must match strides
The fake kernel must match the real output strides, not only the shape. This
operator returns a fresh Tensor with the same shape as x but different
strides.
defnumpy_sin_strided_impl(x:Tensor)->Tensor:result=torch.empty_strided(x.shape,tuple(reversed(x.stride())),dtype=x.dtype,device=x.device,)np.sin(x.detach().numpy(),out=result.numpy())returnresult@torch.library.custom_op("mylib_functional::numpy_sin_strided_bad",mutates_args=(),device_types="cpu",)defnumpy_sin_strided_bad(x:Tensor)->Tensor:returnnumpy_sin_strided_impl(x)@numpy_sin_strided_bad.register_fakedef_(x):returntorch.empty_like(x)try:torch.library.opcheck(numpy_sin_strided_bad,(torch.randn(2,3),))exceptExceptionasexc:print(f"opcheck caught incorrect fake kernel metadata: {type(exc).__name__}")else:torch_version=tuple(int(part)forpartintorch.__version__.split("+")[0].split(".")[:2])iftorch_version>=(2,13):raiseAssertionError("Expected opcheck to fail")print("PyTorch versions before 2.13 may not catch this metadata mismatch")@torch.library.custom_op("mylib_functional::numpy_sin_strided",mutates_args=(),device_types="cpu",)defnumpy_sin_strided(x:Tensor)->Tensor:returnnumpy_sin_strided_impl(x)@numpy_sin_strided.register_fakedef_(x):returntorch.empty_strided(x.shape,tuple(reversed(x.stride())),dtype=x.dtype,device=x.device,)torch.library.opcheck(numpy_sin_strided,(torch.randn(2,3),))
Use torch.library.opcheck to test that the custom operator was registered
correctly. This does not test numerical correctness; write separate tests for
that.
To use opcheck, pass it a set of example inputs to test against. If your
operator supports training, then the examples should include Tensors that
require grad. If your operator supports multiple devices, then the examples
should include Tensors from each device.