1. 程式人生 > 實用技巧 >如何在Visual Studio 2019中啟動並配置一個使用pyTorch的C++專案(Windows系統,CMAKE專案)

如何在Visual Studio 2019中啟動並配置一個使用pyTorch的C++專案(Windows系統,CMAKE專案)

首先感謝做這個視訊的小哥:

https://www.youtube.com/watch?v=6eTVqYGIWx0&t=165s&ab_channel=PythonEngineer

寫下文章備忘。

首先開啟VS後,新建一個CMAKE專案,起名為“demoPytorch”。(小哥說因為CMAKE配置pyTorch比較簡單)

在這個頁面下載pyTorch:https://pytorch.org/get-started/locally/

選擇Windows、LibTorch、C++、顯示卡對應的CUDA版本.。然後選擇debug版本下載。

下載後解壓。

然後開啟專案資料夾中的CMakeLists.txt檔案(注意不是out資料夾),並加入下面這一行:

find_package(Torch REQUIRED)

告訴CMake我們需要Torch這個包。此時Ctrl+S儲存,出現錯誤,無法找到這個包。

點開下拉欄:

點選管理配置。

在CMake命令引數(CMake command argument)中寫入:

-DCMAKE_PREFIX_PATH="C:\\Users\\Think\\Documents\\Visual Studio 2019\\libtorch"

(填入解壓後的pyTorch路徑,注意換成雙反斜\\)

告訴CMake在哪裡可以找到pyTorch。

輸入後,Ctrl+S儲存。如果你已經安裝了CUDA,這時候應該顯示CMake正常配置。如果沒有安裝CUDA,會報錯,請下載安裝CUDA後把CMake變數中的CUDA_SDK_ROOT_DIR設定為CUDA dev安裝後的路徑。

之後,在cpp檔案中加入:

#include "torch/torch.h"

現在include下應該有紅線,我們需要到CMakeLists.txt中進行庫連結。

加入:

target_link_libraries(demoPytorch "${TORCH_LIBRARIES}")

Ctrl+S後,回到cpp檔案,紅線消失。

驗證一下是否配置成功,在cpp中把cout那一行改成:

    cout << torch::randn({3,2}) << endl;

執行出錯,提示找不到c10.dll檔案。

參考:https://pytorch.org/cppdocs/installing.html

複製以下程式碼到CMakeLists.txt檔案:

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

注意把example-app改為自己的專案名。

Ctrl+S後,等待CMake配置成功的提示,然後再次執行,成功:

附上CMakeLists.txt檔案:

# CMakeList.txt: demoPytorch 的 CMake 專案,在此處包括原始碼並定義
# 專案特定的邏輯。
#
cmake_minimum_required (VERSION 3.8)

find_package(Torch REQUIRED)

# 將原始碼新增到此專案的可執行檔案。
add_executable (demoPytorch "demoPytorch.cpp" "demoPytorch.h")
target_link_libraries(demoPytorch "${TORCH_LIBRARIES}")

if (MSVC)
  file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
  add_custom_command(TARGET demoPytorch
                     POST_BUILD
                     COMMAND ${CMAKE_COMMAND} -E copy_if_different
                     ${TORCH_DLLS}
                     $<TARGET_FILE_DIR:demoPytorch>)
endif (MSVC)

# TODO: 如有需要,請新增測試並安裝目標。

.cpp檔案:

 1 // demoPytorch.cpp: 定義應用程式的入口點。
 2 //
 3 
 4 #include "demoPytorch.h"
 5 #include "torch/torch.h"
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     cout << torch::randn({3,2}) << endl;
12     return 0;
13 }