在开发过程中,我们希望TensorFlow跟Python融合的好,这样有利于开发、调试和训练模型。
但在部署模型的过程中,我们希望:
- 模型无Python无关,可移植性好
- 模型容易被优化,能并行运行,能在不同计算设备中运行
- 模型运行速度高效
这时,TensorFlow中的图(Graph)就非常有用了:
- 它是一种数据结构,tf.Operation定义操作,tf.Tensor为经过基本操作的数据
- 与Python代码无关,不需要Python解释器
- 可以用Grappler进行优化
由此,TensorFlow分为Eager Execution和Graph Execution,使用函数 tf.config.run_functions_eagerly来切换
二者性能测试范例代码:
import tensorflow as tf
import timeit
x = tf.random.uniform(shape=[10, 10], minval=-1, maxval=2, dtype=tf.dtypes.int32)
def power(x, y):
result = tf.eye(10, dtype=tf.dtypes.int32)
for _ in range(y):
result = tf.matmul(x, result)
return result
# Eager Execution执行性能
print("Eager execution:", timeit.timeit(lambda: power(x, 100), number=1000))
# Graph Execution执行性能
tf.config.run_functions_eagerly(False)
power_as_graph = tf.function(power)
print("Graph execution:", timeit.timeit(lambda: power_as_graph(x, 100), number=1000))
Eager execution: 1.8359077000000001
2021-09-21 11:32:31.167202: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)
Graph execution: 0.33811800000000014
由此可以看出Graph execution的性能远远好于Eager execution,使用tf.function is commonly used to speed up training loops
网友评论