Python 如何在GPU上运行theano

Python 如何在GPU上运行theano,python,cuda,gpu,theano,Python,Cuda,Gpu,Theano,如果我使用Python3.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 =

如果我使用Python3.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工具包
  • 我在VS2012上成功地完成了一个cuda vectorAdd示例项目

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

如果在调用
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上运行。

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

[global]
device = gpu
floatx = float32

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

import theano.sandbox.cuda
theano.sandbox.cuda.use("gpu0")
您应该会看到这样的消息:

Using gpu device 0: Tesla K80

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

谢谢。但是在我的环境变量中,没有关于theano的变量。文档中显示了一个文件调用。theanoc,在我的主目录中,该文件不存在。如何设置“设备”值?如果不存在“无”标志,请创建它<代码>导入No设备='gpu0'检查设备值
打印(theano.config.device)
它又是'cpu'。如何创建此标志?取决于您的操作系统。对于Windows,请尝试。对于Linux,请尝试一个细节。这是float32,不是floar32(拼写错误)。我无法编辑它:-(对于版本1.0.4;device=cuda,这适用于theano v0.9。现在已弃用。
您正在导入theano.sandbox.cuda。这是旧的GPU后端,已从theano中删除。使用theano 0.9可使用它。更好的是,过渡到新的GPU后端!请参阅。)https://github.com/Theano/Theano/wiki/Converting-to-the-new-gpu-back-end%28gpuarray%29