在pytorch官网下载C++版本的libtorch(这是编译好的)。一般下载release版本就行了。解压。
如果下载的是Windows版本,需要提前装好vs2017或以上的版本(2015会报错)
我习惯使用cmake进行编译。(vs2019可以创建cmake工程)如果你用的是vs2017,
那么可以安装一个clion。编译cmake程序非常方便。配置选x64平台(很重要,否则报错),选release。即可
把cmake文件改为:(这里只需要修改CMAKE_PREFIX_PATH为你自己的路径即可)
cmakelist.txt:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)

set(CMAKE_PREFIX_PATH D:/libtorch)

find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")

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

# The following code block is suggested to be used on Windows.
# According to https://github.com/pytorch/pytorch/issues/25457,
# the DLLs need to be copied to avoid memory errors.
if (MSVC)
    file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
    add_custom_command(TARGET example-app
            POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
            ${TORCH_DLLS}
            $<TARGET_FILE_DIR:example-app>)
endif (MSVC)
main.cpp:

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

int main() {
    std::cout << "Hello, World!" << std::endl;
    auto a = torch::tensor({{1, 2}, {3, 4}});
    std::cout << a << std::endl;
    return 0;
}

编译,即可体验C++版本的pytorch。libtorch调用模型有两种方式,官方给的例子很清楚:

https://pytorch.org/tutorials/advanced/cpp_frontend.html

Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