torch.library¶
torch.library 是一个 API 集合,用于扩展 PyTorch 的核心算子库。它包含用于测试自定义算子、创建新的自定义算子以及扩展使用 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)[源代码][源代码]¶
给定一个算子和一些示例参数,测试算子是否已正确注册。
也就是说,当您使用 torch.library/TORCH_LIBRARY API 创建自定义算子时,您指定了关于自定义算子的元数据(例如,可变性信息),并且这些 API 要求您传递给它们的函数满足某些属性(例如,在 fake/meta/abstract 内核中没有数据指针访问)
opcheck
测试这些元数据和属性。具体来说,我们测试以下内容
test_schema:模式是否与算子的实现匹配。例如:如果模式指定 Tensor 被修改,那么我们检查实现是否修改了 Tensor。如果模式指定我们返回一个新的 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 内核(有时也称为 meta 内核),以及它是否正确。此测试获取在真实张量上运行算子的结果和在 FakeTensor 上运行算子的结果,并检查它们是否具有相同的 Tensor 元数据(大小/步幅/dtype/设备/等)。
test_aot_dispatch_dynamic:算子在使用 PyTorch 编译 API (torch.compile/export/FX) 时是否具有正确的行为。这会检查在 eager 模式 PyTorch 和 torch.compile 下,输出(以及梯度,如果适用)是否相同。此测试是
test_faketensor
的超集,并且是 e2e 测试;它测试的其他内容包括算子是否支持函数化,以及反向传播(如果存在)是否也支持 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,我们将返回一个字典,其中包含有关每个测试是否通过的信息。
- 返回类型
警告
opcheck 和
torch.autograd.gradcheck()
测试不同的内容;opcheck 测试您对 torch.library API 的使用是否正确,而torch.autograd.gradcheck()
测试您的 autograd 公式在数学上是否正确。同时使用两者来测试支持梯度计算的自定义算子。示例
>>> @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)[源代码]¶
将函数包装到自定义算子中。
您可能想要创建自定义算子的原因包括:- 包装第三方库或自定义内核以与 Autograd 等 PyTorch 子系统一起工作。 - 防止 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”。当为不接受 Tensor 的算子注册特定于设备的实现时,我们要求该算子具有“device: torch.device argument”。
schema (None | str) – 算子的模式字符串。如果为 None(推荐),我们将从其类型注释中推断出算子的模式。我们建议让您推断模式,除非您有不这样做的特定原因。示例:“(Tensor x, int y) -> (Tensor, Tensor)”。
- 返回类型
注意
我们建议不要传入
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 内核支持。
这是使用带有 PyTorch 的 triton 内核的更结构化的方式。首选使用没有
torch.library
自定义算子包装器(如torch.library.custom_op()
,torch.library.triton_op()
)的 triton 内核,因为它更简单;仅当您想要创建行为类似于 PyTorch 内置算子的算子时,才使用torch.library.custom_op()
/torch.library.triton_op()
。例如,您可以使用torch.library
包装器 API 来定义当传递 tensor 子类或在 TorchDispatchMode 下时 triton 内核的行为。当实现由 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(推荐),我们将从其类型注释中推断出算子的模式。我们建议让您推断模式,除非您有不这样做的特定原因。示例:“(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)[源代码][源代码]¶
为此算子的设备类型注册实现。
一些有效的 device_types 是:“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_autograd(op, backward, /, *, setup_context=None, lib=None)[源代码][源代码]¶
为此自定义算子注册反向公式。
为了使算子与 autograd 一起工作,您需要注册一个反向公式:1. 您必须通过向我们提供“backward”函数来告诉我们如何在反向传播期间计算梯度。2. 如果您需要来自前向传播的任何值来计算梯度,您可以使用 setup_context 来保存值以供反向传播使用。
backward
在反向传播期间运行。它接受(ctx, *grads)
:-grads
是一个或多个梯度。梯度的数量与算子的输出数量匹配。ctx
对象是 与torch.autograd.Function
使用的相同的 ctx 对象。backward_fn
的语义与torch.autograd.Function.backward()
相同。setup_context(ctx, inputs, output)
在前向传播期间运行。请将反向传播所需的量保存在ctx
对象上,可以通过torch.autograd.function.FunctionCtx.save_for_backward()
或将其赋值为ctx
的属性来实现。如果您的自定义操作具有仅关键字参数,我们期望setup_context
的签名为setup_context(ctx, inputs, keyword_only_inputs, output)
。
和setup_context_fn
都必须是可追踪的。也就是说,它们可能无法直接访问backward_fn
torch.Tensor.data_ptr()
,并且它们不得依赖或改变全局状态。如果您需要不可追踪的反向传播,您可以将其制作成单独的 custom_op,并在
内部调用它。backward_fn
如果您需要在不同的设备上使用不同的 autograd 行为,那么我们建议创建两个不同的自定义运算符,每个设备需要不同的行为对应一个运算符,并在运行时在它们之间切换。
示例
>>> 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)[source][source]¶
为该运算符注册一个 FakeTensor 实现(“fake impl”)。
有时也称为 “meta kernel”、“abstract impl”。
“FakeTensor 实现” 指定此运算符在不携带数据的 Tensor(“FakeTensor”)上的行为。给定一些具有特定属性(大小/步幅/存储偏移/设备)的输入 Tensor,它指定输出 Tensor 的属性是什么。
FakeTensor 实现具有与运算符相同的签名。它既用于 FakeTensor 也用于元张量。要编写 FakeTensor 实现,请假定运算符的所有 Tensor 输入都是常规 CPU/CUDA/Meta 张量,但它们没有存储,并且您尝试返回常规 CPU/CUDA/Meta 张量作为输出。FakeTensor 实现必须仅包含 PyTorch 操作(并且可能无法直接访问任何输入或中间 Tensor 的存储或数据)。
此 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)[source][source]¶
注册一个 vmap 实现,以支持此自定义操作的
torch.vmap()
。此 API 可以用作装饰器(请参阅示例)。
为了使运算符与
torch.vmap()
一起工作,您可能需要在以下签名中注册一个 vmap 实现vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)
,其中
和*args
是**kwargs
的参数和 kwargs。我们不支持仅关键字 Tensor 参数。op
它指定了在给定具有附加维度(由
指定)的输入的情况下,我们如何计算in_dims
的批量版本。op
对于
中的每个 arg,args
都有一个对应的in_dims
。如果 arg 不是 Tensor,或者 arg 没有被 vmap 处理,则为Optional[int]
,否则,它是一个整数,指定 Tensor 的哪个维度正在被 vmap 处理。None
是可能有用的附加元数据的集合:info
指定被 vmap 处理的维度的大小,而info.batch_size
是传递给info.randomness
torch.vmap()
的
选项。randomness
函数
的返回值是一个func
元组。与(output, out_dims)
类似,in_dims
应与out_dims
具有相同的结构,并为每个输出包含一个output
,以指定输出是否具有 vmap 处理的维度以及它在哪个索引中。out_dim
示例
>>> 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)[source][source]¶
此 API 在 PyTorch 2.4 中已重命名为
torch.library.register_fake()
。请改用它。
- torch.library.get_ctx()[source][source]¶
get_ctx() 返回当前的 AbstractImplCtx 对象。
调用
仅在 fake impl 内部有效(有关更多用法详细信息,请参阅get_ctx()
torch.library.register_fake()
)。- 返回类型
FakeImplCtx
- torch.library.register_torch_dispatch(op, torch_dispatch_class, func=None, /, *, lib=None)[source][source]¶
为给定的运算符和
注册一个 torch_dispatch 规则。torch_dispatch_class
这允许开放注册以指定运算符和
之间的行为,而无需直接修改torch_dispatch_class
或运算符。torch_dispatch_class
要么是具有torch_dispatch_class
的 Tensor 子类,要么是 TorchDispatchMode。__torch_dispatch__
如果是 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)[source]¶
解析具有类型提示的给定函数的模式。模式是从函数的类型提示推断出来的,可用于定义新的运算符。
我们做出以下假设
没有任何输出别名任何输入或彼此别名。
- 没有库规范的字符串类型注解 “device, dtype, Tensor, types” 是假定为 torch.*。类似地,没有库规范的字符串类型注解 “Optional, List, Sequence, Union”假定为 typing.*。
- 只有
中列出的参数正在被改变。如果mutates_args
为 “unknown”,mutates_args
则假定运算符的所有输入都在被改变。
调用者(例如,自定义操作 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)[source][source]¶
CustomOpDef 是围绕函数的包装器,它将函数转换为自定义操作。
它具有用于为此自定义操作注册附加行为的各种方法。
您不应直接实例化 CustomOpDef;而是使用
torch.library.custom_op()
API。- set_kernel_enabled(device_type, enabled=True)[source][source]¶
禁用或重新启用已为此自定义运算符注册的内核。
如果内核已被禁用/启用,则此操作无效。
注意
如果内核先被禁用然后注册,则它将保持禁用状态,直到再次启用。
示例
>>> 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 对象)。这篇博客文章 <http://blog.ezyang.com/2020/09/lets-talk-about-the-pytorch-dispatcher/>`_ 是了解 PyTorch Dispatcher 的一个好的起点。
有关如何使用此 API 的一些示例的教程可在 Google Colab 上找到。
- class torch.library.Library(ns, kind, dispatch_key='')[source][source]¶
一个用于创建库的类,可用于从 Python 注册新运算符或覆盖现有库中的运算符。如果用户只想注册仅对应于一个特定调度键的内核,则可以选择传入调度键名称。
要创建库以覆盖现有库(名称为 ns)中的运算符,请将 kind 设置为 “IMPL”。要创建新库(名称为 ns)以注册新运算符,请将 kind 设置为 “DEF”。要创建可能现有库的片段以注册运算符(并绕过给定命名空间只有一个库的限制),请将 kind 设置为 “FRAGMENT”。
- 参数
ns – 库名称
kind – “DEF”、“IMPL”(默认值:“IMPL”)、“FRAGMENT”
dispatch_key – PyTorch 调度键(默认值:“”)
- define(schema, alias_analysis='', *, tags=())[source][source]¶
在 ns 命名空间中定义新的运算符及其语义。
- 参数
- 返回
从模式推断出的运算符名称。
- 示例:
>>> my_lib = Library("mylib", "DEF") >>> my_lib.define("sum(Tensor self) -> Tensor")
- fallback(fn, dispatch_key='', *, with_keyset=False)[source][source]¶
将函数实现注册为给定键的回退。
此函数仅适用于具有全局命名空间(“_”)的库。
- 参数
fn – 用作给定调度键的回退的函数,或
fallthrough_kernel()
以注册一个 fallthrough。dispatch_key – 输入函数应注册到的调度键。默认情况下,它使用创建库时使用的调度键。
with_keyset – 标志,用于控制在调用
时,是否应将当前调度程序调用 keyset 作为第一个参数传递。这应用于为重新调度调用创建适当的 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)[source][source]¶
为库中定义的运算符注册函数实现。
- 参数
op_name – 运算符名称(以及重载)或 OpOverload 对象。
fn – 作为输入调度键的运算符实现的函数,或
fallthrough_kernel()
以注册一个 fallthrough。dispatch_key – 输入函数应注册到的调度键。默认情况下,它使用创建库时使用的调度键。
with_keyset – 标志,用于控制在调用
时,是否应将当前调度程序调用 keyset 作为第一个参数传递。这应用于为重新调度调用创建适当的 keyset。fn
- 示例:
>>> 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=())[source][source]¶
- torch.library.define(lib, schema, alias_analysis='')
定义一个新的运算符。
在 PyTorch 中,定义一个 op(“运算符”的缩写)是一个两步过程:- 我们需要定义 op(通过提供运算符名称和模式)- 我们需要实现行为,以说明运算符如何与各种 PyTorch 子系统(如 CPU/CUDA Tensor、Autograd 等)交互。
此入口点定义了自定义运算符(第一步),然后您必须通过调用各种
API(如impl_*
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(qualname, types, func=None, *, lib=None)[source][source]¶
- torch.library.impl(lib, name, dispatch_key='')
为此算子的设备类型注册实现。
您可以为
传递 “default”,以将此实现注册为所有设备类型的默认实现。如果实现确实支持所有设备类型,请仅使用此选项;例如,如果它是内置 PyTorch 运算符的组合,则情况如此。types
一些有效的类型为:“cpu”、“cuda”、“xla”、“mps”、“ipu”、“xpu”。
- 参数
示例
>>> import torch >>> import numpy as np >>> >>> # 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())