均匀量化支持量化的层以及约束如下,量化示例请参见获取更多样例>resnet101。
量化方式 |
支持的层类型 |
约束 |
---|---|---|
均匀量化 |
Conv:卷积层 |
支持4维或5维输入场景下的量化 |
Gemm:广义矩阵乘 |
transpose_a=false,Alpha=Beta=1.0 |
|
MatMul:全连接层 |
当权重维度为2时,才支持量化 |
|
ConvTranspose:转置卷积层 |
仅支持4维输入场景下的量化 |
|
AveragePool:平均池化层 |
仅支持4维输入场景下的量化 |
|
MaxPool:最大池化层 |
只做tensor量化 |
|
Add:按元素求和层 |
只做tensor量化 |
均匀量化接口调用流程如图1所示:
本章节详细给出训练后量化的模板代码解析说明,通过解读该代码,用户可以详细了解AMCT的工作流程以及原理,方便用户基于已有模板代码进行修改,以便适配其他网络模型的量化。
用户可以参见resnet-101获取本章节的sample示例代码。训练后量化主要包括如下几个步骤:
如下流程详细演示如何编写脚本调用AMCTAPI进行模型量化。
1
|
import amct_onnx as amct |
建议使用原始待量化的模型和测试集,在ONNX Runtime环境下推理,验证环境、推理脚本是否正常。
推荐执行该步骤,请确保原始模型可以完成推理且精度正常;执行该步骤时,可以使用部分测试集,减少运行时间。
1
|
user_do_inference(ori_model, test_data, test_iterations) |
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, model_file=ori_model, skip_layers=skip_layers, batch_num=batch_num) |
1 2 3 4 5 6 |
record_file = './tmp/record.txt' modified_model = './tmp/modified_model.onnx' amct.quantize_model(config_file=config_file, ori_model=ori_model, modified_onnx_file=modified_model, record_file=record_file) |
若校准过程中有错误信息,则可以尝试参见校准过程中提示"IFMR node. Name:'layer_ifmr_op' Status Message: std::bad_alloc "信息或校准过程中出现"killed"信息进行处理。
1
|
user_do_inference(modified_onnx_file, calibration_data, batch_num) |
1 2 3 4 |
quant_model_path = './results/user_model' amct.save_model(modified_onnx_file=modified_model, record_file=record_file, save_path=quant_model_path) |
1 2 |
quant_model = './results/user_model_fake_quant_model.onnx' user_do_inference(quant_model, test_data, test_iterations) |