使用tensorflow矩阵乘法测试GPU

8

许多机器学习算法依赖于矩阵乘法(或者至少可以使用矩阵乘法来实现),为了测试我的GPU,我计划创建矩阵a,b,将它们相乘并记录计算完成所需的时间。

以下是生成两个维度为300000,20000的矩阵并将它们相乘的代码:

import tensorflow as tf
import numpy as np

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)


#a = np.array([[1, 2, 3], [4, 5, 6]])
#b = np.array([1, 2, 3])

a = np.random.rand(300000,20000)
b = np.random.rand(300000,20000)

println("Init complete");

result = tf.mul(a , b)
v = sess.run(result) 

print(v)

这个测试是否足够来比较GPU的性能?还应该考虑哪些因素呢?
1个回答

16

这是一个矩阵乘法基准测试的示例,避免了常见陷阱,并且在Titan X Pascal上达到了官方的11 TFLOP标志。

import os
import sys
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import tensorflow as tf
import time

n = 8192
dtype = tf.float32
with tf.device("/gpu:0"):
    matrix1 = tf.Variable(tf.ones((n, n), dtype=dtype))
    matrix2 = tf.Variable(tf.ones((n, n), dtype=dtype))
    product = tf.matmul(matrix1, matrix2)


# avoid optimizing away redundant nodes
config = tf.ConfigProto(graph_options=tf.GraphOptions(optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)))
sess = tf.Session(config=config)

sess.run(tf.global_variables_initializer())
iters = 10

# pre-warming
sess.run(product.op)

start = time.time()
for i in range(iters):
  sess.run(product.op)
end = time.time()
ops = n**3 + (n-1)*n**2 # n^2*(n-1) additions, n^3 multiplications
elapsed = (end - start)
rate = iters*ops/elapsed/10**9
print('\n %d x %d matmul took: %.2f sec, %.2f G ops/sec' % (n, n,
                                                            elapsed/iters,
                                                            rate,))

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - blue-sky
只有将 os.environ["CUDA_VISIBLE_DEVICES"]="1" 这一行注释掉,GPU 才能被发现。该方法适用于 Windows 10、tensorflow-gpu (1.4)、cuda_8.0.61_win10 和 cudnn-8.0-windows10-x64-v6.0。 - BSalita
错误信息为“无法为操作'Variable_1'分配设备:该操作已明确分配到/device:GPU:0,但可用设备为[/job:localhost/replica:0/task:0/device:CPU:0]。请确保设备规范引用了有效的设备。” - BSalita
cuda_8.0.61_win10 已从 https://developer.nvidia.com/cuda-toolkit-archive 下载。cudnn-8.0-windows10-x64-v6.0 已从 https://developer.nvidia.com/rdp/cudnn-download 下载。 - BSalita
1
这个测试正确显示了GPU的性能。我的1050 Ti获得了2.3 TFlops。几乎完全正确。 - Yeasin Ar Rahman

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