• 教程 >
  • PyTorch 菜谱 >
  • 部署用的 TorchScript
快捷键

TorchScript 部署指南

创建于:2025 年 4 月 1 日 | 最后更新:2025 年 4 月 1 日 | 最后验证:2024 年 11 月 5 日

警告

TorchScript 不再处于活跃开发状态。

在本菜谱中,您将学习:

  • 什么是火炬脚本

  • 如何将训练好的模型导出为火炬脚本格式

  • 如何在 C++中加载火炬脚本模型并进行推理

需求

  • 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

让我们对两个模型的等效性进行一次 sanity check:

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 的初始展示

  • 完整的 TorchScript 文档,包括 TorchScript 语言和 API 参考


评分这个教程

© 版权所有 2024,PyTorch。

使用 Sphinx 构建,主题由 Read the Docs 提供。
//暂时添加调查链接

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源