评价此页

入门#

创建于:2025 年 6 月 16 日 | 最后更新于:2025 年 12 月 03 日

在阅读本节之前,请务必阅读 torch.compiler

让我们从一个简单的 torch.compile 示例开始,演示如何使用 torch.compile 进行推理。这个示例演示了 torch.cos()torch.sin() 功能,它们是逐点运算符的示例,因为它们逐元素地对向量进行操作。这个示例可能不会显示显著的性能提升,但应该帮助你形成对如何使用 torch.compile 在你自己的程序中的直观理解。

注意

要运行此脚本,你的机器上至少需要一个 GPU。如果你没有 GPU,可以删除下面的代码片段中的 .to(device="cuda:0") 代码,它将在 CPU 上运行。你也可以将设备设置为 xpu:0 以在英特尔® GPU 上运行。

import torch
def fn(x):
   a = torch.cos(x)
   b = torch.sin(a)
   return b
new_fn = torch.compile(fn, backend="inductor")
input_tensor = torch.randn(10000).to(device="cuda:0")
a = new_fn(input_tensor)

你可能想要使用的另一个著名的逐点运算符是像 torch.relu() 这样的运算符。在 eager 模式下,逐点运算符效率低下,因为每个运算符都需要从内存读取一个张量,进行一些更改,然后将这些更改写回。inductor 执行的最重要的优化是融合。在上面的示例中,我们可以将 2 次读取 (x, a) 和 2 次写入 (a, b) 转换为 1 次读取 (x) 和 1 次写入 (b),这对于较新的 GPU 尤其重要,因为瓶颈是内存带宽(将数据发送到 GPU 的速度)而不是计算(GPU 处理浮点运算的速度)。

inductor 提供的另一个主要优化是自动支持 CUDA 图。CUDA 图有助于消除从 Python 程序启动单个内核的开销,这对于较新的 GPU 尤其重要。

TorchDynamo 支持许多不同的后端,但 TorchInductor 特别通过生成 Triton 内核来工作。让我们将上面的示例保存到一个名为 example.py 的文件中。我们可以通过运行 TORCH_COMPILE_DEBUG=1 python example.py 来检查生成的 Triton 内核代码。当脚本执行时,你应该看到打印到终端的 DEBUG 消息。在日志接近结束时,你应该会看到一个指向包含 torchinductor_<你的用户名> 的文件夹的路径。在该文件夹中,你可以找到包含生成的内核代码的 output_code.py 文件,类似于以下内容

@pointwise(size_hints=[16384], filename=__file__, triton_meta={'signature': {'in_ptr0': '*fp32', 'out_ptr0': '*fp32', 'xnumel': 'i32'}, 'device': 0, 'constants': {}, 'mutated_arg_names': [], 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]})
@triton.jit
def triton_(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr):
   xnumel = 10000
   xoffset = tl.program_id(0) * XBLOCK
   xindex = xoffset + tl.arange(0, XBLOCK)[:]
   xmask = xindex < xnumel
   x0 = xindex
   tmp0 = tl.load(in_ptr0 + (x0), xmask, other=0.0)
   tmp1 = tl.cos(tmp0)
   tmp2 = tl.sin(tmp1)
   tl.store(out_ptr0 + (x0 + tl.zeros([XBLOCK], tl.int32)), tmp2, xmask)

注意

上面的代码片段只是一个示例。根据你的硬件,你可能会看到生成的不同代码。

你可以验证 cossin 是否确实发生了融合,因为 cossin 运算发生在单个 Triton 内核内,并且临时变量存储在具有非常快访问速度的寄存器中。

阅读有关 Triton 性能的更多信息 这里。由于代码是用 Python 编写的,即使你没有编写过太多的 CUDA 内核,也相对容易理解。

接下来,让我们尝试一个像 resnet50 这样的真实模型,来自 PyTorch hub。

import torch
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True)
opt_model = torch.compile(model, backend="inductor")
opt_model(torch.randn(1,3,64,64))

这并不是唯一的可用后端,你可以在 REPL 中运行 torch.compiler.list_backends() 来查看所有可用的后端。接下来尝试 cudagraphs 以获取灵感。

使用预训练模型#

PyTorch 用户经常利用来自 transformersTIMM 的预训练模型,其中一个设计目标是 TorchDynamo 和 TorchInductor 能够开箱即用地与人们想要编写的任何模型一起工作。

让我们直接从 HuggingFace hub 下载一个预训练模型并对其进行优化

import torch
from transformers import BertTokenizer, BertModel
# Copy pasted from here https://hugging-face.cn/bert-base-uncased
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained("bert-base-uncased").to(device="cuda:0")
model = torch.compile(model, backend="inductor") # This is the only line of code that we changed
text = "Replace me by any text you'd like."
encoded_input = tokenizer(text, return_tensors='pt').to(device="cuda:0")
output = model(**encoded_input)

如果你从模型和 encoded_input 中删除了 to(device="cuda:0"),那么 Triton 将生成针对在你的 CPU 上运行进行优化的 C++ 内核。你可以检查 BERT 的 Triton 或 C++ 内核。它们比我们尝试的三角函数示例更复杂,但你可以同样地浏览它,看看你是否理解 PyTorch 的工作原理。

同样,让我们尝试一个 TIMM 示例

import timm
import torch
model = timm.create_model('resnext101_32x8d', pretrained=True, num_classes=2)
opt_model = torch.compile(model, backend="inductor")
opt_model(torch.randn(64,3,7,7))

下一步#

在本节中,我们回顾了几个推理示例,并对 torch.compile 的工作方式有了基本的了解。以下是你接下来可以查看的内容