如果均匀量化后的模型精度无法满足要求,则需要进行基于精度的自动量化或量化感知训练或手工调优。
均匀量化支持量化的层以及约束如下,量化示例请参见获取更多样例。
量化方式 |
支持的层类型 |
约束 |
备注 |
---|---|---|---|
均匀量化 |
MatMul |
transpose_a=False, transpose_b=False,adjoint_a=False,adjoint_b=False |
- |
BatchMatMul/BatchMatMulV2 |
adj_x=False,adj_y=False |
|
|
Conv2D |
- |
weight的输入来源不含有placeholder等可动态变化的节点,且weight的节点类型只能是const。 |
|
Conv3D |
dilation_d为1,dilation_h/dilation_w >= 1 |
||
DepthwiseConv2dNative |
- |
||
Conv2DBackpropInput |
dilation为1 |
||
AvgPool |
- |
- |
|
MaxPool |
只做tensor量化 |
- |
|
Add |
只做tensor量化 |
- |
均匀量化接口调用流程如图1所示。
其中数据集用于在TensorFlow环境中对模型进行推理时,测试量化数据的精度;校准集用来产生量化因子,保证精度。
本章节详细给出训练后量化的模板代码解析说明,通过解读该代码,用户可以详细了解AMCT的工作流程以及原理,方便用户基于已有模板代码进行修改,以便适配其他网络模型的量化。
用户可以参见mobilenet_v2获取本章节的sample示例代码。训练后量化主要包括如下几个步骤:
如下流程详细演示如何编写脚本调用AMCTAPI进行模型量化。
1 2 |
import amct_tensorflow as amct amct.set_logging_level(print_level='info', save_level='info') |
建议使用原始待量化的模型和测试集,在TensorFlow环境下推理,验证环境、推理脚本是否正常。
推荐执行该步骤,请确保原始模型可以完成推理且精度正常;执行该步骤时,可以使用部分测试集,减少运行时间。
1
|
user_do_inference(ori_model, test_data, test_iterations) |
1
|
ori_graph = user_load_graph() |
1 2 3 4 5 6 7 |
config_file = './tmp/config.json' skip_layers = [] batch_num = 1 amct.create_quant_config(config_file=config_file, graph=ori_graph, skip_layers=skip_layers, batch_num=batch_num) |
1 2 3 4 |
record_file = './tmp/record.txt' amct.quantize_model(graph=ori_graph, config_file=config_file, record_file=record_file) |
使用AMCT调用quantize_model接口对用户的原始TensorFlow模型进行图修改时,由于插入了searchN层导致尾层输出节点发生改变的场景,可以参见TensorFlow网络模型由于AMCT导致输出节点改变,如何通过修改量化脚本进行后续的量化动作进行处理。如果量化过程存在空tensor输入报错信息,请参见使用训练后量化进行量化时,量化过程存在空tensor输入报错信息进行处理。
1
|
user_do_inference(ori_graph, calibration_data, batch_num) |
若校准时提示“Invalid argument: You must feed a value for placeholder tensor **”,请参见校准时提示“Invalid argument: You must feed a value for placeholder tensor **”进行处理。
若校准过程中如果提示“xxx calculate scale failed”错误信息,请参见IFMR数据量化时,存在"inf或NaN值"或"xxx calculate scale failed",量化过程报错。
1 2 3 4 5 |
quant_model_path = './results/user_model' amct.save_model(pb_model='user_model.pb', outputs=['user_model_outputs0', 'user_model_outputs1'], record_file=record_file, save_path=quant_model_path) |
保存模型时提示“RuntimeError: cannot find shift_bit of layer ** in record_file”,则请参见保存模型时提示“RuntimeError: record_file is empty, no layers to be quantized”进行处理。
1 2 |
quant_model = './results/user_model_quantized.pb' user_do_inference(quant_model, test_data, test_iterations) |