运行 TensorFlow op 在 tf 中的图形模式 2.x
Run TensorFlow op in graph mode in tf 2.x
我想对一些 TensorFlow 操作进行基准测试(例如在它们之间或针对 PyTorch)。但是大多数时候我会写这样的东西:
import numpy as np
import tensorflow as tf
tf_device = '/GPU:0'
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)
with tf.device(tf_device):
a_tf = tf.constant(a)
b_tf = tf.constant(b)
%timeit tf.math.floormod(a_tf, b_tf)
这种方法的问题是它在急切模式下进行计算(我特别认为它必须执行 GPU 到 CPU 放置)。最后,我想在 tf.keras
模型中使用这些操作,因此想在图形模式下评估它们的性能。
首选的方法是什么?
我的 google 搜索一无所获,我不知道如何使用 tf 1.x 中的会话。
您要找的是tf.function
。检查这个 tutorial and this docs.
正如教程所说,在 TensorFlow 2 中,eager execution 是默认开启的。用户界面直观且灵活(运行 一次性操作更容易和更快),但这可能会以牺牲性能和可部署性为代价。要获得高性能和便携模型,请使用 tf.function 从您的程序中制作图表。
检查此代码:
import numpy as np
import tensorflow as tf
import timeit
tf_device = '/GPU:0'
shape = [100000]
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)
@tf.function
def experiment(a_tf, b_tf):
tf.math.floormod(a_tf, b_tf)
with tf.device(tf_device):
a_tf = tf.constant(a)
b_tf = tf.constant(b)
# warm up
experiment(a_tf, b_tf)
print("In graph mode:", timeit.timeit(lambda: experiment(a_tf, b_tf), number=10))
print("In eager mode:", timeit.timeit(lambda: tf.math.floormod(a_tf, b_tf), number=10))
我想对一些 TensorFlow 操作进行基准测试(例如在它们之间或针对 PyTorch)。但是大多数时候我会写这样的东西:
import numpy as np
import tensorflow as tf
tf_device = '/GPU:0'
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)
with tf.device(tf_device):
a_tf = tf.constant(a)
b_tf = tf.constant(b)
%timeit tf.math.floormod(a_tf, b_tf)
这种方法的问题是它在急切模式下进行计算(我特别认为它必须执行 GPU 到 CPU 放置)。最后,我想在 tf.keras
模型中使用这些操作,因此想在图形模式下评估它们的性能。
首选的方法是什么?
我的 google 搜索一无所获,我不知道如何使用 tf 1.x 中的会话。
您要找的是tf.function
。检查这个 tutorial and this docs.
正如教程所说,在 TensorFlow 2 中,eager execution 是默认开启的。用户界面直观且灵活(运行 一次性操作更容易和更快),但这可能会以牺牲性能和可部署性为代价。要获得高性能和便携模型,请使用 tf.function 从您的程序中制作图表。
检查此代码:
import numpy as np
import tensorflow as tf
import timeit
tf_device = '/GPU:0'
shape = [100000]
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)
@tf.function
def experiment(a_tf, b_tf):
tf.math.floormod(a_tf, b_tf)
with tf.device(tf_device):
a_tf = tf.constant(a)
b_tf = tf.constant(b)
# warm up
experiment(a_tf, b_tf)
print("In graph mode:", timeit.timeit(lambda: experiment(a_tf, b_tf), number=10))
print("In eager mode:", timeit.timeit(lambda: tf.math.floormod(a_tf, b_tf), number=10))