Ubuntu下让Theano使用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 %f seconds" % (iters, t1 - t0))
print("Result is %s" % (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')

假设将上述代码存放在test_gpu.py中,运行test_gpu.py,如果输出如下结果:

[Elemwise{exp,no_inplace}(<TensorType(float32, vector)>)]
Looping 1000 times took 3.06635117531 seconds
Result is [ 1.23178029  1.61879337  1.52278066 ...,  2.20771813  2.29967761
  1.62323284]
Used the cpu

则说明当前使用的是CPU,并没有使用GPU。
若出现类似如下结果:

Using gpu device 0: GeForce GTX 580
[GpuElemwise{exp,no_inplace}(<CudaNdarrayType(float32, vector)>), HostFromGpu(GpuElemwise{exp,no_inplace}.0)]
Looping 1000 times took 0.638810873032 seconds
Result is [ 1.23178029  1.61879349  1.52278066 ...,  2.20771813  2.29967761
  1.62323296]
Used the gpu

这说明当前使用了GPU,并且告诉了我们当前使用的是哪个GPU。

如果你电脑上有GPU,并且你成功安装了CUDA,但是你的程序却没有使用GPU,那说明你当前的theano配置中默认是不使用GPU的,可以通过以下两个方式来使你的theano使用GPU。
1、在运行test_gpu.py时,在python test_gpu.py前加下语句:

# THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python test_gpu.py

2、配置你的.theanorc文件
在你home下面会有一个.theanorc文件,在这个文件中添加如下语句:

[global]
floatX = float32
device = gpu0

[lib]
cnmem = 1

注意:如果在你的home下没有发现.theanorc文件,按ctrl+h(显示隐藏文件)就可以看到了。

另外,方法一其实是一种覆盖型方式,即在运行当前的.py文件时,用当前的THEANO_FLAGS来覆盖.theanorc中默认的配置。

猜你喜欢

转载自www.linuxidc.com/Linux/2016-08/134142.htm