如何计算从pb文件加载的tensorflow模型的flops

5

我有一个保存在pb文件中的模型。我希望计算它的FLOPS。我的示例代码如下:

import tensorflow as tf
import sys
from tensorflow.python.platform import gfile

from tensorflow.core.protobuf import saved_model_pb2
from tensorflow.python.util import compat

pb_file = 'themodel.pb'

run_meta = tf.RunMetadata()
with tf.Session() as sess:
    print("load graph")
    with gfile.FastGFile(pb_path,'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
        flops = tf.profiler.profile(tf.get_default_graph(), run_meta=run_meta,
            options=tf.profiler.ProfileOptionBuilder.float_operation())
        print("test flops:{:,}".format(flops.total_float_ops))

打印信息很奇怪。我的模型有数十层,但打印信息中只报告了18个flops。我非常确定模型已经正确加载,因为如果我尝试按如下方式打印每一层的名称:
print([n.name for n in tf.get_default_graph().as_graph_def().node])

打印信息显示了正确的网络。
我的代码出了什么问题?
谢谢!
2个回答

1
我想我找到了我的问题的原因和解决方案。以下代码可以打印给定pb文件的flops。
import os
import tensorflow as tf
from tensorflow.core.framework import graph_pb2
from tensorflow.python.framework import importer

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

pb_path = 'mymodel.pb'

run_meta = tf.RunMetadata()
with tf.Graph().as_default():
    output_graph_def = graph_pb2.GraphDef()
    with open(pb_path, "rb") as f:
        output_graph_def.ParseFromString(f.read())
        _ = importer.import_graph_def(output_graph_def, name="")
        print('model loaded!')
    all_keys = sorted([n.name for n in tf.get_default_graph().as_graph_def().node])
    # for k in all_keys:
    #   print(k)

    with tf.Session() as sess:
        flops = tf.profiler.profile(tf.get_default_graph(), run_meta=run_meta,
            options=tf.profiler.ProfileOptionBuilder.float_operation())
        print("test flops:{:,}".format(flops.total_float_ops))

问题中打印的flops仅为18的原因是,在生成pb文件时,我将输入图像形状设置为[None, None, 3]。如果我将其更改为[500, 500, 3],则打印的flops将是正确的。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接