首先,截至目前,tfprof.model_analyzer.print_model_analysis 已被弃用,根据官方文档应使用tf.profiler.profile。
鉴于我们知道FLOP的数量,我们可以通过测量前向传递的运行时间并除以FLOP/run_time来获得前向传递的FLOPS(每秒FLOP)
让我们举一个简单的例子。
g = tf.Graph()
sess = tf.Session(graph=g)
with g.as_default():
A = tf.Variable(initial_value=tf.random_normal([25, 16]))
B = tf.Variable(initial_value=tf.random_normal([16, 9]))
C = tf.matmul(A,B, name='output')
sess.run(tf.global_variables_initializer())
flops = tf.profiler.profile(g, options=tf.profiler.ProfileOptionBuilder.float_operation())
print('FLOP = ', flops.total_float_ops)
输出8288。但是为什么我们得到 8288 而不是 expected 结果 7200=2*25*16*9[a] ?答案在于张量 A 和 B 的初始化方式。使用高斯分布初始化会花费一些 FLOP。通过
更改
A和
B的定义
A = tf.Variable(initial_value=tf.zeros([25, 16]))
B = tf.Variable(initial_value=tf.zeros([16, 9]))
给出预期的输出7200。
通常,网络的变量在其他方案中使用高斯分布进行初始化。大多数时候,我们对初始化 FLOP 不感兴趣,因为它们在初始化期间完成一次,并且不会在训练或推理期间发生。那么,如何在不考虑初始化 FLOP 的情况下获得确切的 FLOP 数量?
冻结图表,使用pb。
下面的 sn-p 说明了这一点:
import tensorflow as tf
from tensorflow.python.framework import graph_util
def load_pb(pb):
with tf.gfile.GFile(pb, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='')
return graph
# ***** (1) Create Graph *****
g = tf.Graph()
sess = tf.Session(graph=g)
with g.as_default():
A = tf.Variable(initial_value=tf.random_normal([25, 16]))
B = tf.Variable(initial_value=tf.random_normal([16, 9]))
C = tf.matmul(A, B, name='output')
sess.run(tf.global_variables_initializer())
flops = tf.profiler.profile(g, options = tf.profiler.ProfileOptionBuilder.float_operation())
print('FLOP before freezing', flops.total_float_ops)
# *****************************
# ***** (2) freeze graph *****
output_graph_def = graph_util.convert_variables_to_constants(sess, g.as_graph_def(), ['output'])
with tf.gfile.GFile('graph.pb', "wb") as f:
f.write(output_graph_def.SerializeToString())
# *****************************
# ***** (3) Load frozen graph *****
g2 = load_pb('./graph.pb')
with g2.as_default():
flops = tf.profiler.profile(g2, options = tf.profiler.ProfileOptionBuilder.float_operation())
print('FLOP after freezing', flops.total_float_ops)
输出
FLOP before freezing 8288
FLOP after freezing 7200
[a] 通常矩阵乘法的 FLOP 是乘积 AB 的 mq(2p -1),其中 A[m, p] 和 B[p, q] 但 TensorFlow 出于某种原因返回 2mpq。已打开 issue 以了解原因。