创建一个TorchScript模块¶
TorchScript 是一种从 PyTorch 代码创建可序列化和可优化模型的方法。 PyTorch 提供了详细的文档,介绍如何做到这一点 https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html,但简而言之,以下是关键背景信息和过程:
PyTorch 程序基于 Module,可以用来组合更高级别的模块。Modules 包含一个构造函数来设置模块、参数和子模块,以及一个前向函数,描述在调用模块时如何使用参数和子模块。
例如,我们可以这样定义一个LeNet模块:
1import torch.nn as nn
2import torch.nn.functional as F
3
4
5class LeNetFeatExtractor(nn.Module):
6 def __init__(self):
7 super(LeNetFeatExtractor, self).__init__()
8 self.conv1 = nn.Conv2d(1, 6, 3)
9 self.conv2 = nn.Conv2d(6, 16, 3)
10
11 def forward(self, x):
12 x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
13 x = F.max_pool2d(F.relu(self.conv2(x)), 2)
14 return x
15
16
17class LeNetClassifier(nn.Module):
18 def __init__(self):
19 super(LeNetClassifier, self).__init__()
20 self.fc1 = nn.Linear(16 * 6 * 6, 120)
21 self.fc2 = nn.Linear(120, 84)
22 self.fc3 = nn.Linear(84, 10)
23
24 def forward(self, x):
25 x = torch.flatten(x, 1)
26 x = F.relu(self.fc1(x))
27 x = F.relu(self.fc2(x))
28 x = self.fc3(x)
29 return x
30
31
32class LeNet(nn.Module):
33 def __init__(self):
34 super(LeNet, self).__init__()
35 self.feat = LeNetFeatExtractor()
36 self.classifier = LeNetClassifier()
37
38 def forward(self, x):
39 x = self.feat(x)
40 x = self.classifier(x)
41 return x
.
显然,你可能希望将这样一个简单的模型整合到一个单一的模块中,但我们可以看到PyTorch的可组合性在这里
从这里开始,有两种途径可以从PyTorch Python代码转换为TorchScript代码:追踪和脚本化。
跟踪功能在模块被调用时跟随执行路径并记录发生的情况。
要跟踪我们的LeNet模块的一个实例,我们可以使用一个示例输入调用torch.jit.trace。
import torch
model = LeNet()
input_data = torch.empty([1, 1, 32, 32])
traced_model = torch.jit.trace(model, input_data)
脚本实际上使用编译器检查您的代码,并生成一个等效的TorchScript程序。不同之处在于,由于跟踪是跟随模块的执行,它无法捕捉控制流等。通过从Python代码工作,编译器可以包含这些组件。我们可以通过调用torch.jit.script在我们的LeNet模块上运行脚本编译器。
import torch
model = LeNet()
script_model = torch.jit.script(model)
有理由选择一种路径或另一种路径,PyTorch 文档中有关于如何选择的信息。从 Torch-TensorRT 的角度来看,对于跟踪模块有更好的支持(即您的模块更有可能编译),因为它不包含完整编程语言的所有复杂性,尽管两种路径都支持。
在编写或跟踪您的模块后,您将获得一个TorchScript模块。这包含了用于运行模块的代码和参数,这些代码和参数存储在Torch-TensorRT可以使用的中间表示中。
以下是LeNet跟踪模块IR的样子:
graph(%self.1 : __torch__.___torch_mangle_10.LeNet,
%input.1 : Float(1, 1, 32, 32)):
%129 : __torch__.___torch_mangle_9.LeNetClassifier = prim::GetAttr[name="classifier"](%self.1)
%119 : __torch__.___torch_mangle_5.LeNetFeatExtractor = prim::GetAttr[name="feat"](%self.1)
%137 : Tensor = prim::CallMethod[name="forward"](%119, %input.1)
%138 : Tensor = prim::CallMethod[name="forward"](%129, %137)
return (%138)
以及LeNet脚本化模块的IR:
graph(%self : __torch__.LeNet,
%x.1 : Tensor):
%2 : __torch__.LeNetFeatExtractor = prim::GetAttr[name="feat"](%self)
%x.3 : Tensor = prim::CallMethod[name="forward"](%2, %x.1) # x.py:38:12
%5 : __torch__.LeNetClassifier = prim::GetAttr[name="classifier"](%self)
%x.5 : Tensor = prim::CallMethod[name="forward"](%5, %x.3) # x.py:39:12
return (%x.5)
你可以看到IR保留了我们在Python代码中的模块结构。
在Python中使用TorchScript¶
TorchScript 模块的运行方式与普通 PyTorch 模块相同。您可以使用 forward 方法运行前向传播,或者直接调用模块 torch_script_module(in_tensor)。JIT 编译器将即时编译并优化模块,然后返回结果。
将TorchScript模块保存到磁盘¶
对于追踪或脚本化的模块,您可以使用以下命令将模块保存到磁盘
import torch
model = LeNet()
script_model = torch.jit.script(model)
script_model.save("lenet_scripted.ts")