快捷方式

入门

在阅读本节内容之前,请确保阅读 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()。在急切模式下,逐元素操作效率低下,因为每个操作都需要从内存中读取一个张量,进行一些更改,然后将这些更改写回。诱导器执行的最重要的优化是融合。在上面的示例中,我们可以将 2 次读取 (x, a) 和 2 次写入 (a, b) 转换为 1 次读取 (x) 和 1 次写入 (b),这对于更新的 GPU 来说至关重要,因为瓶颈是内存带宽(将数据发送到 GPU 的速度)而不是计算(GPU 处理浮点运算的速度)。

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

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

@pointwise(size_hints=[16384], filename=__file__, triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': 0, 'constants': {}, 'mutated_arg_names': [], 'configs': [instance_descriptor(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 内核,也相当容易理解。

接下来,让我们尝试一个真正的模型,例如来自 PyTorch 集线器的 resnet50。

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 集线器下载一个预训练模型并对其进行优化

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 的工作原理有了基本了解。以下是您接下来可以查看的内容

文档

訪問 PyTorch 的全面開發者文檔

查看文檔

教程

獲取針對初學者和高級開發人員的深入教程

查看教程

資源

查找開發資源並獲得問題解答

查看資源