Apple M2 Max设备上PyTorch启用MPS失败的问题求助
我编写了如下函数用于检查MacBook Pro Apple M2 Max上PyTorch的MPS启用状态:
def check_mps(): if torch.backends.mps.is_available(): print("MPS is available") else: print("MPS is not available") if torch.backends.mps.is_built(): print("MPS is built") else: print("MPS is not built") if torch.backends.mps.is_macos_or_newer(13, 0): print("MPS is macOS 13 or newer") else: print("MPS is not macOS 13 or newer")运行后得到以下结果:
MPS is not available MPS is not built随后出现报错,原因是MPS不存在时无法检查macOS版本。我已确认系统为最新版本,且尝试过更新系统,但没有任何变化,请问遗漏了什么步骤?
可能遗漏的步骤及解决方法
确认PyTorch版本及安装方式
MPS支持从PyTorch 1.12版本开始提供,必须安装官方针对Apple Silicon优化的版本。如果之前用conda或旧pip命令安装,可能拿到的是不支持MPS的构建包。请执行以下命令重新安装:pip3 install torch torchvision torchaudio检查Python环境架构
M2 Max是arm64架构,若你使用的是通过Rosetta运行的x86_64版本Python,PyTorch无法启用MPS。在终端运行以下命令验证架构:python -c "import platform; print(platform.machine())"若输出为
x86_64,需重新安装arm64版本的Python(可从python.org下载对应安装包,或用conda创建arm64专属环境)。验证PyTorch的MPS编译状态
运行以下命令查看PyTorch的构建配置,确认是否包含MPS支持:python -c "import torch; print(torch.__config__.show())"若输出中没有
MPS相关的编译选项,说明当前安装的PyTorch未编译MPS支持,需重新安装官方提供的Apple Silicon适配版本。修正检查函数的逻辑错误
当MPS未被构建时,调用is_macos_or_newer()会触发报错,需先判断is_built()再执行版本检查,修改后的函数如下:def check_mps(): if torch.backends.mps.is_available(): print("MPS is available") else: print("MPS is not available") if torch.backends.mps.is_built(): print("MPS is built") if torch.backends.mps.is_macos_or_newer(13, 0): print("MPS is macOS 13 or newer") else: print("MPS is not macOS 13 or newer") else: print("MPS is not built")重启Mac并验证Metal状态
偶尔Metal服务可能出现异常,重启Mac可恢复。同时可通过「关于本机」→「系统报告」→「图形/显示器」确认GPU的Metal支持状态是否正常。
内容的提问来源于stack exchange,提问作者Bryan

