• 教程 >
  • 自定义 Python 操作
快捷键

自定义 Python 运算符 ¶

创建于:2025 年 4 月 1 日 | 最后更新:2025 年 4 月 1 日 | 最后验证:2024 年 11 月 5 日

你将学到什么
  • 如何将用 Python 编写的自定义运算符与 PyTorch 集成

  • 如何使用 torch.library.opcheck 测试自定义算子

前提条件
  • PyTorch 2.4 或更高版本

PyTorch 提供了一个大型库,其中包含在张量上工作的运算符(例如 torch.addtorch.sum 等)。然而,您可能希望使用 PyTorch 的新自定义运算符,这可能是由第三方库编写的。本教程展示了如何包装 Python 函数,使其表现得像 PyTorch 原生运算符。您可能希望在 PyTorch 中创建自定义运算符的原因包括:

  • 将任意 Python 函数作为不可见调用处理(即防止 torch.compile 追踪进入函数)。

  • 为任意 Python 函数添加训练支持

使用 torch.library.custom_op() 创建 Python 自定义操作符。使用 C++的 TORCH_LIBRARY API 创建 C++自定义操作符(这些在无 Python 的环境中也能工作)。有关更多详细信息,请参阅自定义操作符页面。

请注意,如果您的操作可以用现有 PyTorch 操作符的组合来表示,那么通常不需要使用自定义操作符 API - 所有内容(例如 torch.compile 、训练支持)都应该正常工作。

示例:将 PIL 的裁剪操作封装成自定义运算符

假设我们正在使用 PIL 的 crop 操作。

import torch
from torchvision.transforms.functional import to_pil_image, pil_to_tensor
import PIL
import IPython
import matplotlib.pyplot as plt

def crop(pic, box):
    img = to_pil_image(pic.cpu())
    cropped_img = img.crop(box)
    return pil_to_tensor(cropped_img).to(pic.device) / 255.

def display(img):
    plt.imshow(img.numpy().transpose((1, 2, 0)))

img = torch.ones(3, 64, 64)
img *= torch.linspace(0, 1, steps=64) * torch.linspace(0, 1, steps=64).unsqueeze(-1)
display(img)
cropped_img = crop(img, (10, 10, 50, 50))
display(cropped_img)

crop 默认情况下并没有被 torch.compile 有效处理: torch.compile 在无法处理函数时会导致“图断开”,而图断开对性能不利。以下代码通过引发错误来演示这一点( torch.compilefullgraph=True 一起引发错误,如果发生图断开)。

@torch.compile(fullgraph=True)
def f(img):
    return crop(img, (10, 10, 50, 50))

# The following raises an error. Uncomment the line to see it.
# cropped_img = f(img)

为了将 crop 黑盒化以与 torch.compile 一起使用,我们需要做两件事:

  1. 将函数封装成 PyTorch 自定义算子。

  2. 在算子中添加一个“ FakeTensor kernel”(即“元 kernel”)。给定一些 FakeTensors 输入(没有存储的虚拟张量),此函数应返回您选择的虚拟张量,并带有正确的张量元数据(形状/步长/ dtype /设备)。

from typing import Sequence

# Use torch.library.custom_op to define a new custom operator.
# If your operator mutates any input Tensors, their names must be specified
# in the ``mutates_args`` argument.
@torch.library.custom_op("mylib::crop", mutates_args=())
def crop(pic: torch.Tensor, box: Sequence[int]) -> torch.Tensor:
    img = to_pil_image(pic.cpu())
    cropped_img = img.crop(box)
    return (pil_to_tensor(cropped_img) / 255.).to(pic.device, pic.dtype)

# Use register_fake to add a ``FakeTensor`` kernel for the operator
@crop.register_fake
def _(pic, box):
    channels = pic.shape[0]
    x0, y0, x1, y1 = box
    result = pic.new_empty(y1 - y0, x1 - x0, channels).permute(2, 0, 1)
    # The result should have the same metadata (shape/strides/``dtype``/device)
    # as running the ``crop`` function above.
    return result

之后, crop 现在可以无图断点地工作:

@torch.compile(fullgraph=True)
def f(img):
    return crop(img, (10, 10, 50, 50))

cropped_img = f(img)
display(img)
display(cropped_img)

添加对 crop ¶的训练支持

使用 torch.library.register_autograd 为操作符添加训练支持。优先使用此方法,而不是直接使用 torch.autograd.Function ;当与 autograd.Function 与 PyTorch 操作符注册 API 的某些组合时,可能会导致(并且已经导致了)与 torch.compile 组合时的静默错误。

如果您不需要训练支持,则无需使用 torch.library.register_autograd 。如果您使用没有自动微分注册的 custom_op 进行训练,我们将引发错误消息。

