recipes/torch_compile_torch_function_modes
在 Google Colab 中运行
Colab
下载 Notebook
Notebook
在 GitHub 上查看
GitHub
注意
转到底部 下载完整的示例代码。
(beta) 将 Torch Function 模式与 torch.compile 结合使用#
作者: Michael Lazos
- 本教程介绍了如何使用一个关键的 Torch 扩展点,
Torch Function 模式,与
torch.compile结合使用,在跟踪时覆盖 Torch 算子(也称为 **ops**)的行为,且没有运行时开销。
注意
本教程要求 PyTorch 2.7.0 或更高版本。
重写一个 Torch op (torch.add -> torch.mul)#
在这个示例中,我们将使用 Torch Function 模式将加法运算替换为乘法运算。这种覆盖在某个后端为给定 op 提供了自定义实现时很常见。
import torch
# exit cleanly if we are on a device that doesn't support ``torch.compile``
if torch.cuda.get_device_capability() < (7, 0):
print("Exiting because torch.compile is not supported on this device.")
import sys
sys.exit(0)
from torch.overrides import BaseTorchFunctionMode
# Define our mode, Note: ``BaseTorchFunctionMode``
# implements the actual invocation of func(..)
class AddToMultiplyMode(BaseTorchFunctionMode):
def __torch_function__(self, func, types, args=(), kwargs=None):
if func == torch.Tensor.add:
func = torch.mul
return super().__torch_function__(func, types, args, kwargs)
@torch.compile()
def test_fn(x, y):
return x + y * x # Note: infix operators map to torch.Tensor.* methods
x = torch.rand(2, 2)
y = torch.rand_like(x)
with AddToMultiplyMode():
z = test_fn(x, y)
assert torch.allclose(z, x * y * x)
# The mode can also be used within the compiled region as well like this:
@torch.compile()
def test_fn(x, y):
with AddToMultiplyMode():
return x + y * x # Note: infix operators map to torch.Tensor.* methods
x = torch.rand(2, 2)
y = torch.rand_like(x)
z = test_fn(x, y)
assert torch.allclose(z, x * y * x)
结论#
在本教程中,我们演示了如何从 torch.compile 内部使用 Torch Function 模式来覆盖 torch.* 算子的行为。这使得用户可以在不产生每次调用 op 时调用 Torch Function 的运行时开销的情况下,利用 Torch Function 模式的扩展性优势。
有关 Torch Function 模式的其他示例和背景信息,请参阅 使用模式扩展 Torch API。
脚本总运行时间: (0 分钟 10.322 秒)