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)))
When I ran this code, I got the result as below:
1.3403866291046143
4.291470527648926
which are the running time.
I don't know why tensorflow.matmul is slower than numpy.matmul. I am running this code on the P40 NVIDIA GPU and the tensorflow version I am using is 1.4.
When I tried running this code on tensorflow 1.8, I got the same result.
If tensorflow runs matrix multiplication in parallel, shouldn't the run times for the matrix multiplication on the GPU be much faster than those that are run on numpy, which are run on the CPU?
A, B = tf.get_variable('v0', initializer=A), ...and be prepared for a surprise (no cudaMemcpy). - Patwie