crop 的梯度公式本质上等同于 PIL.paste (我们将推导过程留给读者作为练习)。首先,让我们将 paste 包装成一个自定义操作符:

@torch.library.custom_op("mylib::paste", mutates_args=())
def paste(im1: torch.Tensor, im2: torch.Tensor, coord: Sequence[int]) -> torch.Tensor:
    assert im1.device == im2.device
    assert im1.dtype == im2.dtype
    im1_pil = to_pil_image(im1.cpu())
    im2_pil = to_pil_image(im2.cpu())
    PIL.Image.Image.paste(im1_pil, im2_pil, coord)
    return (pil_to_tensor(im1_pil) / 255.).to(im1.device, im1.dtype)

@paste.register_fake
def _(im1, im2, coord):
    assert im1.device == im2.device
    assert im1.dtype == im2.dtype
    return torch.empty_like(im1)

现在,让我们使用 register_autograd 来指定 crop 的梯度公式:

def backward(ctx, grad_output):
    grad_input = grad_output.new_zeros(ctx.pic_shape)
    grad_input = paste(grad_input, grad_output, ctx.coords)
    return grad_input, None

def setup_context(ctx, inputs, output):
    pic, box = inputs
    ctx.coords = box[:2]
    ctx.pic_shape = pic.shape

crop.register_autograd(backward, setup_context=setup_context)

注意,反向操作必须是 PyTorch 理解的运算符的组合,这就是为什么我们将粘贴操作封装成自定义运算符,而不是直接使用 PIL 的粘贴功能。

img = img.requires_grad_()
result = crop(img, (10, 10, 50, 50))
result.sum().backward()
display(img.grad)

这是正确的梯度,裁剪区域为 1(白色),未使用区域为 0(黑色)。

测试 Python 自定义运算符

使用 torch.library.opcheck 来测试自定义运算符是否正确注册。这并不测试梯度在数学上的正确性;请为这一点编写单独的测试(无论是手动测试还是 torch.autograd.gradcheck )。

使用 opcheck 时,请传递一组示例输入进行测试。如果您的操作符支持训练,则示例应包括需要梯度的张量。如果您的操作符支持多个设备,则示例应包括来自每个设备的张量。

examples = [
    [torch.randn(3, 64, 64), [0, 0, 10, 10]],
    [torch.randn(3, 91, 91, requires_grad=True), [10, 0, 20, 10]],
    [torch.randn(3, 60, 60, dtype=torch.double), [3, 4, 32, 20]],
    [torch.randn(3, 512, 512, requires_grad=True, dtype=torch.double), [3, 4, 32, 45]],
]

for example in examples:
    torch.library.opcheck(crop, example)

可变 Python 自定义操作符

您还可以将修改其输入的 Python 函数包装成自定义操作符。修改输入的函数很常见,因为许多底层内核都是这样编写的;例如,一个计算 sin 的内核可能需要输入和一个输出张量,并将 input.sin() 写入输出张量。

我们将使用 numpy.sin 来演示一个可变 Python 自定义操作符的示例。

import numpy as np

@torch.library.custom_op("mylib::numpy_sin", mutates_args={"output"}, device_types="cpu")
def numpy_sin(input: torch.Tensor, output: torch.Tensor) -> None:
    assert input.device == output.device
    assert input.device.type == "cpu"
    input_np = input.numpy()
    output_np = output.numpy()
    np.sin(input_np, out=output_np)

因为操作符不返回任何内容,所以没有必要注册一个 FakeTensor 内核(元内核)来使其与 torch.compile 协同工作。

@torch.compile(fullgraph=True)
def f(x):
    out = torch.empty(3)
    numpy_sin(x, out)
    return out

x = torch.randn(3)
y = f(x)
assert torch.allclose(y, x.sin())

以下是 opcheck 的运行结果,告诉我们确实正确地注册了操作符。如果我们忘记将输出添加到 mutates_args ,例如, opcheck 将会出错。

example_inputs = [
    [torch.randn(3), torch.empty(3)],
    [torch.randn(0, 3), torch.empty(0, 3)],
    [torch.randn(1, 2, 3, 4, dtype=torch.double), torch.empty(1, 2, 3, 4, dtype=torch.double)],
]

for example in example_inputs:
    torch.library.opcheck(numpy_sin, example)

结论 ¶

在本教程中,我们学习了如何使用 torch.library.custom_op 在 Python 中创建一个自定义操作符,使其与 PyTorch 子系统如 torch.compile 和 autograd 协同工作。

本教程提供了自定义操作符的基本介绍。如需更详细的信息,请参阅:

脚本总运行时间:(0 分钟 0.000 秒)

由 Sphinx-Gallery 生成的画廊


评分这个教程

© 版权所有 2024,PyTorch。

使用 Sphinx 构建,主题由 Read the Docs 提供。
//暂时添加调查链接

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源