Mac OS 安裝 PyTorch 且支援GPU的步驟
新版 PyTorch 已內含Caffe2不需要再額外安裝,且已經支持Windows平台 (更新:2018/4)
根據官網安裝步驟,在macOS下PyTorch要支援Cuda GPU只能從 Source Code安裝
Step 0: (重要:必需先安裝好Cuda及Cudnn,並確認Xcode的版本為8.3.3)
安裝步驟請看另一篇文章:Mac OS 安裝Cuda及Cudnn
Step 1: 重要:移除所有曾經安裝過的 protobuf,例如:
(以免因為與PyTorch套件內建的版本不同,在編譯時抓取到『不相容的版本』而發生編譯錯誤)
conda uninstall protobuf
conda uninstall libprotobuf
brew uninstall protobuf
pip3 uninstall protobuf
pip3 uninstall libprotobuf
Step 2: 下載相依套件
pip3 install future numpy pyyaml six
Step 3: 下載最新版本 (目前為 v1.1.0可以成功安裝且正確執行 , 2019 7/17)
git clone https://github.com/pytorch/pytorch.git
cd pytorch
Step 4: 切換版本 (如果要使用舊版本才需要此步驟)
git tag # 查看可用版本
git checkout v1.1.0 # 此處切換為 v1.1.0版
Step 5: 下載子模組
git submodule update --init --recursive
Step 6: 設為10.9以免編譯發生錯誤
MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++
python3 setup.py install
Step 7: 安裝 PyTorch 常用的相關套件
pip3 install visdom torchvision torchnet
Step 8: 測試PyTorch是否支援GPU、安裝版本及GPU轉換是否成功:
import torch as tor
print( "Cuda: ", tor.cuda.is_available() ) # 檢查cuda是否可用
print( "Cudnn: ", tor.backends.cudnn.enabled ) # 檢查cudnn啟用狀態
print( "Devices: ", tor.cuda.device_count() )
print( "Version: ", tor.__version__)
t = tor.rand(3)
r = t.cuda() # 測試cuda轉換
Step 9: 程式可以使用下列技巧寫成GPU、CPU通用程式:
若有GPU則將變數配置或轉換到 GPU,否則配置於 CPU
device = tor.device("cuda:0" if tor.cuda.is_available() else "cpu")
x = tor.randn(3, 3, dtype=tor.float64, device=device)
input = data.to(device)
model = MyNN().to(device)