Welcome 微信登录

首页 / 操作系统 / Linux / Ubuntu下让Theano使用GPU

在Ubuntu下安装完Theano以及cuda后,可以使用如下程序来测试你当前是否使用了GPU:from theano import function, config, shared, sandboximport theano.tensor as Timport numpyimport timevlen = 10 * 30 * 768# 10 x #cores x # threads per coreiters = 1000rng = 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 secondsResult is [ 1.231780291.618793371.52278066 ...,2.207718132.299677611.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 secondsResult is [ 1.231780291.618793491.52278066 ...,2.207718132.299677611.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.py2、配置你的.theanorc文件
在你home下面会有一个.theanorc文件,在这个文件中添加如下语句:[global]floatX = float32device = gpu0[lib]cnmem = 1注意:如果在你的home下没有发现.theanorc文件,按ctrl+h(显示隐藏文件)就可以看到了。另外,方法一其实是一种覆盖型方式,即在运行当前的.py文件时,用当前的THEANO_FLAGS来覆盖.theanorc中默认的配置。更多Ubuntu相关信息见Ubuntu 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=2本文永久更新链接地址