我想知道在Tensorflow 2中,在量化感知训练期间模拟BatchNorm折叠的当前可用选项是什么。Tensorflow 1有tf.contrib.quantize.create_training_graph
函数,它将FakeQuantization层插入到图形中,并负责模拟批归一化折叠(根据这篇white paper)。
Tensorflow 2在其最近采用的tf.keras
API中有一个tutorial,介绍如何在其中使用量化,但他们没有提及任何关于批归一化的内容。我尝试了以下带有BatchNorm层的简单示例:
import tensorflow_model_optimization as tfmo
model = tf.keras.Sequential([
l.Conv2D(32, 5, padding='same', activation='relu', input_shape=input_shape),
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.Conv2D(64, 5, padding='same', activation='relu'),
l.BatchNormalization(), # BN!
l.MaxPooling2D((2, 2), (2, 2), padding='same'),
l.Flatten(),
l.Dense(1024, activation='relu'),
l.Dropout(0.4),
l.Dense(num_classes),
l.Softmax(),
])
model = tfmo.quantization.keras.quantize_model(model)
然而,它会产生以下异常:
RuntimeError: Layer batch_normalization:<class 'tensorflow.python.keras.layers.normalization.BatchNormalization'> is not supported. You can quantize this layer by passing a `tfmot.quantization.keras.QuantizeConfig` instance to the `quantize_annotate_layer` API.
这表明TF不知道如何处理它。
我还看到了这个相关主题,他们在keras构建的模型上应用了
tf.contrib.quantize.create_training_graph
。 但是他们没有使用BatchNorm层,所以我不确定这是否有效。那么,在TF2中如何使用BatchNorm折叠功能的选项是什么? 这可以通过keras API完成,还是应该切换回TensorFlow 1 API并以旧方式定义图形?