在当今使用Python作为机器学习的主流语言,我们已经越来越难看到使用C++训练模型的範例了。然而当您想在现实世界中的商用软体使用您的模型时,Python的速度、和隐私/安全问题,都会让您不想将模型储存在云上。有些善于在Microsoft上发展应用程式的团队会用Azure\Python训练模型(后端),再将模型转为ONNX,并且基于(前端)效能考量而在C++或C#的Visual Studio开发环境下布署。如果您的模型训练并不特别依赖高速运算;又希望能在一个专案中就能达到训练与预测的功能;那么我们可以考虑PyTorch的LibTorch (C++ API)。
关于如何使用 python 在 PyTorch 中训练模型,网路上已经有很多教学了。但是,关于如何在 Visual Studio C++ 使用LibTorch就没那么多了。参考了网路上的教学,写了这篇简易教学;想看原文的同学们,请点击以下的连结。
"Setting up a C++ project in Visual Studio 2019 with LibTorch 1.6"- Manpreet Singh Minhas
https://towardsdatascience.com/setting-up-a-c-project-in-visual-studio-2019-with-libtorch-1-6-ad8a0e49e82c
PyTorch官网:USING THE PYTORCH C++ FRONTEND
https://pytorch.org/tutorials/advanced/cpp_frontend.html
Visual Studio Extension for LibTorch
https://github.com/mszhanyi/VSIXTorch
环境:
VS2019
PyTorch 1.11
NVidia CUDA v11.6
先到PyTorch官网下载GPU版本
Download here (Release version):
https://download.pytorch.org/libtorch/cu113/libtorch-win-shared-with-deps-1.11.0%2Bcu113.zip
Download here (Debug version):
https://download.pytorch.org/libtorch/cu113/libtorch-win-shared-with-deps-debug-1.11.0%2Bcu113.zip
分别下载后直接解压缩并分开放置在
c:\libTorch-1-11\release...
c:\libTorch-1-11\debug...
然后到NVidia下载CUDA
https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64&target_version=11
再到visual studio marketplace下载libtorch专案模板
https://marketplace.visualstudio.com/items?itemName=YiZhang.LibTorch001
第一次安装时,切勿自行产生新的专案, 请使用专案模板产生专案,才能正确地连结应有的函式库。