2015-11-04 328 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運行的環境」易於配置。