在Ubuntu下安裝完Theano以及cuda後,可以使用如下程序來測試你當前是否使用了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中默認的配置。
更多Ubuntu相關信息見Ubuntu 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=2