本节详细介绍训练后量化支持的量化层,接口调用流程和示例。
训练后量化支持量化的层以及约束如下,量化过程请参见样例列表。
支持的层类型 |
约束 |
备注 |
---|---|---|
MatMul:全连接层 |
transpose_a=False, transpose_b=False,adjoint_a=False,adjoint_b=False |
- |
BatchMatMul/BatchMatMulV2 |
adjoint_a=False,adjoint_b=False |
- |
Conv2D:卷积层 |
- |
weight的输入来源不含有placeholder等可动态变化的节点,且weight的节点类型只能是const。 |
DepthwiseConv2dNative:Depthwise卷积层 |
dilation=1 |
|
Conv2DBackpropInput:反卷积层 |
dilation=1 |
|
AvgPool:平均下采样层 |
- |
- |
训练后量化接口调用流程如图1所示:
其中数据集用于在NPU环境中对模型进行推理时,测试量化数据的精度;校准集用来产生量化因子,保证精度。
其中数据集用于在TensorFlow环境中对模型进行推理时,测试量化数据的精度;校准集用来产生量化因子,保证精度。
如果用户不使用场景1中的接口,而是用自己计算得到的量化因子以及TensorFlow原始模型,生成量化模型,则需要使用convert_model接口完成相关量化动作。
训练后量化主要包括如下几个步骤:
如下流程详细演示如何编写脚本调用AMCTAPI进行模型量化。
1 2 |
import amct_tensorflow as amct amct.set_logging_level(print_level="info", save_level="info") |
执行该步骤时,需要注意如下两点:
1
|
user_do_inference_on_npu(ori_model, test_data) |
1 2 |
ori_model = 'user_model.pb' ori_graph = user_load_graph(ori_model) |
1 2 3 4 5 |
config_file = './tmp/config.json' skip_layers = [] amct.create_quant_config_ascend(config_file=config_file, graph=ori_graph, skip_layers=skip_layers) |
1 2 3 4 5 6 7 |
record_file = './tmp/record.txt' user_model_outputs = ['user_model_outputs0', 'user_model_outputs1'] calibration_graph, calibration_outputs = amct.quantize_model_ascend( graph=ori_graph, config_file=config_file, record_file=record_file, outputs=user_model_outputs) |
1
|
user_do_inference_on_npu(calibration_graph, calibration_outputs, calibration_data) |
1 2 3 4 5 |
quant_model_path = './results/user_model' amct.save_model_ascend(pb_model=ori_model, outputs=user_model_outputs, record_file=record_file, save_path=quant_model_path) |
使用量化后仿真模型精度与2中的原始精度做对比,可以观察量化对精度的影响。
1 2 |
quant_model = './results/user_model_quantized.pb' user_do_inference_on_cpu(quant_model, test_data) |