Skip to main content

mac m芯片 配置pytorch开发环境

· 3 min read

准备工作如下​

1、去安装Conda(推荐 Miniforge 或 Anaconda)
2、在里面创建一个干净的虚拟环境
3、安装PyTorch
4、测试GPU是否可用

安装Conda(推荐 Miniforge 或 Anaconda)​

这边我用的是Miniforge,因为它原生支持ARM架构,使用社区驱动的conda-forge频道,更轻量。
顺便说一下我的是m2芯片。

下载最新版本的ARM64(M芯片)安装脚本:

curl -L -O https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh

安装 Miniforge:

bash Miniforge3-MacOSX-arm64.sh

中途会显示一些协议条目,它开始打印协议时,需要你按enter继续,最后问你是否同意的时候打yes。

选择安装目录,这边我选择默认的没有修改。

Miniforge3 will now be installed into this location:
/Users/xxx/miniforge3

- Press ENTER to confirm the location
- Press CTRL-C to abort the installation
- Or specify a different location below

出现这个:选择yes自动执行conda init

You can undo this by running `conda init --reverse $SHELL`? [yes|no]

查找你的conda位置:

which conda

手动使conda生效:

eval "$(/Users/xxx/miniforge3/bin/conda shell.zsh hook)"

验证是否安装成功:

conda --version

在里面创建一个干净的虚拟环境​

创建独立的PyTorch环境:

#创建命令  -n 虚拟环境名称 
conda create -n torch python=3.10
#激活虚拟环境
conda activate torch

检查python是否安装:

python --version

安装 PyTorch​

安装 PyTorch:

conda install pytorch torchvision torchaudio -c pytorch

测试GPU是否可用:​

打开编辑器,进入刚刚建立好的虚拟环境: 1、终端手动进入:

conda activate torch
python torch_demo.py

2、在编辑器中指定解释器:(每次运行都自动使用torch环境的Python)
我用的是vs code,打开命令面板(Cmd + Shift + P)输入以下内容,然后找到类似这种路径miniforge3/envs/torch/bin/python

“Python: Select Interpreter”

建立一个torch_demo.py文件用来测试:

#导入 PyTorch 库
import torch
#输出当前PyTorch的版本
print("PyTorch version:", torch.__version__)
#检查MPS是否可用
print("MPS available:", torch.backends.mps.is_available())
#检查 PyTorch 是否编译时包含了 MPS 支持
print("MPS built:", torch.backends.mps.is_built())

以后每次运行PyTorch项目前,都要先确实处于torch环境,如果没有的话就先激活:

#激活虚拟环境
conda activate torch