如何为tflite解释器调用Flex委托?

时间:2019-08-26 13:06:07

标签: c++ python-3.x tensorflow tensorflow-lite

我有一个TensorFlow模型,我想将其转换为tflite模型,该模型将部署在ARM64平台上。

碰巧我的模型的两个操作(RandomStandardNormal,Softplus)似乎需要自定义实现。由于执行时间并不那么重要,因此我决定使用使用扩展运行时的混合模型。我通过以下方式进行了转换:

graph_def_file = './model/frozen_model.pb'
inputs = ['eval_inputs']
outputs = ['model/y']

converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]

tflite_file_name = 'vae_' + str(tf.__version__) + '.tflite'

tflite_model = converter.convert()
open(tflite_file_name, 'wb').write(tflite_model)

这有效,我最终得到了看似有效的tflite模型文件。每当我尝试使用解释器加载此模型时,都会收到错误消息(无论使用Python还是C ++ API都无关紧要):

ERROR: Regular TensorFlow ops are not supported by this interpreter. Make sure you invoke the Flex delegate before inference.
ERROR: Node number 4 (FlexSoftplus) failed to prepare.

我很难在tf网站上找到有关如何为这两个API调用Flex委托的文档。我偶然发现了一个头文件(“ tensorflow / lite / delegates / flex / delegate_data.h”),该文件似乎与此问题有关,但是将其包含在我的C ++项目中会产生另一个错误:

In file included from /tensorflow/tensorflow/core/common_runtime/eager/context.h:28:0,
                 from /tensorflow/tensorflow/lite/delegates/flex/delegate_data.h:18,
                 from /tensorflow/tensorflow/lite/delegates/flex/delegate.h:19,
                 from demo.cpp:7:
/tensorflow/tensorflow/core/lib/core/status.h:23:10: fatal error: tensorflow/core/lib/core/error_codes.pb.h: No such file or directory
 #include "tensorflow/core/lib/core/error_codes.pb.h"
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.

是否有机会在此之前遇到并解决?如果您有示例片段,请共享链接!

2 个答案:

答案 0 :(得分:1)

使用bazel管道构建TensorFlow Lite库时,可以包括并启用以下额外的TensorFlow ops库:

如有必要,通过添加--config = monolithic build标志来启用整体构建。

将TensorFlow ops委托库依赖项添加到构建依赖项中:tensorflow / lite / delegates / flex:delegate。

请注意,只要将委托链接到客户端库,在运行时创建解释器时,就会自动安装必要的TfLiteDelegate。不需要像其他委托类型通常需要的那样显式安装委托实例。

Python pip包

Python支持正在积极开发中。

来源:https://www.tensorflow.org/lite/guide/ops_select

答案 1 :(得分:0)

根据https://www.tensorflow.org/lite/guide/ops_select#android_aar,2019年9月25日

“选择运算符”的Python支持正在积极开发中。

您可以使用FlexDelegate在Android中测试模型。 我以相同的方式成功运行了模型。

例如https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/java/src/test/java/org/tensorflow/lite/InterpreterFlexTest.java