Ubuntu18.04安装gpu版本libtorch1.3.1

2023-11-08

安装libtorch

X86平台直接下载官方编译的版本,解压后可直接用, arm平台需要下载源码编译
libtorch库的安装参考:https://pytorch.org/cppdocs/installing.html。
下载:libtorch c++

GPU版本
Libtorch1.3.1 cuda10.0
https://download.pytorch.org/libtorch/cu100/libtorch-shared-with-deps-1.3.1%2Bcu100.zip
https://download.pytorch.org/libtorch/cu100/libtorch-cxx11-abi-shared-with-deps-1.3.1%2Bcu100.zip  (使用这个链接)

unzip libtorch-cxx11-abi-shared-with-deps-1.3.1%2Bcu100.zip
解压后就可以使用

一个简单的 example-app

example-app/
  CMakeLists.txt
  example-app.cpp

example-app.cpp

#include <torch/torch.h>
#include <iostream>

int main() {
  torch::Tensor tensor = torch::rand({2, 3});
  std::cout << tensor << std::endl;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)

find_package(Torch REQUIRED)

add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 11)

编译example-app

mkdir build
cd build
cmake -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch .. //(=后面不能有空格)
cmake --build . --config Release 或者 make

libTorch调用预训练好的模型

转换一个简单的分类模型resnet18
python代码 , 将.pth模型转为.pt模型, 环境配置 torch1.3.1 libtorch1.3.1
opencv4+

demo.py

#!/usr/bin/env python
#coding:utf-8
import torch
import torchvision
from torchvision import transforms
from PIL import Image
from time import time
import numpy as np

# An instance of your model.
model = torchvision.models.resnet18(pretrained=False)
#将模型提前下载下来, 直接加载
state_dict = torch.load('./resnet18-5c106cde.pth') 
model.load_state_dict(state_dict)
model.eval()

# 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("model.pt")

# evalute time
batch = torch.rand(64, 3, 224, 224)
start = time()
output = traced_script_module(batch)
stop = time()
print(str(stop-start) + "s")

# read image
image = Image.open('cat.jpg').convert('RGB')
default_transform = transforms.Compose([
        transforms.Resize([224, 224]),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
      ])
image = default_transform(image)

# forward
output = traced_script_module(image.unsqueeze(0))
print(output[0, :10])

# print top-5 predicted labels
labels = np.loadtxt('synset_words.txt', dtype=str, delimiter='\n')

data_out = output[0].data.numpy()
sorted_idxs = np.argsort(-data_out)

for i,idx in enumerate(sorted_idxs[:5]):
  print('top-%d label: %s, score: %f' % (i, labels[idx], data_out[idx]))

将.pt模型用c++调用

example-app.cpp

#include "torch/script.h"
#include "torch/torch.h" 
//#include "torch/Tensor.h" 
#include "opencv2/opencv.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/types_c.h"

#include <iostream>
#include <memory>
#include <string>
#include <vector>

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

  // Deserialize the ScriptModule from a file using torch::jit::load().
  //std::shared_ptr<torch::jit::script::Module> module = torch::jit::load(argv[1]);
  torch::jit::script::Module module = torch::jit::load(argv[1]);

  //assert(module != nullptr);
  std::cout << "load model ok\n";

  // Create a vector of inputs.
  std::vector<torch::jit::IValue> inputs;
  inputs.push_back(torch::rand({64, 3, 224, 224}));

  // evalute time
  double t = (double)cv::getTickCount();
  module.forward(inputs).toTensor();
  t = (double)cv::getTickCount() - t;
  printf("execution time = %gs\n", t / cv::getTickFrequency());
  inputs.pop_back();

  // load image with opencv and transform
  cv::Mat image;
  image = cv::imread(argv[2], 1);
  cv::cvtColor(image, image, CV_BGR2RGB);
  cv::Mat img_float;
  image.convertTo(img_float, CV_32F, 1.0/255);
  cv::resize(img_float, img_float, cv::Size(224, 224));
  //std::cout << img_float.at<cv::Vec3f>(56,34)[1] << std::endl;
  //auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, {1, 224, 224, 3});

  auto img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3}); //.permute({0, 3, 1, 2}).to(torch::kCUDA);
 
  img_tensor = img_tensor.permute({0,3,1,2}); //.to(torch::kCUDA);

  img_tensor[0][0] = img_tensor[0][0].sub_(0.485).div_(0.229);
 
  img_tensor[0][1] = img_tensor[0][1].sub_(0.456).div_(0.224);
  img_tensor[0][2] = img_tensor[0][2].sub_(0.406).div_(0.225);

  //auto img_var = torch::autograd::make_variable(img_tensor, false);
  //torch::Tensor img_var = torch::autograd::make_variable(img_tensor, false);
 
  inputs.push_back(img_tensor);
  
  // Execute the model and turn its output into a tensor.
  torch::Tensor out_tensor = module.forward(inputs).toTensor();
 
  std::cout << out_tensor.slice(/*dim=*/1, /*start=*/0, /*end=*/10) << '\n';


  // Load labels
  std::string label_file = argv[3];
  std::ifstream rf(label_file.c_str());
  CHECK(rf) << "Unable to open labels file " << label_file;
  std::string line;
  std::vector<std::string> labels;
  while (std::getline(rf, line))
    labels.push_back(line);

  // print predicted top-5 labels
  std::tuple<torch::Tensor,torch::Tensor> result = out_tensor.sort(-1, true);
  torch::Tensor top_scores = std::get<0>(result)[0];
  torch::Tensor top_idxs = std::get<1>(result)[0].toType(torch::kInt32);
  
  auto top_scores_a = top_scores.accessor<float,1>();
  auto top_idxs_a = top_idxs.accessor<int,1>();

  for (int i = 0; i < 5; ++i) {
    int idx = top_idxs_a[i];
    std::cout << "top-" << i+1 << " label: ";
    std::cout << labels[idx] << ", score: " << top_scores_a[i] << std::endl;
  }

  return 0;
}


CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(custom_ops)

find_package(Torch REQUIRED)

find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )

add_executable(example-app example-app.cpp)
target_link_libraries(example-app ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_property(TARGET example-app PROPERTY CXX_STANDARD 11)

编译 与运行

mkdir build
cd build 
cmake -DCMAKE_PREFIX_PATH=/home/jonado/soft/libtorch/libtorch ..     
make
//运行
./example-app ../model.pt ../dog.png ../synset_words.txt 

…/model.pt 为运行demo.py程序生成的
…/dog.png 任意一张图片
…/synset_words.txt 是googlenet的synset_words.txt为分类标签, 可以在github搜索下载, 里面放的是1000个类的名称

以下为遇到的相关错误及处理:

fatal error: torch/Tensor.h: 没有那个文件或目录
屏蔽该行
//#include <torch/Tensor.h>

std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("../xxx.pt");
	修改为:
torch::jit::script::Module module = torch::jit::load("../xxx.pt");

现在的Module已经不是指针,这个断言没有存在的必要了,删掉就行
	assert(module != nullptr);
torch::Tensor output = module->forward(std::move(inputs)).toTensor();
	修改为
torch::Tensor output = module.forward(std::move(inputs)).toTensor();
	
error:class at::DeprecatedTypeProperties’ has no member named ‘tensorFromBlob’
   auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, {1, 224, 224, 3});

错误代码:
	auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, { 1, input_image_size, input_image_size, 3 });
原因:libtorch 1.1的接口改了,
正确代码:
	auto img_tensor = torch::from_blob(image.data, {1, inp_dim[0], inp_dim[1], 3}).permute({0, 3, 1, 2}).to(torch::kCUDA);
	
terminate called after throwing an instance of 'c10::Error' 
  what():  Must not create a new variable from a variable, use its .tensor_data() (make_variable at /home/jonado/soft/libtorch/libtorch/include/torch/csrc/autograd/variable.h:545)
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x6a (0x7fecf0a1dc4a in /home/jonado/soft/libtorch/libtorch/lib/libc10.so)
frame #1: torch::autograd::make_variable(at::Tensor, bool, bool) + 0x10c (0x5575108ced11 in ./example-app)
frame #2: main + 0xa76 (0x5575108c64aa in ./example-app)
frame #3: __libc_start_main + 0xe7 (0x7fecee847b97 in /lib/x86_64-linux-gnu/libc.so.6)
frame #4: _start + 0x2a (0x5575108c43aa in ./example-app)

定位错误代码行: auto img_var = torch::autograd::make_variable(img_tensor, false);
img_tensor已经是tensor类型数据了, 删掉这一行, 直接把img_tensor放入到inputs容器 inputs.push_back(img_tensor);

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ubuntu18.04安装gpu版本libtorch1.3.1 的相关文章

