2015-11-04 324 views
4
import numpy as np 
import time 
import theano 
A = np.random.rand(1000,10000).astype(theano.config.floatX) 
B = np.random.rand(10000,1000).astype(theano.config.floatX) 
np_start = time.time() 
AB = A.dot(B) 
np_end = time.time() 
X,Y = theano.tensor.matrices('XY') 
mf = theano.function([X,Y],X.dot(Y)) 
t_start = time.time() 
tAB = mf(A,B) 
t_end = time.time() 
print ("NP time: %f[s], theano time: %f[s] **(times should be close when run 
on CPU!)**" %(np_end-np_start, t_end-t_start)) 
print ("Result difference: %f" % (np.abs(AB-tAB).max(),)) 

我运行此代码与Python 3.5测试theano代码,如何使用GPU?

NP time: 0.161123[s], theano time: 0.167119[s] (times should be close when 
run on CPU!) 
Result difference: 0.000000 

它说,如果时间接近,这意味着你的CPU运行。 我如何使用GPU。 ?

注:

  • 我有一个的NVIDIA Quadro k4200工作站。
  • 我安装Cuda工具包
  • 我成功地在VS2012上创建了一个cuda vectorAdd示例项目。

回答

13

通过在Theano的配置中指定device=gpu来配置Theano以使用GPU。有两种设置配置的主要方法:(1)在THEANO_FLAGS环境变量中,或(2)通过.theanorc文件。这两种方法以及Theano的所有配置标志都是documented

你会知道Theano使用GPU如果调用import theano后,您会看到一条消息,看起来像这样

Using gpu device 0: GeForce GT 640 (CNMeM is disabled) 

的细节可能对您有所不同,但如果出现任何消​​息都那么Theano是仅使用CPU。

请注意,即使您看到GPU消息,您的特定计算图形也可能无法在GPU上运行。查看哪些计算的部分在GPU上运行的打印的编译和优化图形

f = theano.function(...) 
theano.printing.debugprint(f) 

操作以前缀“GPU”启动会在GPU上运行。没有该名称前缀的操作将在CPU上运行。

+0

谢谢。但在我的环境变量中,没有关于theano的变量。 该文件说一个文件调用.theanorc,在我的主目录中,该文件不存在。我如何设置“设备”的价值? – babeyh

+0

如果'THEANO_FLAGS'不存在,请创建它! –

+1

'import theano' 'device ='gpu0'' 检查设备值 'print(theano.config.device)' 它又是'cpu'。 – babeyh

6

如果您在Linux上,请在您的个人文件夹中创建一个.theanorc文件,并添加以下内容以设置要在GPU上运行的theano。

[global] 
device = gpu 
floatx = float32 
+1

只是一个细节。它是float32,而不是floar32(错字)。我不能编辑它:-( – FiReTiTi

5

另外,如果你想使用programattically的GPU:

import theano.sandbox.cuda 
theano.sandbox.cuda.use("gpu0") 

你应该看到这样的消息:

Using gpu device 0: Tesla K80 

有用的,如果你是在ISN运行的环境”易于配置。