[work] 最爽的GPU深度學習環境搭建教程
背景介紹
GPU 在以下方面有別於 CPU:
- CPU和GPU之所以大不相同,是由於其設計目標的不同,它們分別針對了兩種不同的應用場景。CPU需要很強的通用性來處理各種不同的資料型別,同時邏輯判斷又會引入大量的分支、跳轉和中斷的處理。這些都使得CPU的內部結構異常複雜。而GPU面對的則是型別高度統一的、相互無依賴的大規模資料和不需要被打斷的純淨的計算環境。
上圖中,綠色的部分是計算單元(ALU),就是我們用來進行加減乘除運算的部分;橙紅色的部分是儲存單元(Cache),用來儲存計算的相關資料;橙黃色部分是控制單元(Control)。由於GPU的工作物件資料結構相對簡單,其絕大部分硬體資源用來進行計算,而CPU所面對的計算任務則要複雜的多,所以不得不花費相當多的資源在其他方面。
機器學習和深度學習在處理大的資料集的時候,如果使用傳統的CPU伺服器或工作站,只能採用out-of-core或者採用資料子集的方式進行訓練,這往往意味著訓練模型精準度的下降:比如out-of-core的方式,必須解決梯度下降是否合理的問題,傳統方法是梯度截斷以及最新的FTRL,以上方法都能解決一些問題,但是缺陷也比較明顯:比如梯度截斷很容易陷入梯度爆炸或者梯度消失、FTRL可適應的演算法模型又比較少(出來的比較晚,在深度學習上基本沒有應用,不過在on-line-learning方面有很好的前景);資料子集採用隨機取樣或者部分擷取,會丟掉一些週期性的關鍵資訊;而使用GPU的話,可以訓練更大的資料集、更快的得到訓練結果,這也意味著更快的迭代,更好的學習效果。
本文基於阿里給的一臺GPU雲主機,講解如何在CentOS7.4上搭建以基於TensorFlow的深度學習環境。
環境搭建
安裝zsh, oh-my-zsh
zsh與oh-my-zh可以極大的提高Linux shell環境的命令輸入效率,更加強大的自動提示功能,各種強大的外掛、主題。
zsh安裝:
1. yum search zsh
2. yum install -y zsh.x86_64
oh-my-zsh安裝
1. yum install git 2. sh -c "$(wget https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)" 3. chsh -l: 4. chsh -s /bin/zsh
虛擬環境
pyenv是Python的虛擬環境管理外掛,有這個外掛,可以非常方便的安裝不同版本的Python、anaconda。
$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv #使用 git 把 pyenv 下載到家目錄
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc #然後需要修改環境變數,使用 Bash Shell 的輸入
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
$ echo 'eval "$(pyenv init -)"' >> ~/.zshrc #最後新增 pyenv init
$ exec $SHELL -l #輸入命令重啟 Shell,然後就可以重啟pyenv
pyenv-virtual 外掛保證在使用pyenv locan anacon*設定目錄環境的時候,能夠在terminal顯示正確的虛擬環境名稱。
git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.zshrc
source ~/.zshrc
安裝anaconda
anaconda是一個打包好的Python科學計算包,裡面包含Python以及大部分科學計算需要的安裝包,比如pandas, matplotlib, statemodel等。
pyenv install --list | grep anaconda #獲取可以安裝的anaconda版本
pyenv install anaconda3-5.1.0
安裝顯示卡驅動
首先檢查是否有支援英偉達CUDA的顯示卡:
1. lspci | grep -i nvidia
2. 00:08.0 3D controller: NVIDIA Corporation GP100GL [Tesla P100 PCIe 16GB] (rev a1)
3. 00:09.0 3D controller: NVIDIA Corporation GP100GL [Tesla P100 PCIe 16GB] (rev a1)
檢查顯示卡驅動以及型號:
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm
yum install nvidia-detect
nvidia-detect -v
去NVIDIA官網下載對應型號、版本的顯示卡驅動。
禁用系統自帶的顯示卡驅動:
#新建一個配置檔案
sudo vim /etc/modprobe.d/blacklist-nouveau.conf
#sudo vim /usr/lib/modprobe.d/dist-blacklist.conf #上面的的命令最後失敗的話使用這個
#寫入以下內容
blacklist nouveau
options nouveau modeset=0
#儲存並退出
:wq
#備份當前的映象
sudo mv /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r).img.bak
#建立新的映象
sudo dracut /boot/initramfs-$(uname -r).img $(uname -r)
#重啟
sudo reboot
#最後輸入上面的命令驗證
lsmod | grep nouveau
#如果還不行可以嘗試下面的命令再重啟:
sudo dracut --force
安裝顯示卡驅動;
chmod +x NVIDIA-Linux-x86_64-390.48.run
sh NVIDIA-Linux-x86_64-390.48.run
可能會出現以下warning:
WARNING: nvidia-installer was forced to guess the X library path '/usr/lib' and X module path '/usr/lib/xorg/modules'; these paths were not queryable from the system. If X fails to find the NVIDIA X driver module, please install the `pkg-config` utility and the X.Org SDK/development package for your distribution and reinstall the driver.
忽略不管。檢測顯示卡是否安裝成功:
nvidia-smi
安裝CUDA
CUDA安裝方式推薦使用runfile,使用rmp線上安裝會出錯,很難解決。下載時配置選擇如下:
如果下載不動,可以手動更改DNS到1.1.1.1,傳說中最快的DNS。
runfile中,實際上包含了三個檔案:顯示卡驅動、CUDA、sample,我們這裡只需要最後兩個,所以先解壓這個檔案:
./cuda_7.5.18_linux.run --extract=$HOME
./cuda-linux64-rel-7.5.18-19867135.run
檢測CUDA 安裝是否成功:
./cuda-samples.9.1.85-23083092-linux.run ./software/cuda-sample
cd /usr/local/cuda/samples
make
cd bin/x86_64/linux/release/
./deviceQuery
#出現一大段結果,最後是
Result = PASS
#代表通過了
#最後檢查
./bandwidthTest
#顯示Result = PASS
安裝CuDNN
CuDNN下載需要註冊賬號,這裡就不一一舉例,自行去NVIDIA官網下載CuDNN的壓縮檔案:
解壓到以下目錄:
tar -xvf cudnn-8.0-linux-x64-v6.0.tgz -C /usr/local
ldconfig
安裝bazel
bazel是Google的打包工具,到https://github.com/bazelbuild/bazel/releases下載對應的bazel 版本安裝。
原始碼編譯安裝TensorFlow
選擇原始碼安裝的方式,好處式可以自定義很多需求,谷歌給的編譯好的wheel檔案,是比較common的,很多功能我們並不需要,比如Google Cloud Platform support,也有一些很有用的功能考慮相容性預設是關閉的,比如CPU加速計算指令,使用原始碼編譯安裝可以對這些進行更合理的選擇。當然原始碼安裝也有一個壞處,就是安裝時間比較長。
進入TensorFlow原始碼目錄,pyenv locan anaconda3*設定該目錄的虛擬環境,保證我們的TensorFlow是安裝在需要的虛擬環境裡面去。
對應谷歌給出的目前編譯安裝通過的版本:
選擇對應gcc與bazel版本。
本文使用以下指令碼對TensorFlow進行編譯安裝:
#!/usr/bin/env bash
# Detect platform
if [ "$(uname)" == "Darwin" ]; then
# MacOS
raw_cpu_flags=`sysctl -a | grep machdep.cpu.features | cut -d ":" -f 2 | tr '[:upper:]' '[:lower:]'`
elif [ "$(uname)" == "Linux" ]; then
# GNU/Linux
raw_cpu_flags=`grep flags -m1 /proc/cpuinfo | cut -d ":" -f 2 | tr '[:upper:]' '[:lower:]'`
else
echo "Unknown plaform: $(uname)"
exit -1
fi
# check if VirtuelEnv activated
if [ -z "$VIRTUAL_ENV" ]; then
echo "VirtualEnv is not activated"
exit -1
fi
VENV_BIN=$VIRTUAL_ENV/bin
VENV_LIB=$VIRTUAL_ENV/lib
# bazel tf needs these env vars
export PYTHON_BIN_PATH=$VENV_BIN/python
export PYTHON_LIB_PATH=$VENV_LIB/`ls $VENV_LIB | grep python | grep -v lib`
COPT="--copt=-march=native"
for cpu_feature in $raw_cpu_flags
do
case "$cpu_feature" in
"sse4.1" | "sse4.2" | "ssse3" | "fma" | "cx16" | "popcnt" | "maes")
COPT+=" --copt=-m$cpu_feature"
;;
"avx1.0")
COPT+=" --copt=-mavx"
;;
*)
# noop
;;
esac
done
bazel clean
./configure
bazel build -c opt $COPT -k //tensorflow/tools/pip_package:build_pip_package
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
pip install --upgrade /tmp/tensorflow_pkg/`ls /tmp/tensorflow_pkg/ | grep tensorflow`
該指令碼支援mac, linux。指令碼啟動之後,會有以下選項提示:
INFO: Starting clean (this may take a while). Consider using --async if the clean takes more than several minutes.
WARNING: Running Bazel server needs to be killed, because the startup options are different.
You have bazel 0.13.0 installed.
Do you wish to build TensorFlow with jemalloc as malloc support? [Y/n]: n
No jemalloc as malloc support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Google Cloud Platform support? [Y/n]: n
No Google Cloud Platform support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Hadoop File System support? [Y/n]: n
No Hadoop File System support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Amazon S3 File System support? [Y/n]: n
No Amazon S3 File System support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Apache Kafka Platform support? [Y/n]: n
No Apache Kafka Platform support will be enabled for TensorFlow.
Do you wish to build TensorFlow with XLA JIT support? [y/N]: y
XLA JIT support will be enabled for TensorFlow.
Do you wish to build TensorFlow with GDR support? [y/N]: n
No GDR support will be enabled for TensorFlow.
Do you wish to build TensorFlow with VERBS support? [y/N]: n
No VERBS support will be enabled for TensorFlow.
Do you wish to build TensorFlow with OpenCL SYCL support? [y/N]: n
No OpenCL SYCL support will be enabled for TensorFlow.
Do you wish to build TensorFlow with CUDA support? [y/N]: y
CUDA support will be enabled for TensorFlow.
Please specify the CUDA SDK version you want to use, e.g. 7.0. [Leave empty to default to CUDA 9.0]: 9.1
Please specify the location where CUDA 9.1 toolkit is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:
Please specify the cuDNN version you want to use. [Leave empty to default to cuDNN 7.0]: 7.1
Please specify the location where cuDNN 7 library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:
Do you wish to build TensorFlow with TensorRT support? [y/N]: n
No TensorRT support will be enabled for TensorFlow.
Please specify the NCCL version you want to use. [Leave empty to default to NCCL 1.3]:
Please specify a list of comma-separated Cuda compute capabilities you want to build with.
You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus.
Please note that each additional compute capability significantly increases your build time and binary size. [Default is: 6.0,6.0]
Do you want to use clang as CUDA compiler? [y/N]: n
nvcc will be used as CUDA compiler.
Please specify which gcc should be used by nvcc as the host compiler. [Default is /usr/bin/gcc]:
Do you wish to build TensorFlow with MPI support? [y/N]: n
No MPI support will be enabled for TensorFlow.
Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]:
Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: n
Not configuring the WORKSPACE for Android builds.
Preconfigured Bazel build configs. You can use any of the below by adding "--config=<>" to your build command. See tools/bazel.rc for more details.
--config=mkl # Build with MKL support.
--config=monolithic # Config for mostly static monolithic build.
Configuration finished
Starting local Bazel server and connecting to it...
主要需要開啟上面的幾個選項:
1. JIT #開啟Intel CPU 加速計算指令集
2. CUDA #版本號輸入9.1
3. CuDNN #版本號輸入7.1
4. #其它選項如上面的配置log所示
測試TensorFlow是否安裝成功
執行以下程式碼,如果log中顯示有GPU,說明安裝成功:
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
執行結果如下圖所示:
說明安裝成功。
安裝Keras
Keras是在TensorFlow以及PyTorch(未來PyTorch會和Caffe2進一步合併)上面更抽象的一層,使用了layer的概念實現了很多深度學習的基本模型結構,比如Embedding, Pooling, DropOut, Dense等,也可以直接呼叫TensorFlow或者PyTorch的backend(二選一),使得深度學習的編碼難度大幅降低。
pip install keras
好了,你可以開始愉快的機器學習之旅了~