用于部署的TorchScript¶
创建于:2020年5月4日 | 最后更新:2024年12月2日 | 最后验证:2024年11月5日
警告
TorchScript 不再处于积极开发阶段。
在本教程中,您将学习:
什么是TorchScript
如何以TorchScript格式导出您训练好的模型
如何在C++中加载您的TorchScript模型并进行推理
需求¶
PyTorch 1.5
TorchVision 0.6.0
libtorch 1.5
C++ 编译器
安装三个PyTorch组件的说明可在pytorch.org上找到。C++编译器将取决于您的平台。
什么是TorchScript?¶
TorchScript 是 PyTorch 模型的中间表示形式
(nn.Module 的子类),可以在 C++ 等高性能环境中运行。它是 Python 的一个高性能子集,
旨在由 PyTorch JIT 编译器 使用,该编译器对模型的计算进行运行时优化。TorchScript 是
使用 PyTorch 模型进行扩展推理的推荐模型格式。
有关更多信息,请参阅 PyTorch 的 TorchScript 入门教程、
在 C++ 中加载 TorchScript 模型教程 以及
完整的 TorchScript 文档,所有这些都可以在
pytorch.org 上找到。
如何导出您的模型¶
举个例子,我们来看一个预训练的视觉模型。TorchVision中的所有预训练模型都与TorchScript兼容。
运行以下Python 3代码,无论是在脚本中还是从REPL中运行:
import torch
import torch.nn.functional as F
import torchvision.models as models
r18 = models.resnet18(pretrained=True) # We now have an instance of the pretrained model
r18_scripted = torch.jit.script(r18) # *** This is the TorchScript export
dummy_input = torch.rand(1, 3, 224, 224) # We should run a quick test
让我们对两个模型的等价性进行一次健全性检查:
unscripted_output = r18(dummy_input) # Get the unscripted model's prediction...
scripted_output = r18_scripted(dummy_input) # ...and do the same for the scripted version
unscripted_top5 = F.softmax(unscripted_output, dim=1).topk(5).indices
scripted_top5 = F.softmax(scripted_output, dim=1).topk(5).indices
print('Python model top 5 results:\n {}'.format(unscripted_top5))
print('TorchScript model top 5 results:\n {}'.format(scripted_top5))
你应该看到模型的这两个版本给出了相同的结果:
Python model top 5 results:
tensor([[463, 600, 731, 899, 898]])
TorchScript model top 5 results:
tensor([[463, 600, 731, 899, 898]])
确认检查无误后,继续保存模型:
r18_scripted.save('r18_scripted.pt')
在C++中加载TorchScript模型¶
创建以下C++文件并将其命名为ts-infer.cpp:
#include <torch/script.h>
#include <torch/nn/functional/activation.h>
int main(int argc, const char* argv[]) {
if (argc != 2) {
std::cerr << "usage: ts-infer <path-to-exported-model>\n";
return -1;
}
std::cout << "Loading model...\n";
// deserialize ScriptModule
torch::jit::script::Module module;
try {
module = torch::jit::load(argv[1]);
} catch (const c10::Error& e) {
std::cerr << "Error loading model\n";
std::cerr << e.msg_without_backtrace();
return -1;
}
std::cout << "Model loaded successfully\n";
torch::NoGradGuard no_grad; // ensures that autograd is off
module.eval(); // turn off dropout and other training-time layers/functions
// create an input "image"
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::rand({1, 3, 224, 224}));
// execute model and package output as tensor
at::Tensor output = module.forward(inputs).toTensor();
namespace F = torch::nn::functional;
at::Tensor output_sm = F::softmax(output, F::SoftmaxFuncOptions(1));
std::tuple<at::Tensor, at::Tensor> top5_tensor = output_sm.topk(5);
at::Tensor top5 = std::get<1>(top5_tensor);
std::cout << top5[0] << "\n";
std::cout << "\nDONE\n";
return 0;
}
这个程序:
加载您在命令行中指定的模型
创建一个虚拟的“图像”输入张量
对输入执行推理
另外,请注意此代码中不依赖于TorchVision。 您保存的TorchScript模型版本包含您的学习权重 和您的计算图 - 不需要其他任何东西。
构建和运行您的C++推理引擎¶
创建以下 CMakeLists.txt 文件:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(custom_ops)
find_package(Torch REQUIRED)
add_executable(ts-infer ts-infer.cpp)
target_link_libraries(ts-infer "${TORCH_LIBRARIES}")
set_property(TARGET ts-infer PROPERTY CXX_STANDARD 11)
编写程序:
cmake -DCMAKE_PREFIX_PATH=<path to your libtorch installation>
make
现在,我们可以在C++中运行推理,并验证我们是否得到了结果:
$ ./ts-infer r18_scripted.pt
Loading model...
Model loaded successfully
418
845
111
892
644
[ CPULongType{5} ]
DONE
重要资源¶
pytorch.org 用于安装说明,以及更多文档和教程。
TorchScript教程介绍,深入了解TorchScript的初步内容
Full TorchScript documentation 完整的 TorchScript 语言和 API 参考