【问题标题】:How can I run theano on GPU如何在 GPU 上运行 theano
【发布时间】:2016-02-04 18:57:16
【问题描述】:

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

【问题讨论】:

    标签: python cuda gpu theano


    【解决方案1】:

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

    [global]
    device = gpu
    floatx = float32
    

    【讨论】:

    • 只是一个细节。它是 float32,而不是 float32(错字)。我无法编辑它:-(
    • 适用于 1.0.4 版;设备=cuda
    【解决方案2】:

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

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

    您应该会看到这样的消息:

    Using gpu device 0: Tesla K80
    

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

    【讨论】:

    • 这适用于 theano v0.9。现在已弃用。 You are importing theano.sandbox.cuda. This is the old GPU back-end and is removed from Theano. Use Theano 0.9 to use it. Even better, transition to the new GPU back-end! See https://github.com/Theano/Theano/wiki/Converting-to-the-new-gpu-back-end%28gpuarray%29
    【解决方案3】:

    您可以通过在 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 上运行。

    【讨论】:

    • 谢谢。但是在我的环境变量中,没有关于theano的变量。该文件说一个文件调用.theanorc,在我的主目录中,该文件不存在。我如何设置“设备”值?
    • 如果THEANO_FLAGS 不存在,创建它!
    • import theano device='gpu0' 检查设备值 print(theano.config.device) 又是'cpu'。
    • 我如何创建这个标志?
    • 取决于您的操作系统。对于 Windows,请尝试 microsoft.com/resources/documentation/windows/xp/all/proddocs/…。对于 Linux,请尝试 digitalocean.com/community/tutorials/…
    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2023-03-18
    • 2021-04-06
    • 2015-12-15
    • 1970-01-01
    • 2016-08-20
    相关资源
    最近更新 更多