非均匀量化是指量化后的数据在某个数值空间中的分布是不均匀的。非均匀量化过程中,会根据待量化数据的概率分布来对均匀量化后的数据分布进一步进行根据目标压缩率(保留数值量/原始量化数值量)的聚类操作。相较于均匀量化,非均匀量化在进一步压缩数据信息量的基础上尽可能的保留高概率分布的数据信息,从而减小压缩后的数据信息丢失。
由于硬件约束,该版本不建议使用非均匀量化的功能,获取不到性能收益。
模型在昇腾AI处理器上推理时,可通过非均匀量化提高权重压缩率(需要与ATC工具配合,通过编译时使能权重压缩),降低权重传输开销,进一步提升推理性能。非均匀量化后,如果精度仿真模型在原始Caffe环境中推理精度不满足要求,可通过调整非均匀量化配置文件config.json中的参数来恢复模型精度,根据是否自动调整量化配置文件,非均匀量化又分为静态非均匀量化和自动非均匀量化。
详细量化示例请参见获取更多样例>resnet50>执行自动非均匀量化。
非均匀量化支持量化的层以及约束如下:
量化方式 |
支持的层类型 |
约束 |
---|---|---|
非均匀量化 |
Convolution:卷积层 |
dilation为1、group为1、filter维度为4 |
InnerProduct:全连接层 |
transpose属性为false,axis为1 |
非均匀量化接口调用流程如图1所示。非均匀量化不支持多个GPU同时运行。
下面以自动非均匀量化为例介绍主要流程,静态非均匀量化流程请参见均匀量化。
1 2 |
import amct_caffe as amct from amct_caffe.auto_nuq import AutoNuqEvaluatorBase |
1 2 3 4 5 |
class AutoNuqEvaluator(AutoNuqEvaluatorBase): # Auto Nuq Evaluator def __init__(self, evaluate_batch_num): super().__init__(self) self.evaluate_batch_num = evaluate_batch_num |
1 2 |
def eval_model(self, model_file, weights_file, batch_num): return do_benchmark_test(QUANT_ARGS, model_file, weights_file, batch_num) |
1 2 3 4 5 |
def is_satisfied(self, original_metric, new_metric): # the loss of top1 acc need to be less than 1% if (original_metric - new_metric) * 100 < 1: return True return False |
1 2 3 4 5 6 7 8 9 10 11 12 |
config_json_file = os.path.join(TMP, 'config.json') skip_layers = [] batch_num = 2 activation_offset = True # do weights calibration with non uniform quantize configure amct.create_quant_config( config_json_file, args.model_file, args.weights_file, skip_layers, batch_num, activation_offset, args.cfg_define) scale_offset_record_file = os.path.join(TMP, 'scale_offset_record.txt') result_path = os.path.join(RESULT, 'ResNet50') |
1 2 3 4 5 6 7 8 |
evaluator = AutoNuqEvaluator(args.iterations) amct.auto_nuq( args.model_file, args.weights_file, evaluator, config_json_file, scale_offset_record_file, result_path) |