Linux下源码编译Libtorch


在部署AI模型的时候用到了libtorch库,直接从官网下载后发现与现有环境不兼容,执行strings /usr/lib64/libstdc++.so.6 | grep GLIBC发现缺失相应的GLIBC版本,因此选择下载源码重新编译libtorch。这里记录一下编译过程。

参照官网编译教程,主要分为以下几步:

一、安装anconda3

anaconda3的安装教程可以参考: 安装anconda3

安装完后创建一个环境,我这里采用的python版本是3.7.4,所以执行以下命令

conda create -n Test374 python=3.7.4

创建完成后,进入该环境,conda activate Test374

二、安装环境

安装相关依赖

conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

三、下载

git clone --recursive https://github.com/pytorch/pytorch  # --recursive表示下载子模块,但有些模块很难下载下来,可以先用 git clone https://github.com.cnpmjs.org/pytorch/pytorch 
cd pytorch

四、切换分支

克隆下来的是最新版本,执行git tag查看分支,然后git checkout branch_name切换到想要的分支,

git checkout v1.2.0

# if you are updating an existing checkout
git submodule sync
git submodule update --init --recursive

注意:如果下载比较慢或者报错,可以在pytorch目录下查看.gitmodules文件, 切换分支后先把里面网址替换为github加速插件的地址, 然后再执行git submodule sync 和 后面的命令

  • 加速
    asmjit库为例
# 原始网址: 
   git@github.com:asmjit/asmjit.git
# 加速:
   https://github.com.cnpmjs.org/asmjit/asmjit.git
   https://hub.fastgit.org/asmjit/asmjit.git
   https://github.91chi.fun//https://github.com/asmjit/asmjit.git

五、安装

用export或者cmake-gui设置编译选项,如:

export USE_CUDA=False
export BUILD_TEST=False
export USE_NINJA=OFF

在分支目录下新建一个build文件夹,进入文件夹后执行以下命令,完成后在build目录下可以找到生成的结果

mkdir build && cd build
python ../tools/build_libtorch.py

六、整理

新建libtorch文件夹

  • 复制pytorch下的torch/include 到libtorch 目录
  • 复制build/lib下编译好的库文件到 libtorch/lib