前提条件
已安装AMCT工具包。详情请参见工具安装。
解析代码
训练后量化主要包括如下几个步骤:
- 准备训练好的模型和数据集。
- 在原始TensorFlow环境中验证模型精度以及环境是否正常。
- 编写训练后量化脚本调用AMCTAPI。
- 执行训练后量化脚本。
- 在原始TensorFlow环境中验证量化后仿真模型精度。
如下流程详细演示如何编写脚本调用AMCTAPI进行模型量化。
- 如下示例标有“由用户补充处理”的步骤,需要用户根据自己的模型和数据集进行补充处理,示例中仅为示例代码。
- 如下示例调用AMCT的部分,函数入参请根据实际情况进行调整。
- 导入AMCT包,调用set_logging_level接口设置日志级别。
| import amct_tensorflow as amct
amct.set_logging_level(print_level="info", save_level="info")
|
- (可选,由用户补充处理)建议使用原始待量化的模型和测试集,基于TensorFlow在NPU环境下在线推理,验证环境、推理脚本是否正常。
执行该步骤时,需要注意如下两点:
- 推荐执行该步骤,确保原始模型可以在NPU完成推理且精度正常,如果该步骤无法完成,则将无法进行量化操作;如果该步骤的推理精度不满足要求,则后续量化精度结果将不可信。
- 执行该步骤时,可以使用部分测试集,减少运行时间。
| user_do_inference_on_npu(ori_model, test_data)
|
- (由用户补充处理)根据原始模型user_model.pb,准备好图结构tf.Graph。
| ori_model = 'user_model.pb'
ori_graph = user_load_graph(ori_model)
|
- 调用AMCT,量化模型。
- 生成量化配置。
| config_file = './tmp/config.json'
skip_layers = []
amct.create_quant_config_ascend(config_file=config_file,
graph=ori_graph,
skip_layers=skip_layers)
|
- 修改图,在图中插入量化相关的算子。
| 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)
|
- (由用户补充处理)使用修改后的图在校准集上做在线推理,找到量化因子。
该步骤执行时,需要注意如下两点:
- 校准集及其预处理过程数据要与模型匹配,以保证量化的精度。
- 量化后图的calibration_graph输出为calibration_outputs,在线推理时都要执行。
| user_do_inference_on_npu(calibration_graph, calibration_outputs, calibration_data)
|
- 保存模型。
| 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)
|
- (可选,由用户补充处理)使用量化后模型user_model_quantized.pb和测试集,在TensorFlow CPU环境下推理,测试量化后的仿真模型精度。
使用量化后仿真模型精度与2中的原始精度做对比,可以观察量化对精度的影响。
| quant_model = './results/user_model_quantized.pb'
user_do_inference_on_cpu(quant_model, test_data)
|
运行样例
参见获取的样例代码中的README,按照步骤执行训练后量化相关操作。