基于精度的自动量化是为了方便用户在对量化精度有一定要求时所使用的功能。该方法能够在保证用户所需的模型精度前提下,自动搜索模型的量化配置并执行训练后量化的流程,最终生成满足精度要求的量化模型。
基于精度的自动量化基本原理与手工量化相同,但是用户无需手动调整量化配置文件,大大简化了优化流程,提高量化效率。量化示例请参见获取更多样例>mobilenetV2。
接口调用流程如图1所示。
主要流程如下:
该过程还会调用accuracy_based_auto_calibration中的量化策略strategy模块,输出初始化的quant config量化配置文件,该文件记录所有层都可以进行量化。
accuracy_based_auto_calibration接口内部基于精度的自动量化流程如图2所示。
本示例演示使用AMCT进行基于精度的自动量化流程。该过程需要用户实现一个模型推理得到精度的回调函数,由于AMCT需要基于回调函数返回的精度数据进行量化层的筛选,因此回调函数的返回数值应尽可能反映模型的精度。
1 2 3 |
import os import amct_caffe as amct from amct_caffe.common.auto_calibration import AutoCalibrationEvaluatorBase |
上述回调函数的入参要和基类AutoCalibrationEvaluatorBase保持一致。其中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 |
1 2 |
model_file = os.path.realpath(user_model_file) weights_file = os.path.realpath(user_weights_file) |
1 2 3 4 5 6 7 8 9 |
config_json_file = './config.json' skip_layers = [] batch_num = 1 activation_offset = True amct.create_quant_config(config_json_file, model_file, weights_file, skip_layers, batch_num, activation_offset) scale_offset_record_file = os.path.join(TMP, 'scale_offset_record.txt') result_path = os.path.join(RESULT, 'model') |
1
|
evaluator = AutoCalibrationEvaluator() |
1 2 3 4 5 6 7 |
amct.accuracy_based_auto_calibration( model_file, weights_file, evaluator, config_json_file, scale_offset_record_file, result_path) |