Pytorch Windows C++调用(libtorch) Cmake编译 分别在python和C++中验证一致

2023-11-18

0 下载准备

具备vs2015,cmake libtorch
libtorch
https://pytorch.org/get-started/locally/
先用的release版本测试了一下,
把lib中的dll放在bin中,然后加到环境变量的path中
在这里插入图片描述

保存使用的模型

定义自己model后,使用torch.jit.trace

example=torch.rand(1,3,234,345)#尺度随意
traced_script_module = torch.jit.trace(net, example)
traced_script_module.save("model.pt")
#output = traced_script_module(data)#可以用这个验证是否结果一致

pytorch部分到此结束

1 cmake

在这里插入图片描述
CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(my_test)

find_package(Torch REQUIRED)

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


example.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;
	}

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

	assert(module != nullptr);
	std::cout << "ok";

}

进入到build 打开cmd
执行:

cmake -DCMAKE_PREFIX_PATH=I:\libtorch -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 14 Win64" ..
-- Selecting Windows SDK version  to target Windows 10.0.17134.
-- The C compiler identification is MSVC 19.0.24215.1
-- The CXX compiler identification is MSVC 19.0.24215.1
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - not found
-- Found Threads: TRUE
CMake Warning (dev) at I:/libtorch/share/cmake/Caffe2/public/utils.cmake:57 (if):
  Policy CMP0054 is not set: Only interpret if() arguments as variables or
  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
  details.  Use the cmake_policy command to set the policy and suppress this
  warning.

  Quoted variables like "MSVC" will no longer be dereferenced when the policy
  is set to NEW.  Since the policy is not set the OLD behavior will be used.
Call Stack (most recent call first):
  I:/libtorch/share/cmake/Caffe2/Caffe2Config.cmake:121 (caffe2_interface_library)
  I:/libtorch/share/cmake/Torch/TorchConfig.cmake:40 (find_package)
  CMakeLists.txt:4 (find_package)
This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) at I:/libtorch/share/cmake/Torch/TorchConfig.cmake:88 (if):
  Policy CMP0054 is not set: Only interpret if() arguments as variables or
  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
  details.  Use the cmake_policy command to set the policy and suppress this
  warning.

  Quoted variables like "MSVC" will no longer be dereferenced when the policy
  is set to NEW.  Since the policy is not set the OLD behavior will be used.
Call Stack (most recent call first):
  CMakeLists.txt:4 (find_package)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Found torch: I:/libtorch/lib/torch.lib
-- Configuring done
-- Generating done
CMake Warning:
  Manually-specified variables were not used by the project:

    CMAKE_BUILD_TYPE


-- Build files have been written to: H:/code/c++_code/pytorch+C/example/build

在这里插入图片描述
打开,运行,就可生成exe

ref
https://oldpan.me/archives/pytorch-windows-libtorch
https://oldpan.me/archives/pytorch-c-libtorch-inference
官网:https://pytorch.org/cppdocs/installing.html

测试

在python中

arr=np.arange(1,19).reshape((3,2,3)).astype(np.float32)

arr_torch = torch.from_numpy(arr).float().unsqueeze(0)

output = traced_script_module(arr_torch )

输出

output
Out[40]: 
tensor([[[[ 1.0000,  2.7597,  3.3423],
          [ 5.1762,  8.7566,  7.2332]],

         [[11.7321, 19.8502, 15.8473],
          [17.1406, 27.9997, 21.4676]],

         [[22.5052, 36.0626, 27.0142],
          [27.9509, 44.2620, 32.6647]]]], grad_fn=<ThresholdBackward1>)
arr
Out[41]: 
array([[[ 1.,  2.,  3.],
        [ 4.,  5.,  6.]],

       [[ 7.,  8.,  9.],
        [10., 11., 12.]],

       [[13., 14., 15.],
        [16., 17., 18.]]], dtype=float32)

C++中

	float data[] = { 1, 2, 3,4, 5, 6 ,
		7,8,9,10,11,12,13,
		14,15,16,17,18};
	torch::TensorOptions option(torch::kFloat32);
	torch::Tensor f = torch::from_blob(data, { 1, 3, 2,3 }, option);
	cout << f;
	at::Tensor result = module->forward({ f }).toTensor();
	cout << result;

输出

(1,1,.,.) =
  1  2  3
  4  5  6

(1,2,.,.) =
   7   8   9
  10  11  12

(1,3,.,.) =
  13  14  15
  16  17  18
[ Variable[CPUType]{1,3,2,3} ]

(1,1,.,.) =
  1.0000  2.7597  3.3423
  5.1762  8.7566  7.2332

(1,2,.,.) =
  11.7321  19.8502  15.8473
  17.1406  27.9997  21.4676

(1,3,.,.) =
  22.5052  36.0626  27.0142
  27.9509  44.2620  32.6647
[ Variable[CPUType]{1,3,2,3} ]

一致!
https://pytorch.org/tutorials/advanced/cpp_export.html

译文:https://blog.csdn.net/dou3516/article/details/82912480
torchscript:https://pytorch.org/docs/master/jit.html

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

Pytorch Windows C++调用(libtorch) Cmake编译 分别在python和C++中验证一致 的相关文章

