如何在Python中实现TF-Lite推理

如何在Python中实现TF-Lite推理,python,tensorflow,tensorflow-lite,quantization-aware-training,Python,Tensorflow,Tensorflow Lite,Quantization Aware Training,出于研究目的,我试图了解TF Lite是如何进行推理的。我只对软件逻辑感兴趣 我正在使用TensorFlow 2.1和TensorFlow模型优化0.3.0 例如,我使用一个非常简单的完全连接的网络: tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28, 1)), tf.keras.layers.Dense(10, activation=None) ]) 我通过量化感知训练在mnist

出于研究目的,我试图了解TF Lite是如何进行推理的。我只对软件逻辑感兴趣

我正在使用TensorFlow 2.1和TensorFlow模型优化0.3.0

例如,我使用一个非常简单的完全连接的网络:

tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
    tf.keras.layers.Dense(10, activation=None)
])
我通过量化感知训练在mnist上训练网络

然后用TF Lite对网络进行量化:

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = data_generator(ds_train)
quantized_tflite_model = converter.convert()
为了确保我知道自己在做什么,我做了三件事: 我使用TF从32位模型获得输出。 我使用TF Lite从量化模型中获取输出。 我用Python实现了32位模型的前向传递,并将其输出与前两个模型进行了比较

现在我试图理解如何实现量化模型的前向传递

使用解释器.get_tensor_details(),我得到以下输出:

{'name': 'Identity', 'index': 0, 'shape': array([ 1, 10]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}
{'name': 'flatten_input_int8', 'index': 1, 'shape': array([ 1, 28, 28,  1]), 'dtype': <class 'numpy.int8'>, 'quantization': (0.003921568859368563, -128)}
{'name': 'sequential/quant_dense/BiasAdd', 'index': 2, 'shape': array([ 1, 10]), 'dtype': <class 'numpy.int8'>, 'quantization': (0.22868551313877106, 49)}
{'name': 'sequential/quant_dense/LastValueQuant/FakeQuantWithMinMaxVars/transpose', 'index': 3, 'shape': array([ 10, 784]), 'dtype': <class 'numpy.int8'>, 'quantization': (0.01087072491645813, 0)}
{'name': 'sequential/quant_dense/MatMul_bias', 'index': 4, 'shape': array([10]), 'dtype': <class 'numpy.int32'>, 'quantization': (4.263029768480919e-05, 0)}
{'name': 'sequential/quant_dense/BiasAdd_float', 'index': 5, 'shape': array([ 1, 10]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}
{'name': 'flatten_input', 'index': 6, 'shape': array([ 1, 28, 28,  1]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}
函数quantize_multiplier_minor_than_one是我对C函数的Python实现:

所以我的问题是,这是正确的方法吗? 我肯定错过了一些计算,是什么? 而且,当我有一个更大的网络时,我如何知道如何系统地使用正确的索引来提取每个层的量化参数


非常感谢您的建议。

最后,我通过深入研究TensorFlow/Lite代码解决了这个问题。 我找到了相关代码并对其进行了修改,因此它将我需要的所有相关信息打印到文本文件中。从那个里,我可以解析Python中的所有内容,并运行Python版本的cpp逻辑

如果有人想尝试同样的方法,为了构建CPP解决方案,请转到

示例应用程序的入口点如下:

例如,卷积参考码如下:


享受(不是真的)

最后,我通过深入研究TensorFlow/Lite代码解决了这个问题。 我找到了相关代码并对其进行了修改,因此它将我需要的所有相关信息打印到文本文件中。从那个里,我可以解析Python中的所有内容,并运行Python版本的cpp逻辑

如果有人想尝试同样的方法,为了构建CPP解决方案,请转到

示例应用程序的入口点如下:

例如,卷积参考码如下:

享受(不是真的)

def quantization_params(index):
    return tensor_details[index]['quantization'][0], tensor_details[index]['quantization'][1]

image = get_single_test_image(show_image=False)

# #### Convert input image from float32 to int8 ####

q_scale, q_zero = quantization_params(index=1)
x = image / q_scale + q_zero

# #### Flatten input ####

x = x.flatten()

# #### Dense layer ####

kernel, bias = tflite_model.interpreter.get_tensor(3), tflite_model.interpreter.get_tensor(4)
s_input, z_input = quantization_params(index=1)
s_kernel, z_kernel = quantization_params(index=3)
s_output, z_output = quantization_params(index=4)

M = s_input * s_kernel
quantized_multiplier, right_shift = quantize_multiplier_smaller_than_one(M)

dense_output = np.zeros((kernel.shape[0],), dtype=np.int32)

for i in range(dense_output.shape[0]):
    for j in range(kernel.shape[1]):
        dense_output[i] += int((x[j] + z_input) * (kernel[i, j] + z_kernel))

x = dense_output + bias

x = np.right_shift(x * quantized_multiplier, right_shift)