这些天来,我试图跟踪一个错误的部署TF模型与TPU的支持。
我可以得到一个不支持TPU运行的模型,但一旦我启用量化,我就会迷路。
我的情况如下:
对于最后一点,我使用了TFLite转换器的Python。生成函数tflite模型的脚本是
import tensorflow as tf
graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']
converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.FLOAT
input_arrays = converter.get_input_arrays()
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
tflite_model = converter.convert()
open('model.tflite', 'wb').write(tflite_model)这告诉我,到目前为止,我的方法似乎还不错。现在,如果我想使用珊瑚TPU棒,我必须量化我的模型(我在培训期间考虑到这一点)。我所要做的就是修改我的转换器脚本。我想我得把它改成
import tensorflow as tf
graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']
converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.QUANTIZED_UINT8 ## Indicates TPU compatibility
input_arrays = converter.get_input_arrays()
converter.quantized_input_stats = {input_arrays[0]: (0., 1.)} ## mean, std_dev
converter.default_ranges_stats = (-128, 127) ## min, max values for quantization (?)
converter.allow_custom_ops = True ## not sure if this is needed
## REMOVED THE OPTIMIZATIONS ALTOGETHER TO MAKE IT WORK
tflite_model = converter.convert()
open('model.tflite', 'wb').write(tflite_model)这个tflite模型在加载解释器的Python时会产生结果,但我无法理解它们的含义。此外,没有关于如何选择均值、std_dev和min/max范围的文档(或者如果存在,则是隐藏的很好)。另外,在用edgetpu_compiler编译并部署它(用C++ API加载它)之后,我会收到一个错误:
INFO: Initialized TensorFlow Lite runtime.
ERROR: Failed to prepare for TPU. generic::failed_precondition: Custom op already assigned to a different TPU.
ERROR: Node number 0 (edgetpu-custom-op) failed to prepare.
Segmentation fault我想我在转换过程中遗漏了一个标志或什么东西。但是,由于这里也缺乏文档,所以我不能肯定。
简言之:
我非常感谢您的帮助和指导!
编辑:我用完整的测试代码打开了一个github问题。随便玩这个吧。
发布于 2019-12-21 14:49:00
您不应该需要手动设置量化状态。
你试过训练后的量化教程了吗?
基本上,他们设置了量化选项:
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8然后,他们将一个“有代表性的数据集”传递给转换器,以便转换器能够运行几批模型来收集必要的统计信息:
def representative_data_gen():
for input_value in mnist_ds.take(100):
yield [input_value]
converter.representative_dataset = representative_data_gen虽然有量化训练的选择,但训练后量化总是比较容易的.
https://stackoverflow.com/questions/57077974
复制相似问题