随机推荐

  • 传感器超声波雷达

    转自 http www itsiwei com 21962 html 在上一次分享中 我介绍了毫米波雷达的原理 数据特性及优缺点 毫米波雷达的低环境敏感和低成本的特性使得其在ADAS和自动驾驶领域得到了广泛的应用 今天要介绍的是一款极其常见
  • 【Python】cnocr的使用

    1 介绍 cnocr于2019年7月25日开源 以下是使用介绍 2 安装 pip install cnocr 3 使用 from cnocr import CnOcr ocr CnOcr path r D server cnocr exam
  • 【AI前沿】chatgpt还有哪些不足?

    博客昵称 吴NDIR 个人座右铭 得之淡然 失之坦然 作者简介 喜欢轻音乐 象棋 爱好算法 刷题 其他推荐内容 计算机导论速记思维导图 其他内容推荐 五种排序算法 在这个愉快的周末让我们聊一下ChatGPT吧 ChatGPT 4时代来临 C
  • AD怎么调整PCB板子大小

    方法一 Design Board Shape Redefine Board Shape 快捷键D S R 对于方形 依次画好4个点 然后右键退出操作 没有画成想要的形状之前不要点击右键 方法二 1 在PCB页面用Keep Out Layer
  • C语言学习笔记(七)————分支语句相关

    1 单独一个分号是空语句 在一些情况下有重要作用 2 使用if else语句时 如果条件成立 要执行多条语句 这里要用一对 封装一个代码块 如果if else后面是单条语句则不用大括号括起 3 注意C语言中if else遵循就近原则 不看缩
  • 分析告警流量

    关键指标分析 事件量 原始告警量 主告警量 自动去重 规则压缩后告警量 压缩比 压缩比计算公式 1 主告警量 事件量 100 MTTA 告警平均响应or认领时长 MTTR 告警平均恢复or关闭时长 事件压缩分析 按天统计事件量 所有告警 主
  • 电商数据分析---RFM用户画像

    电商数据分析 一 数据描述 数据下载 订单顺序编号 订单号 用户名 商品编号 订单金额 付款金额 二 分析角度 1 整体角度 探索每个月有效的订单 以及销售额 2 个人角度 统计第一次购买的数量 以及最新时间购买的人数 3 用户画像 使用R
  • Windows API一日一练(13)TranslateMessage函数

    Windows API一日一练 13 TranslateMessage函数 分类 Direct3D 2007 07 23 08 41 7881人阅读 评论 5 收藏 举报 windows api winapi null 工作 Transla
  • linux基础命令之zip

    zip用来解压缩文件或对文件进行打包 语法 zip 选项 参数 zip压缩包 指定要创建的zip压缩包 文件列表 指定要压缩的文件列表 通常用法 zip r aaa zip aaa 压缩目录 zip r aaa zip aaa 压缩文件 选
  • 服务器来电后自动开机

    实战 xfs文件系统的备份和恢复 XFS提供了 xfsdump 和 xfsrestore 工具协助备份XFS文件系统中的数据 xfsdump 按inode顺序备份一个XFS文件系统 与传统的UNIX文件系统不同 XFS不需要在dump前被卸
  • Mac M1(arm 系列芯片)如何安装 Chromium

    最近写个脚本用到 puppeteer 然后安装 Chromium 出现一点问题 这里记录一下解决方案 Puppeteer 自动安装失败 在 Puppeteer 安装时会自动安装 Chromium 然而却总是报错 502 导致下载失败 直接下
  • [Unity] Unity 插件Behavior Designer行为树使用

    Unity 插件Behavior Designer行为树使用 1 创建行为树 在Tools gt Behavior Designer gt Editor中打开行为树编辑编辑窗口 选择一个游戏物体 在Behavior Designer中右键A
  • open3d-点云读写和显示

    目录 一 点云读取 二 点云写入 二 点云显示 三 open3d支持如下点云文件类型 四 代码及结果示例 一 点云读取 read point cloud filename format auto remove nan points True
  • 人工智能专家:AI并不像你想象的那么先进

    2019 10 28 14 44 32 神译局是36氪旗下编译团队 关注科技 商业 职场 生活等领域 重点介绍国外的新技术 新观点 新风向 编者按 近些年 很多人工智能产品已经投入应用 走进人们的生活 人工智能迅猛的发展速度很难不引人注意
  • OSI七层模型及各层功能概述

    目录 1 OSI的基本概念及原则 2 OSI七层模型各层功能概述 3 OSI七层模型举例 4 OSI七层模型总结 1 OSI的基本概念及原则 OSI是Open System Interconnect的缩写 意为开放式系统互联 其各个层次的划
  • pandas读取SQL数据库到DataFrame

    在查询sql数据库时可以直接将数据读取到dataframe中 这样直接解决读取了大量含BLOB的记录后出现BLOB数据无效的问题 如LOB variable no longer valid after subsequent fetch 对这
  • python绘制饼图双层_Python通过matplotlib画双层饼图及环形图简单示例

    1 饼图 pie 即在一个圆圈内分成几块 显示不同数据系列的占比大小 这也是我们在日常数据的图形展示中最常用的图形之一 在python中常用matplotlib的pie来绘制 基本命令如下所示 python3 X版本 vals 1 2 3
  • 刷脸支付促使传统行业迎来了数字化变革契机

    人脸识别的时候可以进行性别识别 性别识别是利用计算机视觉来辨别和分析图像中的人脸性别属性 多年来 人脸性别分类因其在人类身份认证 人机接口 视频检索以及机器人视觉中的潜在应用而备受关注 性别分类是一个复杂的大规模二次模式分类问题 分类器将数
  • Flutter安装的常见错误

    1 android studio not installed flutter config android studio dir E Android AndroidStudio 指定android studio的目录 2 flutter d
  • Pytorch Windows C++调用(libtorch) Cmake编译 分别在python和C++中验证一致

    0 下载准备 具备vs2015 cmake libtorch libtorch https pytorch org get started locally 先用的release版本测试了一下 把lib中的dll放在bin中 然后加到环境变量