torch.library#
创建于: 2022年6月13日 | 最新更新于: 2025年6月7日
torch.library 是一组用于扩展 PyTorch 核心操作符库的 API。它包含用于测试自定义操作符、创建新自定义操作符以及扩展使用 PyTorch C++ 操作符注册 API (例如 aten 操作符) 定义的操作符的实用程序。
有关有效使用这些 API 的详细指南,请参阅 PyTorch 自定义操作符入门页面 以了解更多关于如何有效使用这些 API 的信息。
测试自定义操作#
使用 torch.library.opcheck()
来测试自定义操作符是否不正确地使用了 Python torch.library 和/或 C++ TORCH_LIBRARY API。此外,如果您的操作符支持训练,请使用 torch.autograd.gradcheck()
来测试梯度是否数学上正确。
- torch.library.opcheck(op, args, kwargs=None, *, test_utils=('test_schema', 'test_autograd_registration', 'test_faketensor', 'test_aot_dispatch_dynamic'), raise_exception=True, atol=None, rtol=None)[source]#
给定一个操作符和一些示例参数,测试该操作符是否正确注册。
也就是说,当您使用 torch.library/TORCH_LIBRARY API 创建自定义操作符时,您指定了关于自定义操作符的元数据(例如可变性信息),并且这些 API 要求您传递给它们的函数满足某些属性(例如 fake/meta/abstract 内核中没有数据指针访问)。
opcheck
测试这些元数据和属性。具体来说,我们测试以下内容:
test_schema:如果 schema 与操作符的实现匹配。例如:如果 schema 指定 Tensor 是可变的,则我们检查实现是否使 Tensor 可变。如果 schema 指定我们返回一个新的 Tensor,则我们检查实现是否返回一个新的 Tensor(而不是现有 Tensor 或现有 Tensor 的视图)。
test_autograd_registration:如果操作符支持训练(autograd):我们检查其 autograd 公式是否通过 torch.library.register_autograd 或手动注册到一个或多个 DispatchKey::Autograd 键。任何其他基于 DispatchKey 的注册都可能导致未定义的行为。
test_faketensor:如果操作符有一个 FakeTensor 内核(以及它是否正确)。FakeTensor 内核对于操作符与 PyTorch 编译 API (torch.compile/export/FX) 配合使用是必要的(但不是充分的)。我们检查是否为操作符注册了 FakeTensor 内核(有时也称为元内核)并且它是正确的。此测试将操作符在真实张量上运行的结果与在 FakeTensor 上运行的结果进行比较,并检查它们是否具有相同的 Tensor 元数据(大小/步幅/dtype/设备等)。
test_aot_dispatch_dynamic:如果操作符与 PyTorch 编译 API (torch.compile/export/FX) 具有正确的行为。这将检查在 eager-mode PyTorch 和 torch.compile 下,输出(以及梯度,如果适用)是否相同。此测试是
test_faketensor
的超集,是一个端到端测试;它还测试其他内容,例如操作符是否支持函数化,以及反向传播(如果存在)是否也支持 FakeTensor 和函数化。
为了获得最佳结果,请使用具有代表性输入集多次调用
opcheck
。如果您的操作符支持 autograd,请使用opcheck
和requires_grad = True
的输入;如果您的操作符支持多个设备(例如 CPU 和 CUDA),请使用opcheck
和所有支持设备上的输入。- 参数
op (Union[OpOverload, OpOverloadPacket, CustomOpDef]) – 操作符。必须是使用
torch.library.custom_op()
装饰的函数,或 torch.ops.* 中找到的 OpOverload/OpOverloadPacket(例如 torch.ops.aten.sin, torch.ops.mylib.foo)test_utils (Union[str, Sequence[str]]) – 应该运行的测试。默认:所有测试。示例:("test_schema", "test_faketensor")
raise_exception (bool) – 如果在第一个错误时应抛出异常。如果为 False,将返回一个字典,其中包含每个测试是否通过的信息。
rtol (Optional[float]) – 浮点比较的相对容差。如果指定,则
atol
也必须指定。如果省略,将根据dtype
选择默认值(参见torch.testing.assert_close()
中的表格)。atol (Optional[float]) – 浮点比较的绝对容差。如果指定,则
rtol
也必须指定。如果省略,将根据dtype
选择默认值(参见torch.testing.assert_close()
中的表格)。
- 返回类型
警告
opcheck 和
torch.autograd.gradcheck()
测试不同的东西;opcheck 测试您对 torch.library API 的使用是否正确,而torch.autograd.gradcheck()
测试您的自动梯度公式是否在数学上正确。同时使用它们来测试支持梯度计算的自定义操作。示例
>>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) >>> def numpy_mul(x: Tensor, y: float) -> Tensor: >>> x_np = x.numpy(force=True) >>> z_np = x_np * y >>> return torch.from_numpy(z_np).to(x.device) >>> >>> @numpy_mul.register_fake >>> def _(x, y): >>> return torch.empty_like(x) >>> >>> def setup_context(ctx, inputs, output): >>> y, = inputs >>> ctx.y = y >>> >>> def backward(ctx, grad): >>> return grad * ctx.y, None >>> >>> numpy_mul.register_autograd(backward, setup_context=setup_context) >>> >>> sample_inputs = [ >>> (torch.randn(3), 3.14), >>> (torch.randn(2, 3, device='cuda'), 2.718), >>> (torch.randn(1, 10, requires_grad=True), 1.234), >>> (torch.randn(64, 64, device='cuda', requires_grad=True), 90.18), >>> ] >>> >>> for args in sample_inputs: >>> torch.library.opcheck(numpy_mul, args)
在 Python 中创建新的自定义操作#
使用 torch.library.custom_op()
创建新的自定义操作。
- torch.library.custom_op(name, fn=None, /, *, mutates_args, device_types=None, schema=None, tags=None)[源]#
将函数封装到自定义运算符中。
您可能想要创建自定义操作的原因包括:- 将第三方库或自定义内核封装起来以与 PyTorch 子系统(如 Autograd)一起使用。- 防止 torch.compile/export/FX 跟踪窥探您的函数内部。
此 API 用作函数周围的装饰器(请参阅示例)。提供的函数必须具有类型提示;这些是与 PyTorch 的各种子系统接口所必需的。
- 参数
name (str) – 自定义操作的名称,形式为“{namespace}::{name}”,例如“mylib::my_linear”。该名称用作操作在 PyTorch 子系统(例如 torch.export、FX 图)中的稳定标识符。为避免名称冲突,请使用您的项目名称作为命名空间;例如,pytorch/fbgemm 中的所有自定义操作都使用“fbgemm”作为命名空间。
mutates_args (Iterable[str] 或 "unknown") – 函数修改的参数名称。这必须准确,否则行为是未定义的。如果为“unknown”,则悲观地假定运算符的所有输入都被修改。
device_types (None | str | Sequence[str]) – 函数有效的设备类型。如果未提供设备类型,则该函数将用作所有设备类型的默认实现。示例:“cpu”、“cuda”。当为不接受张量的运算符注册特定于设备的实现时,我们要求运算符具有“device: torch.device 参数”。
schema (None | str) – 运算符的模式字符串。如果为 None(推荐),我们将从其类型注释中推断出运算符的模式。除非您有特殊原因不这样做,否则我们建议让 PyTorch 推断模式。示例:“(Tensor x, int y) -> (Tensor, Tensor)”。
- 返回类型
Union[Callable[[Callable[[…], object]], CustomOpDef], CustomOpDef]
注意
我们建议不要传入
schema
参数,而是让我们从类型注释中推断它。自己编写模式容易出错。如果我们对类型注释的解释不是您想要的,您可能希望提供自己的模式。有关如何编写模式字符串的更多信息,请参阅此处- 示例:
>>> import torch >>> from torch import Tensor >>> from torch.library import custom_op >>> import numpy as np >>> >>> @custom_op("mylib::numpy_sin", mutates_args=()) >>> def numpy_sin(x: Tensor) -> Tensor: >>> x_np = x.cpu().numpy() >>> y_np = np.sin(x_np) >>> return torch.from_numpy(y_np).to(device=x.device) >>> >>> x = torch.randn(3) >>> y = numpy_sin(x) >>> assert torch.allclose(y, x.sin()) >>> >>> # Example of a custom op that only works for one device type. >>> @custom_op("mylib::numpy_sin_cpu", mutates_args=(), device_types="cpu") >>> def numpy_sin_cpu(x: Tensor) -> Tensor: >>> x_np = x.numpy() >>> y_np = np.sin(x_np) >>> return torch.from_numpy(y_np) >>> >>> x = torch.randn(3) >>> y = numpy_sin_cpu(x) >>> assert torch.allclose(y, x.sin()) >>> >>> # Example of a custom op that mutates an input >>> @custom_op("mylib::numpy_sin_inplace", mutates_args={"x"}, device_types="cpu") >>> def numpy_sin_inplace(x: Tensor) -> None: >>> x_np = x.numpy() >>> np.sin(x_np, out=x_np) >>> >>> x = torch.randn(3) >>> expected = x.sin() >>> numpy_sin_inplace(x) >>> assert torch.allclose(x, expected) >>> >>> # Example of a factory function >>> @torch.library.custom_op("mylib::bar", mutates_args={}, device_types="cpu") >>> def bar(device: torch.device) -> Tensor: >>> return torch.ones(3) >>> >>> bar("cpu")
- torch.library.triton_op(name, fn=None, /, *, mutates_args, schema=None)[源]#
创建一个自定义运算符,其实现由 1 个或多个 Triton 内核支持。
这是使用 Triton 内核与 PyTorch 更结构化的方式。优先使用没有
torch.library
自定义运算符包装器(如torch.library.custom_op()
、torch.library.triton_op()
)的 Triton 内核,因为它更简单;仅当您想创建行为类似于 PyTorch 内置运算符的运算符时才使用torch.library.custom_op()
/torch.library.triton_op()
。例如,您可以使用torch.library
包装器 API 来定义 Triton 内核在传递张量子类或在 TorchDispatchMode 下的行为。当实现包含 1 个或多个 Triton 内核时,请使用
torch.library.triton_op()
而不是torch.library.custom_op()
。torch.library.custom_op()
将自定义运算符视为不透明的(torch.compile()
和torch.export.export()
永远不会跟踪它们),但triton_op
会使实现对这些子系统可见,允许它们优化 Triton 内核。请注意,
fn
必须仅包含对 PyTorch 可理解运算符和 Triton 内核的调用。在fn
内部调用的任何 Triton 内核都必须封装在对torch.library.wrap_triton()
的调用中。- 参数
name (str) – 自定义操作的名称,形式为“{namespace}::{name}”,例如“mylib::my_linear”。该名称用作操作在 PyTorch 子系统(例如 torch.export、FX 图)中的稳定标识符。为避免名称冲突,请使用您的项目名称作为命名空间;例如,pytorch/fbgemm 中的所有自定义操作都使用“fbgemm”作为命名空间。
mutates_args (Iterable[str] 或 "unknown") – 函数修改的参数名称。这必须准确,否则行为是未定义的。如果为“unknown”,则悲观地假定运算符的所有输入都被修改。
schema (None | str) – 运算符的模式字符串。如果为 None(推荐),我们将从其类型注释中推断出运算符的模式。除非您有特殊原因不这样做,否则我们建议让 PyTorch 推断模式。示例:“(Tensor x, int y) -> (Tensor, Tensor)”。
- 返回类型
示例
>>> import torch >>> from torch.library import triton_op, wrap_triton >>> >>> import triton >>> from triton import language as tl >>> >>> @triton.jit >>> def add_kernel( >>> in_ptr0, >>> in_ptr1, >>> out_ptr, >>> n_elements, >>> BLOCK_SIZE: "tl.constexpr", >>> ): >>> pid = tl.program_id(axis=0) >>> block_start = pid * BLOCK_SIZE >>> offsets = block_start + tl.arange(0, BLOCK_SIZE) >>> mask = offsets < n_elements >>> x = tl.load(in_ptr0 + offsets, mask=mask) >>> y = tl.load(in_ptr1 + offsets, mask=mask) >>> output = x + y >>> tl.store(out_ptr + offsets, output, mask=mask) >>> >>> @triton_op("mylib::add", mutates_args={}) >>> def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: >>> output = torch.empty_like(x) >>> n_elements = output.numel() >>> >>> def grid(meta): >>> return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) >>> >>> # NB: we need to wrap the triton kernel in a call to wrap_triton >>> wrap_triton(add_kernel)[grid](x, y, output, n_elements, 16) >>> return output >>> >>> @torch.compile >>> def f(x, y): >>> return add(x, y) >>> >>> x = torch.randn(3, device="cuda") >>> y = torch.randn(3, device="cuda") >>> >>> z = f(x, y) >>> assert torch.allclose(z, x + y)
- torch.library.wrap_triton(triton_kernel, /)[源]#
允许通过 make_fx 或非严格
torch.export
将 Triton 内核捕获到图中。这些技术执行基于 Dispatcher 的跟踪(通过
__torch_dispatch__
),无法看到对原始 Triton 内核的调用。wrap_triton
API 将 Triton 内核封装到一个可调用对象中,该对象实际上可以跟踪到图中。请将此 API 与
torch.library.triton_op()
一起使用。示例
>>> import torch >>> import triton >>> from triton import language as tl >>> from torch.fx.experimental.proxy_tensor import make_fx >>> from torch.library import wrap_triton >>> >>> @triton.jit >>> def add_kernel( >>> in_ptr0, >>> in_ptr1, >>> out_ptr, >>> n_elements, >>> BLOCK_SIZE: "tl.constexpr", >>> ): >>> pid = tl.program_id(axis=0) >>> block_start = pid * BLOCK_SIZE >>> offsets = block_start + tl.arange(0, BLOCK_SIZE) >>> mask = offsets < n_elements >>> x = tl.load(in_ptr0 + offsets, mask=mask) >>> y = tl.load(in_ptr1 + offsets, mask=mask) >>> output = x + y >>> tl.store(out_ptr + offsets, output, mask=mask) >>> >>> def add(x, y): >>> output = torch.empty_like(x) >>> n_elements = output.numel() >>> >>> def grid_fn(meta): >>> return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) >>> >>> wrap_triton(add_kernel)[grid_fn](x, y, output, n_elements, 16) >>> return output >>> >>> x = torch.randn(3, device="cuda") >>> y = torch.randn(3, device="cuda") >>> gm = make_fx(add)(x, y) >>> print(gm.code) >>> # def forward(self, x_1, y_1): >>> # empty_like = torch.ops.aten.empty_like.default(x_1, pin_memory = False) >>> # triton_kernel_wrapper_mutation_proxy = triton_kernel_wrapper_mutation( >>> # kernel_idx = 0, constant_args_idx = 0, >>> # grid = [(1, 1, 1)], kwargs = { >>> # 'in_ptr0': x_1, 'in_ptr1': y_1, 'out_ptr': empty_like, >>> # 'n_elements': 3, 'BLOCK_SIZE': 16 >>> # }) >>> # return empty_like
- 返回类型
扩展自定义操作(由 Python 或 C++ 创建)#
使用 register.* 方法,例如 torch.library.register_kernel()
和 torch.library.register_fake()
,为任何运算符添加实现(它们可能已使用 torch.library.custom_op()
或通过 PyTorch 的 C++ 运算符注册 API 创建)。
- torch.library.register_kernel(op, device_types, func=None, /, *, lib=None)[源]#
为该运算符的设备类型注册一个实现。
一些有效的设备类型包括:“cpu”、“cuda”、“xla”、“mps”、“ipu”、“xpu”。此 API 可用作装饰器。
- 参数
- 示例:
>>> import torch >>> from torch import Tensor >>> from torch.library import custom_op >>> import numpy as np >>> >>> # Create a custom op that works on cpu >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu") >>> def numpy_sin(x: Tensor) -> Tensor: >>> x_np = x.numpy() >>> y_np = np.sin(x_np) >>> return torch.from_numpy(y_np) >>> >>> # Add implementations for the cuda device >>> @torch.library.register_kernel("mylib::numpy_sin", "cuda") >>> def _(x): >>> x_np = x.cpu().numpy() >>> y_np = np.sin(x_np) >>> return torch.from_numpy(y_np).to(device=x.device) >>> >>> x_cpu = torch.randn(3) >>> x_cuda = x_cpu.cuda() >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin()) >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin())
- torch.library.register_autocast(op, device_type, cast_inputs, /, *, lib=None)[源]#
为此自定义操作注册一个自动混合精度调度规则。
有效的 device_type 包括:“cpu”和“cuda”。
- 参数
op (str | OpOverload) – 要注册自动混合精度调度规则的运算符。
device_type (str) – 要使用的设备类型。“cuda”或“cpu”。该类型与
torch.device
的 type 属性相同。因此,您可以使用 Tensor.device.type 获取张量的设备类型。cast_inputs (
torch.dtype
) – 当自定义操作在自动混合精度启用区域中运行时,将传入的浮点张量转换为目标 dtype(非浮点张量不受影响),然后禁用自动混合精度执行自定义操作。lib (Optional[Library]) – 如果提供,此注册的生命周期
- 示例:
>>> import torch >>> from torch import Tensor >>> from torch.library import custom_op >>> >>> # Create a custom op that works on cuda >>> @torch.library.custom_op("mylib::my_sin", mutates_args=()) >>> def my_sin(x: Tensor) -> Tensor: >>> return torch.sin(x) >>> >>> # Register autocast dispatch rule for the cuda device >>> torch.library.register_autocast("mylib::my_sin", "cuda", torch.float16) >>> >>> x = torch.randn(3, dtype=torch.float32, device="cuda") >>> with torch.autocast("cuda", dtype=torch.float16): >>> y = torch.ops.mylib.my_sin(x) >>> assert y.dtype == torch.float16
- torch.library.register_autograd(op, backward, /, *, setup_context=None, lib=None)[源]#
为此自定义操作注册一个反向公式。
为了使运算符与自动梯度配合使用,您需要注册一个反向公式:1. 您必须通过提供“backward”函数来告诉我们如何在反向传播期间计算梯度。2. 如果您需要前向传播中的任何值来计算梯度,您可以使用 setup_context 来保存反向传播所需的值。
backward
在反向传播期间运行。它接受(ctx, *grads)
:-grads
是一个或多个梯度。梯度的数量与运算符的输出数量匹配。ctx
对象是 与上下文方法混合使用的 ctx 对象,由torch.autograd.Function
使用。backward_fn
的语义与torch.autograd.Function.backward()
相同。setup_context(ctx, inputs, output)
在前向传播期间运行。请通过torch.autograd.function.FunctionCtx.save_for_backward()
或将其作为ctx
的属性赋值来保存反向传播所需的值。如果您的自定义操作具有仅限 kwarg 的参数,我们希望setup_context
的签名是setup_context(ctx, inputs, keyword_only_inputs, output)
。setup_context_fn
和backward_fn
都必须是可跟踪的。也就是说,它们不能直接访问torch.Tensor.data_ptr()
,并且它们不能依赖或改变全局状态。如果您需要不可跟踪的反向传播,您可以将其作为单独的 custom_op,在backward_fn
中调用。如果您需要在不同设备上进行不同的自动梯度行为,我们建议创建两个不同的自定义运算符,每个需要不同行为的设备一个,并在运行时在它们之间切换。
示例
>>> import torch >>> import numpy as np >>> from torch import Tensor >>> >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=()) >>> def numpy_sin(x: Tensor) -> Tensor: >>> x_np = x.cpu().numpy() >>> y_np = np.sin(x_np) >>> return torch.from_numpy(y_np).to(device=x.device) >>> >>> def setup_context(ctx, inputs, output) -> Tensor: >>> x, = inputs >>> ctx.save_for_backward(x) >>> >>> def backward(ctx, grad): >>> x, = ctx.saved_tensors >>> return grad * x.cos() >>> >>> torch.library.register_autograd( ... "mylib::numpy_sin", backward, setup_context=setup_context ... ) >>> >>> x = torch.randn(3, requires_grad=True) >>> y = numpy_sin(x) >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) >>> assert torch.allclose(grad_x, x.cos()) >>> >>> # Example with a keyword-only arg >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor: >>> x_np = x.cpu().numpy() >>> y_np = x_np * val >>> return torch.from_numpy(y_np).to(device=x.device) >>> >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor: >>> ctx.val = keyword_only_inputs["val"] >>> >>> def backward(ctx, grad): >>> return grad * ctx.val >>> >>> torch.library.register_autograd( ... "mylib::numpy_mul", backward, setup_context=setup_context ... ) >>> >>> x = torch.randn(3, requires_grad=True) >>> y = numpy_mul(x, val=3.14) >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14))
- torch.library.register_fake(op, func=None, /, *, lib=None, _stacklevel=1, allow_override=False)[源]#
为该运算符注册一个 FakeTensor 实现(“假实现”)。
有时也称为“元核”、“抽象实现”。
“FakeTensor 实现”指定此运算符在不携带数据(“FakeTensor”)的张量上的行为。给定具有某些属性(大小/步幅/存储偏移/设备)的输入张量,它指定输出张量的属性是什么。
FakeTensor 实现具有与运算符相同的签名。它对 FakeTensor 和元张量都运行。要编写 FakeTensor 实现,请假定运算符的所有张量输入都是常规的 CPU/CUDA/Meta 张量,但它们没有存储,并且您正在尝试将常规的 CPU/CUDA/Meta 张量作为输出返回。FakeTensor 实现必须仅包含 PyTorch 操作(并且不得直接访问任何输入或中间张量的存储或数据)。
此 API 可用作装饰器(请参阅示例)。
有关自定义操作的详细指南,请参阅 https://pytorch.ac.cn/tutorials/advanced/custom_ops_landing_page.html
- 参数
示例
>>> import torch >>> import numpy as np >>> from torch import Tensor >>> >>> # Example 1: an operator without data-dependent output shape >>> @torch.library.custom_op("mylib::custom_linear", mutates_args=()) >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: >>> raise NotImplementedError("Implementation goes here") >>> >>> @torch.library.register_fake("mylib::custom_linear") >>> def _(x, weight, bias): >>> assert x.dim() == 2 >>> assert weight.dim() == 2 >>> assert bias.dim() == 1 >>> assert x.shape[1] == weight.shape[1] >>> assert weight.shape[0] == bias.shape[0] >>> assert x.device == weight.device >>> >>> return (x @ weight.t()) + bias >>> >>> with torch._subclasses.fake_tensor.FakeTensorMode(): >>> x = torch.randn(2, 3) >>> w = torch.randn(3, 3) >>> b = torch.randn(3) >>> y = torch.ops.mylib.custom_linear(x, w, b) >>> >>> assert y.shape == (2, 3) >>> >>> # Example 2: an operator with data-dependent output shape >>> @torch.library.custom_op("mylib::custom_nonzero", mutates_args=()) >>> def custom_nonzero(x: Tensor) -> Tensor: >>> x_np = x.numpy(force=True) >>> res = np.stack(np.nonzero(x_np), axis=1) >>> return torch.tensor(res, device=x.device) >>> >>> @torch.library.register_fake("mylib::custom_nonzero") >>> def _(x): >>> # Number of nonzero-elements is data-dependent. >>> # Since we cannot peek at the data in an fake impl, >>> # we use the ctx object to construct a new symint that >>> # represents the data-dependent size. >>> ctx = torch.library.get_ctx() >>> nnz = ctx.new_dynamic_size() >>> shape = [nnz, x.dim()] >>> result = x.new_empty(shape, dtype=torch.int64) >>> return result >>> >>> from torch.fx.experimental.proxy_tensor import make_fx >>> >>> x = torch.tensor([0, 1, 2, 3, 4, 0]) >>> trace = make_fx(torch.ops.mylib.custom_nonzero, tracing_mode="symbolic")(x) >>> trace.print_readable() >>> >>> assert torch.allclose(trace(x), torch.ops.mylib.custom_nonzero(x))
- torch.library.register_vmap(op, func=None, /, *, lib=None)[源]#
为此自定义操作注册一个 vmap 实现,以支持
torch.vmap()
。此 API 可用作装饰器(请参阅示例)。
为了使运算符与
torch.vmap()
配合使用,您可能需要注册一个具有以下签名的 vmap 实现vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)
,其中
*args
和**kwargs
是op
的参数和关键字参数。我们不支持仅限 kwarg 的 Tensor 参数。它指定了如何根据具有额外维度(由
in_dims
指定)的输入来计算op
的批处理版本。对于
args
中的每个参数,in_dims
都有一个对应的Optional[int]
。如果参数不是 Tensor 或参数未进行 vmap 处理,则为None
,否则它是一个整数,指定 Tensor 的哪个维度正在进行 vmap 处理。info
是一个额外的元数据集合,可能很有用:info.batch_size
指定正在进行 vmap 处理的维度的大小,而info.randomness
是传递给torch.vmap()
的randomness
选项。函数
func
的返回是一个(output, out_dims)
元组。与in_dims
类似,out_dims
应该与output
具有相同的结构,并且每个输出包含一个out_dim
,指定输出是否具有 vmap 维度以及它在哪个索引。示例
>>> import torch >>> import numpy as np >>> from torch import Tensor >>> from typing import Tuple >>> >>> def to_numpy(tensor): >>> return tensor.cpu().numpy() >>> >>> lib = torch.library.Library("mylib", "FRAGMENT") >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=()) >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]: >>> x_np = to_numpy(x) >>> dx = torch.tensor(3 * x_np ** 2, device=x.device) >>> return torch.tensor(x_np ** 3, device=x.device), dx >>> >>> def numpy_cube_vmap(info, in_dims, x): >>> result = numpy_cube(x) >>> return result, (in_dims[0], in_dims[0]) >>> >>> torch.library.register_vmap(numpy_cube, numpy_cube_vmap) >>> >>> x = torch.randn(3) >>> torch.vmap(numpy_cube)(x) >>> >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor: >>> return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device) >>> >>> @torch.library.register_vmap("mylib::numpy_mul") >>> def numpy_mul_vmap(info, in_dims, x, y): >>> x_bdim, y_bdim = in_dims >>> x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1) >>> y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1) >>> result = x * y >>> result = result.movedim(-1, 0) >>> return result, 0 >>> >>> >>> x = torch.randn(3) >>> y = torch.randn(3) >>> torch.vmap(numpy_mul)(x, y)
注意
vmap 函数应旨在保留整个自定义操作的语义。也就是说,
grad(vmap(op))
应该可以用grad(map(op))
替换。如果您的自定义运算符在反向传播中具有任何自定义行为,请记住这一点。
- torch.library.impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1)[源]#
此 API 在 PyTorch 2.4 中已重命名为
torch.library.register_fake()
。请改用它。
- torch.library.get_ctx()[源]#
get_ctx() 返回当前的 AbstractImplCtx 对象。
调用
get_ctx()
仅在假实现内部有效(有关更多使用详细信息,请参阅torch.library.register_fake()
)。- 返回类型
FakeImplCtx
- torch.library.register_torch_dispatch(op, torch_dispatch_class, func=None, /, *, lib=None)[源]#
为给定运算符和
torch_dispatch_class
注册一个 torch_dispatch 规则。这允许开放注册来指定运算符和
torch_dispatch_class
之间的行为,而无需直接修改torch_dispatch_class
或运算符。torch_dispatch_class
是一个带有__torch_dispatch__
的 Tensor 子类或一个 TorchDispatchMode。如果它是 Tensor 子类,我们期望
func
具有以下签名:(cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any
如果它是 TorchDispatchMode,我们期望
func
具有以下签名:(mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any
args
和kwargs
将以与__torch_dispatch__
相同的方式规范化(请参阅 __torch_dispatch__ 调用约定)。示例
>>> import torch >>> >>> @torch.library.custom_op("mylib::foo", mutates_args={}) >>> def foo(x: torch.Tensor) -> torch.Tensor: >>> return x.clone() >>> >>> class MyMode(torch.utils._python_dispatch.TorchDispatchMode): >>> def __torch_dispatch__(self, func, types, args=(), kwargs=None): >>> return func(*args, **kwargs) >>> >>> @torch.library.register_torch_dispatch("mylib::foo", MyMode) >>> def _(mode, func, types, args, kwargs): >>> x, = args >>> return x + 1 >>> >>> x = torch.randn(3) >>> y = foo(x) >>> assert torch.allclose(y, x) >>> >>> with MyMode(): >>> y = foo(x) >>> assert torch.allclose(y, x + 1)
- torch.library.infer_schema(prototype_function, /, *, mutates_args, op_name=None)[源]#
解析给定函数及其类型提示的模式。模式从函数的类型提示推断,可用于定义新运算符。
我们做出以下假设
没有一个输出是任何输入或彼此的别名。
- 没有库规范的字符串类型注释“device, dtype, Tensor, types”是假定为 torch.*。同样,没有库规范的字符串类型注释“Optional, List, Sequence, Union”假定为 typing.*。
- 只有
mutates_args
中列出的参数被修改。如果mutates_args
是“unknown”,它假定运算符的所有输入都被修改。
调用者(例如自定义操作 API)负责检查这些假设。
- 参数
- 返回
推断的模式。
- 返回类型
示例
>>> def foo_impl(x: torch.Tensor) -> torch.Tensor: >>> return x.sin() >>> >>> infer_schema(foo_impl, op_name="foo", mutates_args={}) foo(Tensor x) -> Tensor >>> >>> infer_schema(foo_impl, mutates_args={}) (Tensor x) -> Tensor
- class torch._library.custom_ops.CustomOpDef(namespace, name, schema, fn, tags=None)[源]#
CustomOpDef 是一个围绕函数的包装器,它将其转换为自定义操作。
它具有用于注册此自定义操作的其他行为的各种方法。
您不应直接实例化 CustomOpDef;相反,请使用
torch.library.custom_op()
API。- set_kernel_enabled(device_type, enabled=True)[源]#
禁用或重新启用此自定义操作已注册的内核。
如果内核已禁用/启用,则此操作为空操作。
注意
如果内核首先被禁用然后注册,则它将一直禁用,直到再次启用。
示例
>>> inp = torch.randn(1) >>> >>> # define custom op `f`. >>> @custom_op("mylib::f", mutates_args=()) >>> def f(x: Tensor) -> Tensor: >>> return torch.zeros(1) >>> >>> print(f(inp)) # tensor([0.]), default kernel >>> >>> @f.register_kernel("cpu") >>> def _(x): >>> return torch.ones(1) >>> >>> print(f(inp)) # tensor([1.]), CPU kernel >>> >>> # temporarily disable the CPU kernel >>> with f.set_kernel_enabled("cpu", enabled = False): >>> print(f(inp)) # tensor([0.]) with CPU kernel disabled
低级 API#
以下 API 是 PyTorch C++ 低级运算符注册 API 的直接绑定。
警告
低级运算符注册 API 和 PyTorch Dispatcher 是一个复杂的 PyTorch 概念。我们建议您尽可能使用上面的高级 API(不需要 torch.library.Library 对象)。这篇博客文章是了解 PyTorch Dispatcher 的一个很好的起点。
关于如何使用此 API 的一些示例教程可在 Google Colab 上找到。
- class torch.library.Library(ns, kind, dispatch_key='')[源]#
一个类,用于创建可用于从 Python 注册新运算符或覆盖现有库中运算符的库。用户可以选择传入一个调度键名,如果他们只想注册与一个特定调度键对应的内核。
要创建用于覆盖现有库中运算符的库(名称为 ns),请将 kind 设置为“IMPL”。要创建用于注册新运算符的新库(名称为 ns),请将 kind 设置为“DEF”。要创建可能现有库的片段以注册运算符(并绕过给定命名空间只有一个库的限制),请将 kind 设置为“FRAGMENT”。
- 参数
ns – 库名称
kind – “DEF”、“IMPL”、“FRAGMENT”
dispatch_key – PyTorch 调度键(默认值:“”)
- define(schema, alias_analysis='', *, tags=())[源]#
在 ns 命名空间中定义一个新运算符及其语义。
- 参数
- 返回
从模式推断的运算符名称。
示例
>>> my_lib = Library("mylib", "DEF") >>> my_lib.define("sum(Tensor self) -> Tensor")
- fallback(fn, dispatch_key='', *, with_keyset=False)[源]#
将函数实现注册为给定键的后备。
此函数仅适用于具有全局命名空间 (“_”) 的库。
- 参数
fn – 用作给定调度键的后备的函数,或者
fallthrough_kernel()
用于注册直通。dispatch_key – 输入函数应注册的调度键。默认情况下,它使用创建库时使用的调度键。
with_keyset – 控制当前调度器调用键集是否应作为第一个参数传递给
fn
的标志。这应该用于为重新调度调用创建适当的键集。
示例
>>> my_lib = Library("_", "IMPL") >>> def fallback_kernel(op, *args, **kwargs): >>> # Handle all autocast ops generically >>> # ... >>> my_lib.fallback(fallback_kernel, "Autocast")
- impl(op_name, fn, dispatch_key='', *, with_keyset=False, allow_override=False)[源]#
注册库中定义的运算符的函数实现。
- 参数
op_name – 运算符名称(连同重载)或 OpOverload 对象。
fn – 作为输入调度键的运算符实现的函数,或者
fallthrough_kernel()
用于注册直通。dispatch_key – 输入函数应注册的调度键。默认情况下,它使用创建库时使用的调度键。
with_keyset – 控制当前调度器调用键集是否应作为第一个参数传递给
fn
的标志。这应该用于为重新调度调用创建适当的键集。allow_override – 控制是否要覆盖现有注册内核实现的标志。这默认关闭,如果您尝试向已注册内核的调度键注册内核,则会出错。
示例
>>> my_lib = Library("aten", "IMPL") >>> def div_cpu(self, other): >>> return self * (1 / other) >>> my_lib.impl("div.Tensor", div_cpu, "CPU")
- torch.library.define(qualname, schema, *, lib=None, tags=())[源]#
- torch.library.define(lib, schema, alias_analysis='')
定义一个新运算符。
在 PyTorch 中,定义一个操作(“operator”的简称)是一个两步过程:- 我们需要定义操作(通过提供操作名称和模式)- 我们需要为操作如何与各种 PyTorch 子系统(如 CPU/CUDA 张量、Autograd 等)交互实现行为。
此入口点定义了自定义操作(第一步),然后您必须通过调用各种
impl_*
API 来执行第二步,例如torch.library.impl()
或torch.library.register_fake()
。- 参数
qualname (str) – 运算符的限定名称。应为“namespace::name”形式的字符串,例如“aten::sin”。PyTorch 中的运算符需要命名空间以避免名称冲突;给定运算符只能创建一次。如果您正在编写 Python 库,我们建议命名空间为您的顶级模块的名称。
schema (str) – 运算符的模式。例如,接受一个 Tensor 并返回一个 Tensor 的操作的模式为“(Tensor x) -> Tensor”。它不包含运算符名称(该名称在
qualname
中传递)。lib (Optional[Library]) – 如果提供,此运算符的生命周期将与 Library 对象的生命周期绑定。
tags (Tag | Sequence[Tag]) – 要应用于此运算符的一个或多个 torch.Tag。标记运算符会改变运算符在各种 PyTorch 子系统下的行为;请在应用前仔细阅读 torch.Tag 的文档。
- 示例:
>>> import torch >>> import numpy as np >>> >>> # Define the operator >>> torch.library.define("mylib::sin", "(Tensor x) -> Tensor") >>> >>> # Add implementations for the operator >>> @torch.library.impl("mylib::sin", "cpu") >>> def f(x): >>> return torch.from_numpy(np.sin(x.numpy())) >>> >>> # Call the new operator from torch.ops. >>> x = torch.randn(3) >>> y = torch.ops.mylib.sin(x) >>> assert torch.allclose(y, x.sin())
- torch.library.impl(lib, name, dispatch_key='')[源]#
- torch.library.impl(qualname: str, types: Union[str, Sequence[str]], func: Literal[None] = None, *, lib: Optional[Library] = None) Callable[[Callable[..., object]], None]
- torch.library.impl(qualname: str, types: Union[str, Sequence[str]], func: Callable[..., object], *, lib: Optional[Library] = None) None
- torch.library.impl(lib: Library, name: str, dispatch_key: str = '') Callable[[Callable[_P, _T]], Callable[_P, _T]]
为该运算符的设备类型注册一个实现。
您可以为
types
传递“default”以将此实现注册为所有设备类型的默认实现。请仅在实现真正支持所有设备类型时才使用此选项;例如,如果它是由内置 PyTorch 运算符组成的,则为真。此 API 可用作装饰器。您可以将嵌套装饰器与此 API 一起使用,前提是它们返回函数并放置在此 API 内部(参见示例 2)。
一些有效的类型是:“cpu”、“cuda”、“xla”、“mps”、“ipu”、“xpu”。
- 参数
示例
>>> import torch >>> import numpy as np >>> # Example 1: Register function. >>> # Define the operator >>> torch.library.define("mylib::mysin", "(Tensor x) -> Tensor") >>> >>> # Add implementations for the cpu device >>> @torch.library.impl("mylib::mysin", "cpu") >>> def f(x): >>> return torch.from_numpy(np.sin(x.numpy())) >>> >>> x = torch.randn(3) >>> y = torch.ops.mylib.mysin(x) >>> assert torch.allclose(y, x.sin()) >>> >>> # Example 2: Register function with decorator. >>> def custom_decorator(func): >>> def wrapper(*args, **kwargs): >>> return func(*args, **kwargs) + 1 >>> return wrapper >>> >>> # Define the operator >>> torch.library.define("mylib::sin_plus_one", "(Tensor x) -> Tensor") >>> >>> # Add implementations for the operator >>> @torch.library.impl("mylib::sin_plus_one", "cpu") >>> @custom_decorator >>> def f(x): >>> return torch.from_numpy(np.sin(x.numpy())) >>> >>> # Call the new operator from torch.ops. >>> x = torch.randn(3) >>> >>> y1 = torch.ops.mylib.sin_plus_one(x) >>> y2 = torch.sin(x) + 1 >>> assert torch.allclose(y1, y2)