正确地对设备进行基准测试是很困难的,因此请对从这些示例中学到的所有内容持保留态度。一般来说,最好比较您感兴趣的特定模型(例如运行ImageNet网络),以了解性能差异。也就是说,我知道这样做很有趣,所以。。。
更大的型号将更好地说明TPU和GPU的性能。您的示例还包括TPU调用成本中的编译时间:给定程序和形状的第一次调用之后的每个调用都将被缓存,因此您需要
tpu_ops
启动计时器前一次,除非您想捕获编译时间。
-
-
10 0.09931182861328125
-
100 0.5581905841827393
-
500 2.7688047885894775
. 因此,您实际上可以在0.55秒内运行此函数的100次迭代。
import os
import time
import tensorflow as tf
def calc(n):
img = tf.random_normal((128, 100, 100, 3))
def body(_):
result = tf.layers.conv2d(img, 32, 7)
result = tf.reduce_sum(result)
return result
return tf.contrib.tpu.repeat(n[0], body, [0.0])
session = tf.Session('grpc://' + os.environ['COLAB_TPU_ADDR'])
try:
print('Initializing TPU...')
session.run(tf.contrib.tpu.initialize_system())
for i in [1, 10, 100, 500]:
tpu_ops = tf.contrib.tpu.batch_parallel(calc, [[i] * 8], num_shards=8)
print('Warming up...')
session.run(tf.global_variables_initializer())
session.run(tpu_ops)
print('Profiling')
start = time.time()
session.run(tpu_ops)
end = time.time()
elapsed = end - start
print(i, elapsed)
finally:
session.run(tf.contrib.tpu.shutdown_system())
session.close()