Tensorflow 量化感知训练

Tensorflow Quantization Aware Training

我想量化 DenseNet 模型。我正在使用 Tensorflow 2.4。

import tensorflow_model_optimization as tfmot
model = tf.keras.applications.DenseNet121(include_top=True,weights=None,input_tensor=None,input_shape=None,pooling=None,classes=1000) 
quantize_model = tfmot.quantization.keras.quantize_model
model = quantize_model(model)

但我收到以下消息:

RuntimeError:图层 conv2_block1_0_bn: 不受支持。您可以通过将 tfmot.quantization.keras.QuantizeConfig 实例传递给 quantize_annotate_layer API.

来量化该层

有什么办法可以做到这一点。 我无法更改keras代码。

在您的情况下,您需要单独量化图层 BatchNormalization

如果您从 Quantization TF Guide 中看到下面的示例代码片段,DefaultDenseQuantizeConfig 用于处理此问题。希望本指南能帮助您解决这个问题。

quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer
quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model
quantize_scope = tfmot.quantization.keras.quantize_scope

class CustomLayer(tf.keras.layers.Dense):
  pass

model = quantize_annotate_model(tf.keras.Sequential([
   quantize_annotate_layer(CustomLayer(20, input_shape=(20,)), DefaultDenseQuantizeConfig()),
   tf.keras.layers.Flatten()
]))

# `quantize_apply` requires mentioning `DefaultDenseQuantizeConfig` with `quantize_scope`
# as well as the custom Keras layer.
with quantize_scope(
  {'DefaultDenseQuantizeConfig': DefaultDenseQuantizeConfig,
   'CustomLayer': CustomLayer}):
  # Use `quantize_apply` to actually make the model quantization aware.
  quant_aware_model = tfmot.quantization.keras.quantize_apply(model)

quant_aware_model.summary()