配置ubuntu16.04下Theano使用GPU運行程序的環境

 

ubuntu16.04默認安裝了python2.7和python3.5 。本教程使用python3.5python

 

第一步:將ubuntu16.04默認的python2修改爲默認使用python3 。linux

sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150

運行上述代碼以後會將ubuntu16.04默認使用python2修改成默認使用python3 。c++

輸入命令 python 能夠進入python的交互界面,會顯示python的版本 。git

 

第二步:安裝theano和CUDAubuntu

sudo apt-get install python3-numpy python3-scipy python3-dev python3-pip python3-nose g++ libopenblas-dev git
sudo pip3 install Theano

# cuda 7.5 don't support the default g++ version. Install an supported version and make it the default.
sudo apt-get install g++-4.9

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 20
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 10

sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.9 20
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 10

sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30
sudo update-alternatives --set cc /usr/bin/gcc

sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30
sudo update-alternatives --set c++ /usr/bin/g++

# Work around a glibc bug
echo -e "\n[nvcc]\nflags=-D_FORCE_INLINES\n" >> ~/.theanorc

逐個運行上述命令便可安裝theano和CUDA,以及numpy、scipy等經常使用的庫。dom

安裝完成後,可進入python交互界面,運行python2.7

import numpy;numpy.test()         oop

import scipy;scipy.test()測試

import theano;theano.test()blog

檢測是否安裝成功。

做者安裝後測試時numpy和scipy這兩個庫顯示OK,theano顯示Fail,可是theano能夠正常導入和使用。(這點我也不明白,大神們路過期還望指點一二)

至此,theano安裝完畢,能夠在cpu上運行theano的程序了。

 

第三步:配置.theanorc文件

在linux根目錄下打開.theanorc(注意前面是帶點的)文件,將

[global]

device = gpu

floatX = float32

[nvcc]

fastmath = True

加入到該文件裏。

 

第四步:安裝nvcc

這個就比較簡單了

sudo apt-get insatll nvcc

就能夠了。

 

至此,全部安裝程序都完成了。

 

能夠使用下面這點代碼來測試程序是使用cpu仍是gpu

from theano import function, config, shared, sandbox  
import theano.tensor as T  
import numpy  
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core  
iters = 1000

rng = numpy.random.RandomState(22)  
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))  
f = function([], T.exp(x))  
print (f.maker.fgraph.toposort())  
t0 = time.time()  
for i in range(iters):  
    r = f()
t1 = time.time()  
print ('Looping %d times took' % iters, t1 - t0, 'seconds' ) 
print ('Result is', r)  
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):  
    print ('Used the cpu')
else:  
    print ('Used the gpu')

  

 

以上就是本人親身安裝的所有過程,折騰了很久。若有疑問或者哪裏有不對的,還請留言指出。

相關文章
相關標籤/搜索