首页 > 解决方案 > ValueError:未知层:AnchorBoxes 量化张量流

问题描述

我正在将量化应用于 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) 时,模型应该能够感知量化

描述当前行为
在自定义对象上引发错误

重现问题
要点的代码

标签: tensorflowquantizationquantization-aware-training

解决方案


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)

推荐阅读