均匀量化是指量化后的数据比较均匀地分布在某个数值空间中,例如INT8量化就是用只有8比特的INT8数据来表示32比特的FP32数据或16比特的FP16数据,将FP32/FP16的卷积运算过程(乘加运算)转换为INT8的卷积运算,加速运算和实现模型压缩;均匀的INT8量化则是量化后数据比较均匀地分布在INT8的数值空间[-128, 127]中。
如果均匀量化后的模型精度无法满足要求,则需要进行基于精度的自动量化或量化感知训练或手工调优。均匀量化支持量化的层以及约束如下,量化示例请参见样例列表。
支持的层类型 |
约束 |
备注 |
---|---|---|
torch.nn.Linear |
- |
复用层(共用weight和bias参数)不支持量化。 |
torch.nn.Conv2d |
|
|
torch.nn.Conv3d |
|
|
torch.nn.ConvTranspose2d |
|
|
torch.nn.AvgPool2d |
- |
- |
均匀量化接口调用流程如图1所示。
训练后量化主要包括如下几个步骤:
1
|
import amct_pytorch as amct |
建议使用原始待量化的模型和测试集,在PyTorch环境下推理,验证环境、推理脚本是否正常。
推荐执行该步骤,请确保原始模型可以完成推理且精度正常;执行该步骤时,可以使用部分测试集,减少运行时间。
1
|
user_do_inference_torch(ori_model, test_data, test_iterations) |
1 2 3 4 5 6 7 8 |
config_file = './tmp/config.json' skip_layers = [] batch_num = 1 amct.create_quant_config(config_file=config_file, model=ori_model, input_data=ori_model_input_data, skip_layers=skip_layers, batch_num=batch_num) |
1 2 3 4 5 6 7 |
record_file = './tmp/record.txt' modified_onnx_model = './tmp/modified_model.onnx' calibration_model = amct.quantize_model(config_file=config_file, modified_onnx_model=modified_onnx_model, record_file=record_file, model=ori_model, input_data=ori_model_input_data) |
校准过程中如果提示[IFMR]: Do layer xxx data calibration failed!错误信息,则请参见校准执行过程中提示“[IFMR]: Do layer xxx data calibration failed!”解决。
1
|
user_do_inference_torch(calibration_model, calibration_data, batch_num) |
1 2 3 4 |
quant_model_path = './results/user_model' amct.save_model(modified_onnx_file=modified_onnx_file, record_file=record_file, save_path=quant_model_path) |
1 2 |
quant_model = './results/user_model_fake_quant_model.onnx' user_do_inference_onnx(quant_model, test_data, test_iterations) |