Windows下的Libtorch配置

本来想在本地环境下尝试学习libtorch,结果在安装部署的适合就出现了一大堆问题,Windows环境真的很累人。

一、环境

  • Cmake:先在Windows环境下装好cmake
  • MinGW:我这里使用的是MinGW编译器作为反例
  • MSVC:Microsoft Visual C/C++

二、安装libtorch

按照官方的指南开始我们的installing,因为本机环境没有Nvidia GPU,所以下载cpu版本并解压

wget https://download.pytorch.org/libtorch/nightly/cpu/libtorch-shared-with-deps-latest.zip
unzip libtorch-shared-with-deps-latest.zip

如果你的环境有GPU就去官网)上按照你的cuda版本下载对应的libtorch版本

三、编译

1.CMakeLists

现在仅仅只是把libtorch给下载了,接下来需要使用libtorch中的库、头文件,需要根据我们的项目编写CMakeLists,官方给的CMakeLists.txt如下所示,我们需要根据我们的项目名称和文件进行修改(修改其中的example-app、example-app.cpp)

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

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

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

# 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)

2.cmake

在CMakeLists.txt的当前目录下,创建build目录并进入

然后执行

cmake -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch ..
cmake --build . --config Release

-DCMAKE_PREFIX_PATH处填写我们刚刚下载下来的libtorch的绝对路径

好了,如果你和我一样使用的是MinGW,那么现在肯定会报以下错误:

CMake Error at CMakeLists.txt:2 (project):
  Running

   'nmake' '-?'

  failed with:

   The system cannot find the file specified

-- Configuring incomplete, errors occurred!
See also "/Build/CMakeFiles/CMakeOutput.log".

我们这时候需要将刚刚创建的build目录删除,然后使用以下命令重新编译

cmake -S . -G "MinGW Makefiles" -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch ..

此时可成功cmake

cmake --build . --config Release

但接下来仍然失败……

3.原因

最终在stackoverflow上找到了原因,目前mingw并不支持libtorch,所以必须使用MSVC才行

“Building with mingw is not officially supported. github.com/pytorch/pytorch/issues/24460. You should use MSVC”

乖乖的用MicroSoft Visual C++在windows平台使用libtorch吧