通过数据均衡预处理接口计算出均衡因子,将模型数据与权重进行数学等价换算,均衡模型数据与权重的分布,将数据的量化难度迁移一部分至权重,从而降低量化误差。该特性支持的层及约束如下:
支持的层类型 |
约束 |
备注 |
---|---|---|
MatMul |
transpose_a=False, transpose_b=False,adjoint_a=False,adjoint_b=False |
weight的输入来源不含有placeholder等可动态变化的节点,且weight的节点类型只能是const。 |
Conv2D |
- |
|
Conv3D |
dilation_d为1,dilation_h/dilation_w >= 1 |
|
DepthwiseConv2dNative |
dilation为1 |
|
Conv2DBackpropInput |
dilation为1 |
均衡预处理接口调用流程如图1所示。
其中数据集用于在TensorFlow环境中对模型进行推理时,测试量化数据的精度;校准集用来产生均衡因子,保证精度。
本章节详细给出量化数据均衡预处理的模板代码解析说明,通过解读该代码,用户可以详细了解AMCT的工作流程以及原理,方便用户基于已有模板代码进行修改,以便适配其他网络模型。
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_preprocess(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 **”进行处理。
1 2 3 4 |
ori_graph = user_load_graph() 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 **”进行处理。
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) |