开始使用¶
在阅读本节之前,请务必阅读 torch.compiler。
让我们从一个简单的 torch.compile
示例开始,演示如何使用 torch.compile
进行推理。此示例演示了 torch.cos()
和 torch.sin()
功能,它们是逐点算子的示例,因为它们在向量上逐元素操作。此示例可能不会显示显着的性能提升,但应帮助您直观地了解如何在您自己的程序中使用 torch.compile
。
注意
要运行此脚本,您的机器上至少需要有一个 GPU。如果您没有 GPU,您可以删除下面代码片段中的 .to(device="cuda:0")
代码,它将在 CPU 上运行。您也可以将设备设置为 xpu:0
以在 Intel® 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)
注意
上面的代码片段是一个示例。根据您的硬件,您可能会看到生成的不同代码。
您可以验证 cos
和 sin
的融合是否实际发生,因为 cos
和 sin
操作发生在单个 Triton 内核中,并且临时变量保存在具有非常快速访问速度的寄存器中。
在此处阅读更多关于 Triton 性能的信息:链接。由于代码是用 Python 编写的,因此即使您没有编写过很多 CUDA 内核,也很容易理解。
接下来,让我们尝试一个真实的模型,例如来自 PyTorch Hub 的 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 用户经常使用来自 transformers 或 TIMM 的预训练模型,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 将生成 C++ 内核,这些内核将针对在您的 CPU 上运行进行优化。您可以检查 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 的工作原理有了基本的了解。以下是您接下来可以查看的内容