Pytorch源码编译Libtorch

创建虚拟环境:

shell 复制代码
conda create -n build-libtorch python=3.8
cd build-libtorch

安装相关依赖:

shell 复制代码
conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

下载 Pytorch,可通过 HTTPS 或 SSH 方式进行下载:

shell 复制代码
git clone https://github.com/pytorch/pytorch.git  # HTTPS
git clone git@github.com:pytorch/pytorch.git  # SSH

克隆下来的是最新版本,可根据需要切换不同版本:

shell 复制代码
cd pytorch
git tag  # 查看标签
git checkout v1.4.0  # 根据标签切换版本
git submodule sync  # 根据父仓库中的配置,将子模块的URL进行更新,以保证与父仓库中记录的URL一致。这样,当执行git submodule update命令时,Git就能正确地从指定的URL下载子模块的更新或特定版本的代码
git submodule update --init --recursive  # 初始化和更新父仓库中的子模块,并递归地初始化和更新所有嵌套的子模块

如果不能通过 HTTPS 方式更新子模块,可以通过 sudo gedit .gitmodules 命令打开 .gitmodules 文件,该文件中记录了子模块的存储路径和下载地址。打开文件后修改子模块的 url,例如将 url = https://github.com/pybind/pybind11.git 修改为 url = git@github.com:pybind/pybind11.git。所有子模块的 url 都修改好后,依次执行 git submodule sync 和 git submodule update --init --recursive。

也可一步到位进行下载:

shell 复制代码
git clone -b v1.4.0 https://github.com/pytorch/pytorch.git
git clone -b v1.4.0 git@github.com:pytorch/pytorch.git

可根据需要设置编译选项:

shell 复制代码
export USE_CUDA=False
export BUILD_TEST=False
export USE_NINJA=OFF

执行编译:

shell 复制代码
方式一:
# 在pytorch目录下
mkdir build_libtorch && cd build_libtorch
python ../tools/build_libtorch.py

方式二:
# 在pytorch的父目录下
mkdir pytorch-build && cd pytorch-build
cmake -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=Release -DPYTHON_EXECUTABLE:PATH=`which python3` -DCMAKE_INSTALL_PREFIX:PATH=../pytorch-install ../pytorch
cmake --build . --target install

新建 libtorch 目录,将 pytorch/torch/include 目录复制到 libtorch 目录下,将 build/lib 目录复制到 libtorch 目录下。

可能遇到的问题:

  1. 在执行 cmake 命令时,运行到 Performing Test COMPILER_SUPPORTS_LONG_DOUBLE 这一步就停止不动了,长时间没有反应,这很可能是 GCC 版本导致的问题,可尝试更换 GCC 版本来解决,更换的版本可以比之前更高,也可以更低,可以多尝试
  2. 出现 Could not run a simple program built with your compiler. If you are trying to use -fsanitize=address, make sure libasan is properly installed on your system (you can confirm if the problem is this by attempting to build and run a small program.) 问题,可尝试在 pytorch 目录下的 CMakeLists.txt 中设置 set(INTERN_BUILD_MOBILE ON) 来解决
相关推荐
时早玖沐2 分钟前
KOOK「找不到语音频道」:同一个错误假设,我犯了三次
python·开源·ai编程
西瓜拿铁好喝3 分钟前
AI 办公和 RPA 不是一回事:自动化与智能化的分工
人工智能·自动化·rpa
Margrop3 分钟前
下载错一个包,服务器直接崩了?别再让 x64 与 ARM64 搞崩你的环境!小学生都能懂的 CPU 架构大比方与跨三大系统(Linux/macOS/Win)一键秒级识别指南(附全自动检测脚本与避坑秘籍)
人工智能
_冷眸_4 分钟前
Python 调用大模型 API:最小请求、Base URL 和 401/404 排查
开发语言·人工智能·python
Raas1006 分钟前
AI网关怎么部署?MAI Gateway部署实操教程
人工智能·开源·gateway·mai gateway·企业级ai产品
alonglong11 分钟前
本地把 Chrome 会话复用跑通:cookie 解密 + Playwright 注入的工程实录
人工智能
摩羯123012 分钟前
AI署名论文场景下,引用存在性校验如何支撑学术科研诚信
人工智能·aigc
Leo.yuan14 分钟前
2026年可信AI数据分析平台研究:主流厂商的可信机制、能力边界与企业选型
人工智能·数据挖掘·数据分析
記億揺晃着的那天14 分钟前
给网页埋提示词,能防住 AI 抓取吗?
人工智能·网站安全·提示词注入·ai爬虫
Solara19 分钟前
绿灯连亮 6 天、今天我真写了 4 KB:这盏灯从没看过我写的那一层
人工智能·程序员·ai编程