【问题标题】:How do you convert a .onnx to tflite?如何将 .onnx 转换为 tflite?
【发布时间】:2019-04-10 10:51:51
【问题描述】:

我已通过以下方式将模型导出到 ONNX:

# Export the model
torch_out = torch.onnx._export(learn.model,             # model being run
                           x,                       # model input (or a tuple for multiple inputs)
                          EXPORT_PATH + "mnist.onnx", # where to save the model (can be a file or file-like object)
                           export_params=True)      # store the trained parameter weights inside the model file

现在我正在尝试将模型转换为 Tensorflow Lite 文件,以便可以在 Android 上进行推理。不幸的是,对于 Android 而言,PyTorch/Caffe2 支持相当缺乏或过于复杂,但 Tensorflow 似乎要简单得多。

ONNX 到 Tflite 的文档对此非常简单。

我尝试通过以下方式导出到 Tensorflow GraphDef 原型:

tf_rep.export_graph(EXPORT_PATH + 'mnist-test/mnist-tf-export.pb')

然后运行toco:

toco \
--graph_def_file=mnist-tf-export.pb \
--input_format=TENSORFLOW_GRAPHDEF \
--output_format=TFLITE \
--inference_type=FLOAT \
--input_type=FLOAT \
--input_arrays=0 \
--output_arrays=add_10 \
--input_shapes=1,3,28,28 \
--output_file=mnist.tflite`

当我这样做时,我收到以下错误:

File "anaconda3/lib/python3.6/site-packages/tensorflow/lite/python/convert.py", line 172, in toco_convert_protos
    "TOCO failed. See console for info.\n%s\n%s\n" % (stdout, stderr))
tensorflow.lite.python.convert.ConverterError: TOCO failed. See console for info.
2018-11-06 16:28:33.864889: I tensorflow/lite/toco/import_tensorflow.cc:1268] Converting unsupported operation: PyFunc
2018-11-06 16:28:33.874130: F tensorflow/lite/toco/import_tensorflow.cc:114] Check failed: attr.value_case() == AttrValue::kType (1 vs. 6)

此外,即使我运行命令时,我也不知道为 input_arrays 或 output_arrays 指定什么,因为模型最初是在 PyTorch 中构建的。

有没有人成功地将他们的 ONNX 模型转换为 TFlite?

这是我要转换的 ONNX 文件:https://drive.google.com/file/d/1sM4RpeBVqPNw1WeCROpKLdzbSJPWSK79/view?usp=sharing

额外信息

  • Python 3.6.6 :: Anaconda 自定义(64 位)
  • onnx.版本 = '1.3.0'
  • tf.版本 = '1.13.0-dev20181106'
  • torch.版本 = '1.0.0.dev20181029'

【问题讨论】:

  • 更新:不幸的是,对此没有很好的支持,我(此时/日期)建议采用 caffe2 路线或在 Tensorflow 中制作模型。
  • 正如您在评论中所说,PyTorch 现在封装了 Caffe2,因此您可以直接部署。
  • 现在您可以直接在手机上运行 PyTorch 模型。查看 PyTorch Mobile 的文档:pytorch.org/mobile/home

标签: tensorflow keras deep-learning pytorch onnx


【解决方案1】:

我认为您提供的 ONNX 文件(即model.onnx)已损坏,我不知道是什么问题,但它没有对 ONNX 运行时进行任何推断。

现在您可以直接在手机上运行 PyTorch 模型。查看 PyTorch Mobile 的文档here

此答案适用于 TensorFlow 版本 1,
对于 TensorFlow 版本 2 或更高版本,请点击 link

将模型从 protobuf freezeGraph 转换为 TFlite 的最佳方法是使用官方的 TensorFlow lite 转换器documentation

根据 TensorFlow Docs,TocoConverter 已被弃用

此类 (tf.compat.v1.lite.TocoConverter) 已被弃用。请改用 lite.TFLiteConverter。

从 PyTorch 转换为 ONNX 模型

将模型从 Pytorch 转换为 Onnx 的最佳实践是您应该添加以下参数来指定模型的输入和输出层的名称torch.onnx.export() 函数


# Export the model from PyTorch to ONNX
torch_out = torch.onnx._export(model,             # model being run
                                x,          # model input (or a tuple for multiple inputs)
                                EXPORT_PATH + "mnist.onnx",      # where to save the model (can be a file or file-like object)
                                export_params=True,       # store the trained parameter weights inside the model file
                                input_names=['main_input'],     # specify the name of input layer in onnx model
                                output_names=['main_output'])     # specify the name of input layer in onnx model

所以在你的情况下: 现在使用 onnx-tf 将此模型导出到 TensorFlow protobuf FreezeGraph

请注意,此方法仅在 tensorflow_version

从 ONNX 转换为 TensorFlow freezGraph

要转换模型,请从以下命令安装 onnx-tf 版本 1.5.0

pip install  onnx-tf==1.5.0

现在要将 .onnx 模型转换为 TensorFlow 冻结图,请在 shell 中运行以下命令

onnx-tf convert -i "mnist.onnx" -o  "mnist.pb"

从 TensorFlow FreezeGraph .pb 转换为 TF

现在要将此模型从 .pb 文件转换为 tflite 模型,请使用此代码

import tensorflow as tf
# make a converter object from the saved tensorflow file
converter = tf.lite.TFLiteConverter.from_frozen_graph('mnist.pb', #TensorFlow freezegraph .pb model file
                                                      input_arrays=['main_input'], # name of input arrays as defined in torch.onnx.export function before.
                                                      output_arrays=['main_output']  # name of output arrays defined in torch.onnx.export function before.
                                                      )
# tell converter which type of optimization techniques to use
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# to view the best option for optimization read documentation of tflite about optimization
# go to this link https://www.tensorflow.org/lite/guide/get_started#4_optimize_your_model_optional

# convert the model 
tf_lite_model = converter.convert()
# save the converted model 
open('mnist.tflite', 'wb').write(tf_lite_model)

要选择最适合您的模型用例优化的选项,请参阅有关 TensorFlow lite 优化的官方指南

https://www.tensorflow.org/lite/guide/get_started#4_optimize_your_model_optional

注意:您可以在 Google Colaboratory link

上试用我的 Jupyter Notebook 将 ONNX 模型转换为 Tensorflow Lite

【讨论】:

  • 我不能from onnx_tf.backend import prepare。你能告诉我你使用的 onnx、onnx_tf 和 tensorflow 的确切版本吗?投诉是import tensorflow_addons as tfa -> ModuleNotFoundError: No module named 'tensorflow_addons'
  • 似乎 onnx-tensorflow 的当前主分支适用于 TF >= 2.0。对于 TF tf-1.x 的分支
  • 导出为冻结图适用于上述分支,但在转换为 tflite 时我得到Unexpected value for attribute 'data_format'. Expected 'NHWC' Fatal Python error: Aborted
  • @aspiring1 和 mcExchane。感谢报告有关导入和“NHWC”错误的所有问题都已解决,并且我已经改进了我的代码。请再次查看过程答案已更新。再次注意现在我使用 PyPI 安装了 onnx-tf 1.5.0 版。并且 tensorflow 版本必须小于 2。我会尽快更新 tensorflow_version > 2。我还包括了 Google Colab Jupyter Notebook。试试看。
  • 感谢 Colab 代码。转换终于起作用了。然而,转换后的 tflite 模型似乎无法在智能手机上的 GPU 上运行。 CPU 模式有效,但看起来比直接在 TF 中构建的相应模型慢得多(~10 倍)。你有过类似的经历吗?
【解决方案2】:

现在您可以直接在手机上运行 PyTorch 模型。查看 PyTorch Mobile 的文档here

此答案适用于 TensorFlow 版本 2 或更高版本,
对于 TensorFlow 版本 1,请点击 here

将模型从 protobuf freezeGraph 转换为 TFlite 的最佳方法是使用官方的 TensorFlow lite 转换器documentation

根据 TensorFlow Docs,TocoConverter 已被弃用

此类 (tf.compat.v1.lite.TocoConverter) 已被弃用。请改用 lite.TFLiteConverter。

从 PyTorch 转换为 ONNX 模型

# Export the model from PyTorch to ONNX
torch_out = torch.onnx.export(model,             # model being run
                                x,          # model input (or a tuple for multiple inputs)
                                EXPORT_PATH + "mnist.onnx",      # where to save the model (can be a file or file-like object)
                                export_params=True,       # store the trained parameter weights inside the model file
)

所以在你的情况下: 现在使用 onnx-tf 将此模型导出到 TensorFlow protobuf FreezeGraph

从 ONNX 转换为 TensorFlow freezeGraph

通过以下命令转换模型安装onnx-tf

git clone https://github.com/onnx/onnx-tensorflow.git && cd onnx-tensorflow
pip install -e .

现在要将 .onnx 模型转换为 TensorFlow 冻结图,请在 shell 中运行以下命令

onnx-tf convert -i "mnist.onnx" -o  "mnist.pb"

从 TensorFlow FreezeGraph .pb 转换为 TF

现在要将此模型从 .pb 文件转换为 tflite 模型,请使用此代码

import tensorflow as tf
# make a converter object from the saved tensorflow file
converter = tf.lite.TFLiteConverter.from_saved_model('mnist.pb')
# tell converter which type of optimization techniques to use
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# to view the best option for optimization read documentation of tflite about optimization
# go to this link https://www.tensorflow.org/lite/guide/get_started#4_optimize_your_model_optional

# convert the model 
tf_lite_model = converter.convert()
# save the converted model 
open('mnist.tflite', 'wb').write(tf_lite_model)

要选择最适合您的模型用例优化的选项,请参阅有关 TensorFlow lite 优化的官方指南

https://www.tensorflow.org/lite/guide/get_started#4_optimize_your_model_optional

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2022-09-27
    • 2019-05-08
    • 2023-04-02
    • 2019-03-25
    相关资源
    最近更新 更多