Theano GPU计算速度比numpy慢

3

我正在学习使用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因为开销问题?


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

7
事实上,你每次都在编译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通常用于计算密集型任务。

当前任务会有相当大的开销,因为最终您需要读取每个元素O(1)次,所以需要将数据传输到GPU并返回。但如果您想进行更多的计算,使用GPU是明智的选择。


谢谢您指出我每次都在编译函数。这很有启发性。现在我得到了类似的时间,但GPU仍然有点慢,所以我会避免在这样一个“简单”的任务中使用它。 - Vektor88

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接