本节详细介绍量化感知训练支持的量化层,接口调用流程和示例。
INT4量化只有Atlas 推理系列产品(Ascend 310P处理器)支持。
量化感知训练根据量化后低比特位宽大小分为INT8量化和INT4量化,具体使用哪种量化方式,由量化感知训练简易配置文件说明中的dst_type参数控制。量化示例请参见获取更多样例>resnet101。
量化感知训练当前仅支持对FP32数据类型的网络模型进行量化。用户可以根据实际情况选择进行INT8量化还是INT4量化。量化感知训练支持量化的层以及约束如下:
支持的层类型 |
约束 |
备注 |
---|---|---|
torch.nn.Linear |
- |
|
torch.nn.Conv2d |
|
|
torch.nn.ConvTranspose2d |
|
量化感知训练接口调用流程如图1所示。
如果训练过程中断,则可基于保存的pth模型参数和量化配置文件,重新调用restore_quant_retrain_model接口,输出修改后的retrain network,继续进行量化感知的训练,然后进行推理。
1
|
import amct_pytorch as amct |
推荐执行该步骤,请确保原始模型可以完成推理且精度正常;执行该步骤时,可以使用部分测试集,减少运行时间。
1 2 3 |
ori_model.load() # 测试模型 user_test_model(ori_model, test_data, test_iterations) |
实现该步骤前,应先恢复训练好的参数,如2中的ori_model.load()。
1 2 3 4 5 6 |
config_file = './tmp/config.json' simple_cfg = './retrain.cfg' amct.create_quant_retrain_config(config_file=config_file, model=ori_model, input_data=ori_model_input_data, config_defination=simple_cfg) |
1
|
optimizer = user_create_optimizer(quant_retrain_model) |
注意:从训练好的checkpoint恢复模型参数后再训练;训练中保存的参数应该包括量化因子。
1 2 |
quant_pth = './ckpt/user_model' user_train_model(optimizer, quant_retrain_model, train_data) |
1
|
user_infer_graph(quant_retrain_model) |
1 2 3 4 5 6 |
quant_model_path = './result/user_model' amct.save_quant_retrain_model(config_file=config_file, model=quant_retrain_model, record_file=record_file, save_path=quant_model_path, input_data=ori_model_input_data) |
使用量化后仿真模型精度与2中的原始精度做对比,可以观察量化对精度的影响。
1 2 |
quant_model = './results/user_model_fake_quant_model.onnx' user_do_inference_onnx(quant_model, test_data, test_iterations) |
如果训练过程中断,需要从ckpt中恢复数据,继续训练,则调用流程为:
1
|
import amct_pytorch as amct |
1
|
ori_model= user_create_model() |
1 2 3 4 5 6 7 8 9 |
config_file = './tmp/config.json' simple_cfg = './retrain.cfg' record_file = './tmp/record.txt' quant_pth_file = './ckpt/user_model_newest.ckpt' quant_retrain_model = amct.restore_quant_retrain_model(config_file=config_file, model=ori_model, record_file=record_file, input_data=ori_model_input_data, pth_file=quant_pth_file) |
1
|
optimizer = user_create_optimizer(retrain_model) |
注意:从训练好的checkpoint恢复模型参数后再训练;训练中保存的参数应该包括量化因子。
1
|
user_train_model(optimizer, retrain_model, train_data) |
1
|
user_infer_graph(train_graph, retrain_ops[-1].output_tensor) |
1 2 3 4 5 6 |
quant_model_path = './result/user_model' amct.save_quant_retrain_model(config_file=config_file, model=ori_model, record_file=record_file, save_path=quant_model_path, input_data=ori_model_input_data) |
使用量化后仿真模型精度与2中的原始精度做对比,可以观察量化对精度的影响。
1 2 |
quant_model = './results/user_model_fake_quant_model.onnx' user_do_inference_onnx(quant_model, test_data, test_iterations) |