【问题标题】:Theano GPU calculation slower than numpyTheano GPU 计算比 numpy 慢
【发布时间】:2015-10-24 04:13:02
【问题描述】:

我正在学习使用 theano。我想通过计算其中每个元素的二进制 TF-IDF 来填充术语文档矩阵(一个 numpy 稀疏矩阵):

import theano
import theano.tensor as T
import numpy as np
from time import perf_counter

def tfidf_gpu(appearance_in_documents,num_documents,document_words):
    start = perf_counter()
    APP = T.scalar('APP',dtype='int32')
    N = T.scalar('N',dtype='int32')
    SF = T.scalar('S',dtype='int32')
    F = (T.log(N)-T.log(APP)) / SF
    TFIDF = theano.function([N,APP,SF],F)
    ret = TFIDF(num_documents,appearance_in_documents,document_words)
    end = perf_counter()
    print("\nTFIDF_GPU ",end-start," secs.")
    return ret

def tfidf_cpu(appearance_in_documents,num_documents,document_words):
    start = perf_counter()
    tfidf = (np.log(num_documents)-np.log(appearance_in_documents))/document_words
    end = perf_counter()
    print("TFIDF_CPU ",end-start," secs.\n")
    return tfidf

但是numpy版本比theano实现要快很多:

Progress 1/43
TFIDF_GPU  0.05702276699594222  secs.
TFIDF_CPU  1.454801531508565e-05  secs.

Progress 2/43
TFIDF_GPU  0.023830442980397493  secs.
TFIDF_CPU  1.1073017958551645e-05  secs.

Progress 3/43
TFIDF_GPU  0.021920352999586612  secs.
TFIDF_CPU  1.0738993296399713e-05  secs.

Progress 4/43
TFIDF_GPU  0.02303648801171221  secs.
TFIDF_CPU  1.1675001587718725e-05  secs.

Progress 5/43
TFIDF_GPU  0.02359767400776036  secs.
TFIDF_CPU  1.4385004760697484e-05  secs.

....

我了解到这可能是由于开销造成的,对于小型操作可能会降低性能。

我的代码是不是很糟糕,还是应该因为开销而避免使用 GPU?

【问题讨论】:

  • 据我所知,您的函数似乎只对标量输入值 (T.scalar) 起作用。除非您要处理相当大的数组,并执行涉及多个数组元素的矢量化操作,否则使用 GPU 是没有意义的。

标签: python numpy theano tf-idf


【解决方案1】:

问题是你每次都在编译你的 Theano 函数。编译需要时间。尝试像这样传递编译后的函数:

def tfidf_gpu(appearance_in_documents,num_documents,document_words,TFIDF):
    start = perf_counter()
    ret = TFIDF(num_documents,appearance_in_documents,document_words)
    end = perf_counter()
    print("\nTFIDF_GPU ",end-start," secs.")
    return ret

APP = T.scalar('APP',dtype='int32')
N = T.scalar('N',dtype='int32')
SF = T.scalar('S',dtype='int32')
F = (T.log(N)-T.log(APP)) / SF
TFIDF = theano.function([N,APP,SF],F)

tfidf_gpu(appearance_in_documents,num_documents,document_words,TFIDF)

此外,您的 TFIDF 任务是一项带宽密集型任务。 Theano 和 GPU 通常最适合计算密集型任务。

当前任务将数据传输到 GPU 并返回会产生相当大的开销,因为最终您需要读取每个元素 O(1) 次。但是如果你想做更多的计算,使用 GPU 是有意义的。

【讨论】:

  • 感谢您指出我每次都在编译我的函数。这很有启发性。现在我得到了类似的时间,但 GPU 仍然有点慢,所以我会避免将它用于这样“简单”的任务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2017-04-05
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 2018-05-22
相关资源
最近更新 更多