如何量化优化 tflite 模型的输入和输出

How to quantize inputs and outputs of optimized tflite model

我使用下面的代码生成一个量化的tflite模型

import tensorflow as tf

def representative_dataset_gen():
  for _ in range(num_calibration_steps):
    # Get sample input data as a numpy array in a method of your choosing.
    yield [input]

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset_gen
tflite_quant_model = converter.convert()

但根据post training quantization

The resulting model will be fully quantized but still take float input and output for convenience.

要为 Google Coral Edge TPU 编译 tflite 模型,我还需要量化输入和输出。

在模型中,我看到第一个网络层将浮点输入转换为 input_uint8,最后一层将 output_uint8 转换为浮点输出。 如何编辑 tflite 模型以去除第一个和最后一个浮动层?

我知道我可以在转换期间将输入和输出类型设置为 uint8,但这与任何优化都不兼容。唯一可用的选择是使用伪量化,这会导致错误的模型。

您可以通过将 inference_input_type 和 inference_output_type (https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/python/lite.py#L460-L476) 设置为 int8 来避免 float to int8 和 int8 float "quant/dequant" 操作。

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir
converter.optimizations = [tf.lite.Optimize.DEFAULT] 
converter.representative_dataset = representative_dataset
#The below 3 lines performs the input - output quantization
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model = converter.convert()