安装Theano GPU加速环境

安装Theano GPU加速环境

1. theano GPU 环境

theano GPU环境的底层设计主要是依靠pygpu模块进行神经网络的加速。所以第一步首先要安装好pygpu环境。有两种方法进行安装:
第一种是在conda环境下安装。直接输入以下的命令就可以进行安装:

conda install pygpu

这个也在conda-forge包中进行安装

conda install -c conda-forge pygpu

然后再安装theano神经网络库的环境

pip install theano
# 或者是 conda install theano

假设我们需要在虚拟环境中安装pygpu,这时候需要我们对pygpu进行编译操作
首先编译libpygpuarray需要cmake,c99,cython等依赖环境。cython环境可以直接通过pip安装:

pip install cython

安装cmake可以直接这样安装

sudo apt install cmake

或者是通源码进行安装。下面是对libpygpuarray进行安装
首先从theano的github上下载libpygpuarray的源码文件

git clone https://github.com/Theano/libgpuarray.git
cd libgpuarray

创建编译目录进行编译。如果想用libgpuarray进行开发,可以这样有如下编译方法:

cd <dir>
mkdir Build
cd Build
# you can pass -DCMAKE_INSTALL_PREFIX=/path/to/somewhere to install to an alternate location
cmake .. -DCMAKE_BUILD_TYPE=Release # or Debug if you are investigating a crash
make
make install
cd ..

如果只是想安装pygpu,只需要先激活虚拟环境(如果需要的话),然后在源码文件夹下面进行以下操作

python setup.py build
python setup.py install

注意,上述python安装过程需要Cython的支持。然后在用户文件夹下创建.theanorc文件。

nano ~/.theanorc

并且在文件中写入以下的内容

[global]
device = cuda
floatX=float32
root = /usr/local/cuda

[nvcc]
fastmath=True
compiler_bindir=/usr/local/cuda-10.2/bin

[blas]
ldflags = -lopenblas

[cuda]
root = /usr/local/cuda-10.2

[dnn]

enabled=True
inclue_path=/usr/local/cuda/include
library_path=/usr/local/cuda/lib64

然后进行theano环境的安装,这样就安装好了theano GPU加速运行的环境。

2. theano GPU测试

测试theano GPU的代码如下所示,新建test.py

from theano import function, config, shared, tensor
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([], tensor.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 %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, tensor.Elemwise) and
              ('Gpu' not in type(x.op).__name__)
              for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')

最后出现以下的信息说明GPU环境安装成功
显示结果图片

参考

[1] libpygpu参考文档
[2] theano参考文档

猜你喜欢

转载自blog.csdn.net/Zhang_Pro/article/details/107019628