Libtorch初试教程《一》

下载libtorch的包

这里下载的是cpu版本
Download here (Pre-cxx11 ABI):
https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-1.4.0%2Bcpu.zip

Download here (cxx11 ABI):
https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.4.0%2Bcpu.zip

也可以下载gpu版本(cuda10.1):

Download here (Pre-cxx11 ABI):
https://download.pytorch.org/libtorch/cu101/libtorch-shared-with-deps-1.4.0.zip

Download here (cxx11 ABI):
https://download.pytorch.org/libtorch/cu101/libtorch-cxx11-abi-shared-with-deps-1.4.0.zip

转换模型

先使用torchvision自带的resnet小试一下:

import torch
import torchvision

# An instance of your model.
model = torchvision.models.resnet18(pretrained=True)

# An example input you would normally provide to your model's forward() method.
example = torch.rand(1, 3, 224, 224)

# Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save("traced_resnet18_model.pt")
In[1]: output = traced_script_module(torch.ones(1, 3, 224, 224))
In[2]: output[0, :5]
Out[2]: tensor([-0.2698, -0.0381,  0.4023, -0.3010, -0.0448], grad_fn=<SliceBackward>)

在C ++中加载

  1. 使用C++编译器(CLion)新建一个工程libtorch_test1
  2. 解压libtorch-shared-with-deps-1.4.0+cpu.zip,把里面的libtorch文件夹复制到工程目录中
  3. 修改main.cpp 如下:
#include <torch/script.h> // One-stop header.

#include <iostream>
#include <memory>

int main(int argc, const char* argv[]) {
    if (argc != 2) {
        std::cerr << "usage: example-app <path-to-exported-script-module>\n";
        return -1;
    }


    torch::jit::script::Module module;
    try {
        // Deserialize the ScriptModule from a file using torch::jit::load().
        module = torch::jit::load(argv[1]);
    }
    catch (const c10::Error& e) {
        std::cerr << "error loading the model\n";
        return -1;
    }

    std::cout << "ok\n";
}
  1. 修改Cmakelists.txt如下:
cmake_minimum_required(VERSION 3.15)
project(libtorch_test1)

list(APPEND CMAKE_PREFIX_PATH "。/libtorch")

find_package(Torch REQUIRED)

set(CMAKE_CXX_STANDARD 14)

add_executable(libtorch_test1 main.cpp)

target_link_libraries(libtorch_test1 "${TORCH_LIBRARIES}")
set_property(TARGET libtorch_test1 PROPERTY CXX_STANDARD 14)

  1. 编译
mkdir build
cd build 
cmake ..
make 
  1. 把转换后的模型traced_resnet18_model.pt 复制过来,执行
    ./libtorch_test1 traced_resnet18_model.pt
    将会打印出 OK 即为成功。
  2. 在代码中添加vector输入,修改后的main.cpp 如下:
#include <torch/script.h> // One-stop header.

#include <iostream>
#include <memory>

int main(int argc, const char* argv[]) {
    if (argc != 2) {
        std::cerr << "usage: example-app <path-to-exported-script-module>\n";
        return -1;
    }


    torch::jit::script::Module module;
    try {
        // Deserialize the ScriptModule from a file using torch::jit::load().
        module = torch::jit::load(argv[1]);
    }
    catch (const c10::Error& e) {
        std::cerr << "error loading the model\n";
        return -1;
    }
    // Create a vector of inputs.
	std::vector<torch::jit::IValue> inputs;
	inputs.push_back(torch::ones({1, 3, 224, 224}));
	
	// Execute the model and turn its output into a tensor.
	at::Tensor output = module.forward(inputs).toTensor();
	std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n';

    std::cout << "ok\n";
}
  1. 重新编译,执行
root@4b5a67132e81:/example-app/build# make
Scanning dependencies of target example-app
[ 50%] Building CXX object CMakeFiles/example-app.dir/example-app.cpp.o
[100%] Linking CXX executable example-app
[100%] Built target example-app
root@4b5a67132e81:/example-app/build# ./example-app traced_resnet_model.pt
-0.2698 -0.0381  0.4023 -0.3010 -0.0448
[ Variable[CPUFloatType]{1,5} ]
  1. 成功啦

参考: https://pytorch.org/tutorials/advanced/cpp_export.html#loading-a-pytorch-model-in-c

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值