最近使用 PyTorch 的静态链接经历了类似的过程,说实话,它不太漂亮。
我将概述我已采取的步骤(您可以在以下位置找到确切的源代码)火炬拉姆达 https://github.com/szymonmaszke/torchlambda, here https://github.com/szymonmaszke/torchlambda/blob/c70d3ea956972965e2bfe7a33213f9f6ba814972/src/CMakeLists.txt is CMakeLists.txt
(它还包括 AWS SDK 和 AWS Lambda 静态构建),here https://github.com/szymonmaszke/torchlambda/blob/c70d3ea956972965e2bfe7a33213f9f6ba814972/src/dependencies/torch.sh是一个脚本建筑pytorch
从源头(通过克隆和构建/scripts/build_mobile.sh
仅CPU支持)),
尽管它仅支持 CPU(尽管如果您需要 CUDA,类似的步骤应该没问题,但它至少可以帮助您入门)。
Pytorch静态库
预构建的静态 PyTorch
首先,您需要预先构建的静态库文件(all其中需要是静态的,因此没有.so
,只有那些有.a
扩展是合适的)。
老实说,我一直在寻找那些提供的PyTorch
on 安装页面 https://pytorch.org/get-started/locally/,但只有shared
版本。
在一个 GitHub 问题中,我找到了一种下载它们的方法,如下所示:
而不是下载(此处通过wget
)共享库:
$ wget https://download.pytorch.org/libtorch/cu101/libtorch-shared-with-deps-1.4.0.zip
你重命名shared
to static
(如所描述的在这个问题上 https://github.com/pytorch/pytorch/issues/25699#issuecomment-528389300),所以它会变成:
$ wget https://download.pytorch.org/libtorch/cu101/libtorch-static-with-deps-1.4.0.zip
然而下载后却没有libtorch.a
under lib
文件夹(没找到libcaffe2.a
要么如所示这个问题 https://github.com/pytorch/pytorch/issues/20742),所以我剩下的就是从源代码中显式构建。
如果您以某种方式拥有这些文件(如果有,请提供您从何处获取它们),您可以跳过下一步。
从源头构建
对于我用过的CPU版本/pytorch/scripts/build_mobile.sh https://github.com/pytorch/pytorch/blob/master/scripts/build_mobile.sh文件,如果需要 GPU 支持,您可以以此为基础构建您的版本(也许您只需通过-DUSE_CUDA=ON
到这个脚本,但不确定)。
最重要的是cmake
's -DBUILD_SHARED_LIBS=OFF
为了将一切构建为static
图书馆。您还可以检查来自我的工具的脚本 https://github.com/szymonmaszke/torchlambda/blob/c70d3ea956972965e2bfe7a33213f9f6ba814972/src/dependencies/torch.sh它将参数传递给build_mobile.sh
以及。
运行上面会给你静态文件/pytorch/build_mobile/install
默认情况下,那里有您需要的一切。
CMake
现在您可以将上面的构建文件复制到/usr/local
(最好不要这样做,除非您正在使用Docker
as torchlambda
)或从您的内部设置它的路径CMakeLists.txt
像这样:
set(LIBTORCH "/path/to/pytorch/build_mobile/install")
# Below will append libtorch to path so CMake can see files
set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH};${LIBTORCH}")
现在剩下的都很好except target_link_libraries
,这应该是(如这个问题 https://github.com/pytorch/pytorch/issues/21737,请参阅那里列出的相关问题以获取更多参考)与-Wl,--whole-archive
链接器标志,这让我想到了这一点:
target_link_libraries(example-app PRIVATE -lm
-Wl,--whole-archive "${TORCH_LIBRARIES}"
-Wl,--no-whole-archive
-lpthread
${CMAKE_DL_LIBS})
您可能不需要其中任何一个-lm
, -lpthread
or ${CMAKE_DL_LIBS}
,尽管我在构建时需要它亚马逊 Linux AMI https://aws.amazon.com/amazon-linux-ami/.
Building
现在您可以开始构建您的应用程序了。标准libtorch
方式应该没问题,但这是我使用的另一个命令:
mkdir build && \
cd build && \
cmake .. && \
cmake --build . --config Release
以上将创建build
文件夹在哪里example-app
二进制文件现在应该已安全定位。
最后使用ld build/example-app
验证一切PyTorch
是静态链接的,请参阅上述问题 https://github.com/pytorch/pytorch/issues/21737 point 5.
,您的输出应该看起来类似。