基于精度的自动量化是为了方便用户在对量化精度有一定要求时所使用的功能。该方法能够在保证用户所需的模型精度前提下,自动搜索模型的量化配置并执行训练后量化的流程,最终生成满足精度要求的量化模型。
基于精度的自动量化基本原理与基础量化相同,但是用户无需手动调整量化配置文件,大大简化了优化流程,提高量化效率。量化示例请参见获取更多样例>mobilenetv2。
接口调用流程如图1所示。
主要流程如下:
该过程还会调用accuracy_based_auto_calibration中的量化策略strategy模块,输出初始化的quant config量化配置文件,该文件记录所有层都可以进行量化。
accuracy_based_auto_calibration接口内部基于精度的自动量化流程如图2所示。
本示例演示使用AMCT进行基于精度的自动量化流程。该过程需要用户实现一个模型推理得到精度的回调函数,由于AMCT需要基于回调函数返回的精度数据进行量化层的筛选,因此回调函数的返回数值应尽可能反映模型的精度。
import os import amct_pytorch as amct from amct_pytorch.common.auto_calibration import AutoCalibrationEvaluatorBase
上述回调函数的入参要和基类AutoCalibrationEvaluatorBase保持一致。其中:
class ModelEvaluator(AutoCalibrationEvaluatorBase): # The evaluator for model def __init__(self, *args, **kwargs): # 成员变量初始化 # 设置预期精度损失,此处请替换为具体的数值 self.diff = expected_acc_loss pass def calibration(self, model_file, weights_file): # 进行模型的校准推理,推理的batch数要和量化配置的batch_num一致 pass def evaluate(self, model_file, weights_file): # evaluate the input models, get the eval metric of model pass def metric_eval(self, original_metric, new_metric): # 评估原始模型精度和量化模型精度的精度损失是否满足预期,满足返回True, 精度损失数据;否则返回False, 精度损失数据 loss = original_metric - new_metric if loss < self.diff: return True, loss return False, loss
model = MyNet()
config_json_file = './config.json' skip_layers = [] batch_num = 1 amct.create_quant_config(config_json_file, model, input_data, skip_layers, batch_num) scale_offset_record_file = os.path.join(TMP, 'scale_offset_record.txt') result_path = os.path.join(RESULT, 'model')
evaluator = AutoCalibrationEvaluator()
amct.accuracy_based_auto_calibration( model=model, model_evaluator=evaluator, config_file=config_json_file, record_file=record_file, save_dir=result_path, input_data=input_data, input_names=['input'], output_names=['output'], dynamic_axes={ 'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} }, strategy='BinarySearch', sensitivity='CosineSimilarity' )