随机推荐

  • LVS 之 集群搭建

    官网地址 http www linuxvirtualserver org zh lvs1 html 首先 准备4台虚拟机 一个用于客户端 一个用于LVS 调度器 2个用于后端服务器 LVS NAT配置 1 zk02 开启内核的核心转发功能
  • 在Python中使用StanfordOpenIE

    本文在 维基百科数据预处理的基础上进行 1 StanfordOpenIE简介 开放信息提取 open IE 是指从纯文本中提取关系元组 通常是二元关系 例如 Mark Zuckerberg 脸书 与其他信息提取的核心区别在于 这些关系的模式
  • mysql配置和使用中可能会出现的若干问题

    Manually delete the data folder created by yourself 删除自行创建的data文件夹 Then enter the bin directory under the administrator
  • QT应用开发基础

    目录 前言 Windows上搭建开发环境 C 基础 什么是C 什么是面向对象 什么又是面向过程 c 的灵魂 c 的类 对象 类的实例化 怎么访问类的成员 类的函数成员 类的访问修饰符 函数的重载 构造函数和析构函数 类的继承 虚函数和纯虚函
  • Android Studio 的NotePad制作(日志本)

    自己写的NotePad 一个星期左右的时间 完成了最基本的功能 但是 界面还是一如既往的shi 因为百度找的图标都不是那种成套的 想找的找不到 干脆下次自己画 NotePad的功能无非是对日志的增删改查 这次还加入了Preference的一
  • java零基础从入门到精通(全)

    目录 前言 1 入门知识 1 1 JDK JRE JVM区别 1 2 编译与运行理解 1 3 类体函数细节 2 语法 2 1 标识符与关键字 2 2 变量与数据类型 2 3 控制语句 3 方法 3 1 定义 3 2 方法重载 3 3 方法递
  • electron开发环境搭建

    开发环境 Node js Vscode vscode安装Debugger for Chrome 创建开发目录 也是解决方案 执行初始化命令 创建electronpicture工程 并添加main js和index html文件 npm in
  • 存储器容量、位宽及其地址线根数三者之间的关系

    转载于 http blog sina com cn s blog 498dc96f0100gc2r html 1 存储器 Flash ROM SST39VF1601 数据位宽为16位 16根数据线 20根地址线 2M 1M 16bit SD
  • PID算法(一)PID简介

    PID算法简介及实现代码 PID简介 智能车比赛中 用到了PID算法 写下来当一个总结 PID是很经典且应用很广泛的控制算法 依据误差来减少误差 PID PID分为三部分 P 比例 P增大 可以加快系统响应速度 但是不能从根本上消除静态误差
  • 搭建ChatGPT对话式小说

    牙叔教程 简单易懂 你只需要写一个开头 剩下的交给ChatGPT 视频查看效果 两个ChatGPT互聊 写小说 哔哩哔哩 bilibili 这是一种ChatGPT的展现方式 他把你主动问ChatGPT的这种方式 改为了ChatGPT和Cha
  • 双指针算法(acwing)疑难讲解

    相信大家都是看完y总的课来看博客解惑的我会在这里分享一些我理解的细节 回顾一下题目 直接上代码 include
  • VUE element-ui之百度OCR证件识别,组件内证件照转码解码识别身份证照文字

    步骤 接上一篇博文继续完善获取access token 封装Base64照片转码方法 const identification 将图片转为base64格式 transformBase64 file return new Promise re
  • 毕业设计-基于 MATLAB 的小波去噪的研究

    目录 前言 课题背景和意义 实现技术思路 一 小波理论 二 小波去噪原理 三 去噪实验仿真 实现效果图样例 最后 前言 大四是整个大学期间最忙碌的时光 一边要忙着备考或实习为毕业后面临的就业升学做准备 一边要为毕业设计耗费大量精力 近几年各
  • 表的内连接、外连接(左连接与右连接)

    内连接 利用内连接可获取两表的公共部分的记录 语句如下 Select from A JOIN B ON A Aid B Bid 外连接 外连接分为两种 一种是左连接 Left JOIN 和右连接 Right JOIN 1 左连接 Left
  • latex公式对齐方式详解

    符号和 控制公式左对齐 对齐结果如下 begin array 控制公式对齐 begin array 是什么 begin array 是LaTeX中用于创建数学数组 math array 的环境 它可以用于在数学模式下创建一个由多行多列组成的
  • golang web开发

    目录 文章目录 前言 一 golang web是什么 二 搭建流程 1 模块划分 2 详细开发步骤 总结 前言 例如 习惯了java springboot 开发方式 比较疑惑golang web开发的流程和模块化的区分 就golang we
  • 2023最新大数据毕业设计项目推荐

    文章目录 0 前言 1 如何选题 1 1 选题技巧 如何避坑 重中之重 1 2 为什么这么说呢 1 3 难度把控 1 4 题目名称 1 5 最后 2 大数据 选题推荐 2 1 大数据挖掘类 2 2 大数据处理 云计算 区块链 毕设选题 2
  • 微信小程序开发,小程序类目符合,线上版本无权限申请wx.getLocation接口

    我开发 的小程序类目符合wx getLocation接口的申请标准 但是却还是显示无权限申请 后来研究好久才发现 小程序需要在发布线上版本时提交用户隐私保护指引 如未设置也可以在 设置 服务内容声明 用户隐私保护指引 声明处理用户信息项并补
  • 电源芯片MP1584,LM2596,XL1509性能对比

    MP1584耐压只有28V 标称3A输出电流 实测2A发热但是没有问题 再大了发热太严重 估计2A以内放心用 29V输入加上负载芯片就坏了 得益于它的高频开关优势 电感尺寸可以小一点 空载时电流很小 只有0 37mA 空载或轻负载时候 输出
  • Ubuntu18.04安装gpu版本libtorch1.3.1

    安装libtorch X86平台直接下载官方编译的版本 解压后可直接用 arm平台需要下载源码编译 libtorch库的安装参考 https pytorch org cppdocs installing html 下载 libtorch c