如何编写适配Linux、MacOS及M1 Mac Docker容器的requirements.txt?
问题
需要创建适配以下场景的requirements.txt:
- Linux系统
- MacOS系统(含M1芯片机型)
- 在M1 MacOS上构建并运行的Linux Docker容器
当前配置的requirements.txt如下:
torch==2.2.1+cpu ; sys_platform == "linux" torch==2.2.1 ; sys_platform != "linux"
执行安装命令pip install -r requirements.txt --find-links https://download.pytorch.org/whl/torch_stable.html后,Linux(及普通Linux Docker构建)、常规MacOS均可正常工作,但在M1 Mac上构建Linux Docker镜像时,出现错误:
docker build -t my-image:latest -f Dockerfile . // SNIP ERROR: Could not find a version that satisfies the requirement torch==2.2.1+cpu (from versions: 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.10.0, 1.10.1, 1.10.2, 1.11.0, 1.12.0, 1.12.1, 1.13.0, 1.13.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.2.0, 2.2.1, 2.2.2) ERROR: No matching distribution found for torch==2.2.1+cpu
核心诉求:找不到能识别底层物理硬件的需求指定符,希望得到适配所有场景的requirements.txt。
解决方案
问题根源是:M1 Mac上的Linux Docker容器默认使用arm64架构,而PyTorch的2.2.1+cpu版本仅针对x86_64架构的Linux,没有对应arm64的包。通过系统+架构的组合指定符即可解决,修改后的requirements.txt如下:
# x86_64架构Linux torch==2.2.1+cpu ; sys_platform == "linux" and platform_machine == "x86_64" # arm64架构Linux(含M1 Docker场景) torch==2.2.1 ; sys_platform == "linux" and platform_machine == "aarch64" # 所有MacOS(含M1) torch==2.2.1 ; sys_platform == "darwin"
关键说明
- 架构区分:用
platform_machine指定符区分x86_64和aarch64(arm64的标准命名)架构,arm64 Linux环境下无需+cpu后缀,直接用2.2.1版本即可匹配对应架构的CPU包。 - Docker适配:M1 Mac上的Linux Docker容器会识别
platform_machine为aarch64,自动拉取arm64版本的PyTorch,避免找不到包的错误。 - 安装命令不变:依然使用原命令执行安装:
pip install -r requirements.txt --find-links https://download.pytorch.org/whl/torch_stable.html
可选优化(Docker构建)
如果需要明确Docker构建的架构,可以在Dockerfile中添加架构声明:
FROM python:3.11 # 显示当前构建目标架构 ARG TARGETPLATFORM RUN echo "Building for ${TARGETPLATFORM}" RUN pip install -r requirements.txt --find-links https://download.pytorch.org/whl/torch_stable.html
内容的提问来源于stack exchange,提问作者k1eran
相关产品推荐
相关产品推荐

