我怎样才能获得的数量flops从tfprof我的代码如下:
def calculate_flops():
# Print to stdout an analysis of the number of floating point operations in the
# model broken down by individual operations.
param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(
tf.get_default_graph(),
tfprof_options=tf.contrib.tfprof.model_analyzer.
TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
print(param_stats)
Run Code Online (Sandbox Code Playgroud)
但结果说flops = 0。我该如何计算翻牌数。我可以举个例子吗?
首先,到目前为止,tfprof.model_analyzer.print_model_analysis已不推荐使用,tf.profiler.profile应根据官方文档使用它。
假设我们知道的数量FLOP,则可以通过测量向前通过的运行时间并除以得到向前通过的FLOPS(每秒FLOP)FLOP/run_time
让我们举一个简单的例子。
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)
Run Code Online (Sandbox Code Playgroud)
输出8288。但是为什么我们得到的8288不是预期的结果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]))
Run Code Online (Sandbox Code Playgroud)
给出预期的输出7200。
通常,网络的变量会通过其他方案中的高斯分布进行初始化。在大多数情况下,我们对初始化FLOP并不感兴趣,因为它们在初始化期间完成一次,并且在训练或推理期间都不会发生。那么,如何不考虑初始化FLOP而获得FLOP的确切数目呢?
冻结图表用pb。
以下代码段说明了这一点:
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)
Run Code Online (Sandbox Code Playgroud)
输出
FLOP before freezing 8288
FLOP after freezing 7200
Run Code Online (Sandbox Code Playgroud)
[a]通常,乘积AB的矩阵乘法的FLOP为mq(2p -1)A[m, p],B[p, q]但出于某种原因,TensorFlow返回2mpq。已打开一个问题以了解原因。
| 归档时间: |
|
| 查看次数: |
1543 次 |
| 最近记录: |