如何在 windows 配置 libtorch c++ 前端庫?


如何在 windows 配置 libtorch c++ 前端庫?

下載 pytorch 已經編譯好的庫:
此庫不帶 gpu,主要方便演示。支持 win7 win10 系統。
下載地址:https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-latest.zip


1. cmake 配置

1.1 新建 CMakeLists.txt 並添加以下內容:
# 設置 cmake 版本限制
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)

# 項目名稱
project(libtorch-app)

# 設置 libtorch-win-shared-with-deps-latest 目錄,主要讓 find_package 可以找到 Torch 的 TorchConfig.cmake 配置文件以及其他相關 Config.cmake 配置文件

set(CMAKE_PREFIX_PATH "./libtorch-win-shared-with-deps-latest")

find_package(Torch REQUIRED)

add_executable(libtorch-app main.cpp)
target_link_libraries(libtorch-app "${TORCH_LIBRARIES}")
set_property(TARGET libtorch-app PROPERTY CXX_STANDARD 11)
1.2 在 CMakeLists.txt 同級目錄新建一個 main.cpp 文件,添加以下內容:
#include <torch/torch.h>
#include <iostream>
int main()
{
	torch::Tensor tensor = torch::rand({ 9,9 });
	std::cout << tensor << std::endl;
    return 0;
}
1.3 然后在 CMakeLists.txt 同級目錄下打開一個命令行(按住 Shift + 鼠標右鍵即可)輸入以下命令:

cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 14 Win64"

執行完以上命令后生成 libtorch-app.sln 解決方案文件,打開編譯即可。


2. 手動配置(僅適用於CPU,GPU需要自行另外添加相關依賴)

新建一個屬性頁並添加當當前配置文件中

2.1. 在 C/C++->常規->附加包含目錄里面添加以下內容並開啟多處理器編譯:
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\include\torch\csrc\api\include
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\include
2.2. 在 連接器->輸入->附加依賴項里面添加以下內容:
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\torch.lib
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\caffe2.lib
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\c10.lib
2.3. 在 調試->環境 里面添加環境變量

path=%path%;$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib

2.4 新建一個 main.cpp 文件,添加以下內容並使用 x64 模式編譯即可:
#include <torch/torch.h>
#include <iostream>
int main()
{
    torch::Tensor tensor = torch::rand({ 9,9 });
    std::cout << tensor << std::endl;
    return 0;
}

輸出一個隨機數值9x9矩陣:

0.2407  0.9294  0.5167  0.3774  0.9841  0.6530  0.9825  0.5814  0.4903
0.8882  0.5111  0.7414  0.7563  0.1666  0.2542  0.2624  0.0668  0.4328
0.0481  0.4880  0.6299  0.5140  0.0379  0.9187  0.3033  0.1510  0.6705
0.1983  0.6113  0.2893  0.0700  0.8585  0.3588  0.3891  0.0551  0.0458
0.7738  0.0797  0.0611  0.1781  0.3898  0.0238  0.0361  0.3905  0.2005
0.5774  0.5769  0.6275  0.3511  0.9609  0.3415  0.7188  0.5650  0.5670
0.0828  0.2139  0.5793  0.4089  0.5725  0.3938  0.8250  0.2695  0.6470
0.4106  0.3609  0.9982  0.8789  0.0134  0.8454  0.3880  0.0937  0.9598
0.1523  0.9423  0.2989  0.6404  0.0997  0.2817  0.0706  0.1867  0.1980
 Variable[CPUFloatType]{9,9} ]
``


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM