从coremltools4.0转换的mlmodel比从tfcoreml转换的mlmodel慢得多

问题描述

我使用tensorflow 1.15设计了一个简单的网络,并使用tfcoreml和coremltools4.0将其转换为mlmodels。我已经在系统版本为iOS13.5.1的iphonexs上测试了它们,发现从coremltools4.0转换的mlmodel比从tfcoreml转换的慢得多。

tensorflow中的原始网络如下:

graph = tf.Graph()
with graph.as_default():
    x = tf.placeholder(tf.float32,shape=[1,1000,4],name="input")
    y = tf.layers.conv2d(x,4,1,padding='same',activation=tf.nn.relu)
    output_names = [y.op.name]
  1. 使用tfcoreml转换为mlmodel
# using tfcoreml
coreml_save_tfcoreml_file = model_dir + "/debug_tfcoreml.mlmodel"
tfcoreml.convert(tf_model_path=frozen_graph_file,mlmodel_path=coreml_save_tfcoreml_file,output_feature_names=["conv2d/Relu:0"],# name of the output tensor (appended by ":0")
                    input_name_shape_dict={"input": [1,4]},# input tensor[1,height,width,channel]
                    minimum_ios_deployment_target='12')

enter image description here

  1. 使用coremltools4.0转换mlmodel:
coreml_save_coremltools_file = model_dir + "/debug_coremltools.mlmodel"
mlmodel = ct.convert(frozen_graph_file,source='tensorflow')
mlmodel.save(coreml_save_coremltools_file)

enter image description here

我在同一台iphonexs设备上测试了这两个mlmodel,无论在cpucpu + gpu上还是使用ANE,#2所花的时间都比#1多得多。

要确认mlmodel在ANE上运行,我在网络中插入了10个1x1卷积层以添加计算出的数量。它们确实都在ANE上运行,时间成本为(ALL

似乎coremltools4.0通过插入 transpose 层将数据类型从HWC更改为CHW格式。但是tf2coreml直接接受CHW格式。

如何在coremltools4.0的转换中删除转置层,以验证该层是否是导致性能下降的原因?

解决方法

是的,我认为我已经找到了原因。我使用“ MLModel Surgery”来修改mlmodel,删除两个转置层,并将输入形状和输出形状信息修改为NCHW格式。那么使用coretools4.0的性能与tfcoreml相同。 :)