【问题标题】:Tensorflow matrix multiplication is slower than numpyTensorflow 矩阵乘法比 numpy 慢
【发布时间】:2018-11-29 03:52:08
【问题描述】:
import tensorflow as tf
import numpy as np
from time import time

def print_timer(func):
  start_time = time()
  func()
  end_time = time()
  print(end_time - start_time)

N = 4
A = np.random.randn(N, 1000, 16000)
B = np.random.randn(N, 16000, 10)
sess = tf.Session()


A_ = tf.constant(A)
B_ = tf.constant(B)

def np_test():
  r = np.empty([N, 1000, 10])
  for i in range(N):
    r[i] = np.matmul(A[i], B[i])

print_timer(lambda: np.matmul(A, B))
print_timer(lambda: sess.run(tf.matmul(A,B)))

当我运行这段代码时,我得到了如下结果:

1.3403866291046143
4.291470527648926

这是运行时间。

我不知道为什么 tensorflow.matmul 比 numpy.matmul 慢。 我在 P40 NVIDIA GPU 上运行此代码,我使用的 tensorflow 版本是 1.4。

当我尝试在 tensorflow 1.8 上运行此代码时,我得到了相同的结果。

如果 tensorflow 并行运行矩阵乘法,GPU 上的矩阵乘法的运行时间不应该比在 CPU 上运行的 numpy 上运行的运行时间快很多吗?

【问题讨论】:

  • 复制数据到CPU不会增加很大的开销吗?我会尝试更长的操作,例如 100000 矩阵乘法。我可能完全错了。
  • A, B = tf.get_variable('v0', initializer=A), ... 做同样的事情并为惊喜做好准备(没有 cudaMemcpy)。

标签: numpy tensorflow gpu


【解决方案1】:

您在评估中包含tf.matmul,这意味着您正在测量操作的创建时间及其计算时间。

试试这个:

import tensorflow as tf
import numpy as np

sess = tf.InteractiveSession()

N = 4
A = np.random.randn(N, 1000, 16000)
B = np.random.randn(N, 16000, 10)
A_ = tf.constant(A)
B_ = tf.constant(B)

AB_ = A_ @ B_

%timeit np.matmul(A, B)
%timeit sess.run(AB_)

一些备注:

  • 不要重新发明轮子,使用timeit 来衡量计算时间。
  • 从 python 3.5 开始,您可以使用@ 作为矩阵乘法的快捷方式。

【讨论】:

    【解决方案2】:

    您没有使用您创建的常量张量。改变这个:

    print_timer(lambda: sess.run(tf.matmul(A,B)))
    

    到这里:

    print_timer(lambda: sess.run(tf.matmul(A_,B_)))
    

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 2013-03-03
      • 2020-07-13
      • 2018-02-17
      • 2017-06-30
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多