ValueError: Unknown layer: AnchorBoxes quantization tensorflow

ValueError: Unknown layer: AnchorBoxes quantization tensorflow

我正在对 SSD 模型应用量化。附上要点。加载模型时添加了一个名为“AnchorBoxes”的自定义对象。当我不进行量化时,这很好用。但是当我应用量化时,这个自定义对象无法识别。

我尝试了变通方法。

def apply_quantization_to_conv2D(layer):
  #print(layer)
  if isinstance(layer, tf.keras.layers.Conv2D):
    return tfmot.quantization.keras.quantize_annotate_layer(layer)
  return layer

# Use `tf.keras.models.clone_model` to apply `apply_quantization_to_dense` 
# to the layers of the model.
annotated_model = tf.keras.models.clone_model(
    model,
    clone_function=apply_quantization_to_conv2D,
)

#annotated_model.save('quantize_ready_model_20_01_Conv2D.h5', include_optimizer=True)
annotated_model.summary()
# Now that the Dense layers are annotated,
# `quantize_apply` actually makes the model quantization aware.



#quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)

我在上面的代码中注释了这一行 quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model),因为它抛出了错误 ValueError: Unknown layer: AnchorBoxes

相反,我在对 Conv2D 层应用量化后保存了模型,如下所示

def apply_quantization_to_conv2D(layer):
  #print(layer)
  if isinstance(layer, tf.keras.layers.Conv2D):
    return tfmot.quantization.keras.quantize_annotate_layer(layer)
  return layer

# Use `tf.keras.models.clone_model` to apply `apply_quantization_to_dense` 
# to the layers of the model.
annotated_model = tf.keras.models.clone_model(
    model,
    clone_function=apply_quantization_to_conv2D,
)


annotated_model.summary()

annotated_model.save('quantize_ready_model_20_01_Conv2D_1.h5', include_optimizer=True)
# Now that the Dense layers are annotated,
# `quantize_apply` actually makes the model quantization aware.



#quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
#quant_aware_model.compile(optimizer=adam, loss=ssd_loss.compute_loss)
#quant_aware_model.summary()

然后我加载了模型,希望加载的量化模型如下所示将附加 custom_objects。

with tfmot.quantization.keras.quantize_scope():
    loaded_model = tf.keras.models.load_model('./quantize_ready_model_20_01_Conv2D_1.h5', custom_objects={'AnchorBoxes': AnchorBoxes})

最后,我将 quantize_apply 应用于具有量化层的新 loaded_model

quant_aware_model = tfmot.quantization.keras.quantize_apply(loaded_model)

这又导致了同样的错误

ValueError: Unknown layer: AnchorBoxes

系统信息

TensorFlow 版本(从源代码或二进制安装):TF 2.0.0

TensorFlow 模型优化版本(从源代码或二进制安装):0.5.0

描述预期行为
当我 运行 quantize_apply(model) 时,模型应该变得有量化意识

描述当前行为
在自定义对象上抛出错误

重现问题的代码
gist

在下面的代码中像这样 AnchorBoxes': AnchorBoxes 传递自定义层后问题已解决。

with quantize_scope(
  {'DefaultDenseQuantizeConfig': DefaultDenseQuantizeConfig,
   'AnchorBoxes': AnchorBoxes}):
  # Use `quantize_apply` to actually make the model quantization aware.
  quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)