我怎样才能在GPU上运行theano

时间:2015-11-04 10:17:13

标签: python cuda gpu theano

如果我使用python 3.5运行以下代码

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(), ))

我得到了输出

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 toolkit
  • 我在VS2012上成功完成了cuda vectorAdd示例项目。

3 个答案:

答案 0 :(得分:13)

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

如果在调用import theano之后看到类似这样的消息,你就会知道Theano正在使用GPU

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上运行。

答案 1 :(得分:7)

如果您使用的是Linux,请在主文件夹中创建.theanorc文件并添加以下内容以设置theano以在GPU上运行。

[global]
device = gpu
floatx = float32

答案 2 :(得分:5)

或者,如果您想以编程方式使用GPU:

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

您应该会看到如下消息:

Using gpu device 0: Tesla K80

如果您运行的环境不易配置,则非常有用。

相关问题