PPQ库中KLD算法实现代码解析
创始人
2024-05-29 12:13:06
0

PPQ量化工具库KLD算法解析

  • 前言
  • PPQ算法实现
    • NVIDIA的PPT中KLD算法流程
    • KLD算法PPQ实现版本
    • PPQ与NVIDIA的区别:

前言

这是对PPQ库中KLD算法实现代码解析,关于PPQ库安装与使用详情见专栏上一篇博客。

PPQ算法实现

nvidia发布的PPT:8-bit Inference with TensorRT,百度可下载。下两图是KLD算法的实现伪代码:
在这里插入图片描述
在这里插入图片描述
下图是PPQ算法的实现过程:见https://github.com/openppl-public/ppq/blob/master/ppq/quantization/observer/range.py

def hist_to_scale_offset(self, histogram: torch.Tensor, hist_bins: int, hist_scale: float,config: TensorQuantizationConfig, computing_device: str = OBSERVER_KL_COMPUTING_DEVICE,scale_threshold: float=OBSERVER_MIN_SCALE) -> Tuple[float, int]:"""PPQ core quant parameter computing method - Histogram to scale & offsetWith a pre-defined histogram,this function will automatically search best clip valueto minimize KL divergence between quantized result and fp32 input.only work for per-tensor symmetrical quantization policy for now.see also https://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdfArgs:histogram (torch.Tensor): histogram records activation's statistics.hist_bins (int): how many bins are included in histogram(also known as histogram length)hist_scale (float): histogram step size. it can be solved by histogram.max_val / histogram.binsconfig (TensorQuantizationConfig): quantization config.computing_device (str, optional): computing device. Defaults to 'cpu'.Raises:ValueError: given quantization config is invalid.Returns:Tuple[float, int]: scale(fp32) and offset(int)."""if config.policy.has_property(QuantizationProperty.ASYMMETRICAL):raise PermissionError('KL observer is not designed for ASYMMETRICAL quantization')if OBSERVER_MIN_SCALE_MANUL_OVERRIDE in config.detail:scale_threshold = config.detail[OBSERVER_MIN_SCALE_MANUL_OVERRIDE]# move histogram to cpu, speedup computation.histogram = histogram.to(computing_device).float()# compute symmtrical kl-divergence.# Here is a simple example: reference distribution P consisting of 8 bins, we want to quantize into 2 bins:# P = [ 1, 0, 2, 3, 5, 3, 1, 7]# we merge into 2 bins (8 / 2 = 4 consecutive bins are merged into one bin)# [1 + 0 + 2 + 3 , 5 + 3 + 1 + 7] = [6, 16]# then proportionally expand back to 8 bins, we preserve empty bins from the original distribution P:# Q = [ 6/3, 0, 6/3, 6/3, 16/4, 16/4, 16/4, 16/4] = [ 2, 0, 2, 2, 4, 4, 4, 4]# now we should normalize both distributions, after that we can compute KL_divergence# P /= sum(P) Q /= sum(Q)# result = KL_divergence(P, Q)# see also# https://github.com/NVIDIA/TensorRT/blob/3835424af081db4dc8cfa3ff3c9f4a8b89844421/tools/pytorch-quantization/pytorch_quantization/calib/histogram.py#L147losses, quant_bins = [], 2 ** (config.num_of_bits - 1)# following code is curcial, do not movehistogram[: int(hist_bins * .002)] = 0histogram[int(hist_bins * .002)] = 1hist_sum = torch.sum(histogram)for bin_range in range(quant_bins, hist_bins + quant_bins - 1, quant_bins):p_hist = torch.zeros(size=(bin_range, ), dtype=torch.float, device=computing_device)p_hist[: bin_range].copy_(histogram[: bin_range])p_hist[bin_range - 1] += torch.sum(histogram[bin_range: ])p_hist = p_hist / hist_sumexpand_ratio = int(bin_range / quant_bins)q_hist = histogram[: bin_range].clone()q_hist = q_hist.reshape((quant_bins, expand_ratio))positive_map = q_hist > 0positive_cnt = positive_map.sum(axis=1, keepdim=True)positive_cnt[positive_cnt == 0] = 1q_hist = torch.div(q_hist.sum(axis=1, keepdim=True), positive_cnt)q_hist = q_hist.repeat([1, expand_ratio])q_hist = q_hist * positive_mapq_hist = q_hist / torch.sum(q_hist)q_hist = q_hist.flatten()losses.append({'kl': torch_KL_divergence(p_hist, q_hist),'bin_range': bin_range})best_bin_range = sorted(losses, key=lambda x: x['kl'])[0]['bin_range']scale, offset = (best_bin_range / self._hist_bins) * hist_scale * (self._hist_bins / quant_bins), 0if scale < scale_threshold and OBSERVER_WARNING: ppq_warning('Numeric instability detected: ''ppq find there is a scale value < 1e-7, ''which probably cause numeric underflow in further computation.')scale = max(scale, scale_threshold)if config.policy.has_property(QuantizationProperty.POWER_OF_2):scale = ppq_round_to_power_of_2(scale, policy=RoundingPolicy.ROUND_HALF_UP)return scale, offset

NVIDIA的PPT中KLD算法流程

整个过程:从128循环到2048,i为截断阈值将bin截断(第i个条形图也会被舍弃),生成P和Q,计算每组P和Q的KL散度,最小散度对应阈值即为所求
输入Input:一个有2048个统计条条形图bin
输出:截断阈值threshhold,浮点数
在这里插入图片描述
在这里插入图片描述

KLD算法PPQ实现版本

算法流程:
在这里插入图片描述
具体代码分析:
在这里插入图片描述

PPQ与NVIDIA的区别:

1.原始histogram条形图舍弃
NVIDIA是:不进行预处理
PPQ:前其千分之二置为零,第千分之二个条形置为1
2.for循环找截断阈值
NVIDIA是:for i in range(102,2048)
PPQ库是:for bin_range in range(quant_bins, hist_bins + quant_bins - 1, quant_bins):
3.阈值m转为实际浮点数
NVIDIA是:threshold = ( m + 0.5 ) * ( width of a bin )
PPQ库是:
在这里插入图片描述

相关内容

热门资讯

安卓平板系统升级关闭,揭秘操作... 亲爱的安卓平板用户们,你们是不是也遇到了这样的烦恼:每次系统升级,都要忍受漫长的等待,甚至有时候升级...
安卓系统怎么修改密码,轻松掌握... 手机里的安卓系统密码忘记了?别急,让我来给你支个招,让你轻松修改密码,重获手机自由! 一、解锁密码的...
优酷对安卓系统要求,揭秘安卓系... 你有没有发现,最近优酷的视频越来越高清了?是不是觉得看视频的体验提升了不少?不过,你知道吗?想要享受...
安卓两个系统切换系统,畅享多系... 你有没有想过,你的安卓手机里竟然可以藏着两个完全不同的系统呢?没错,就是那种一个系统用来工作,另一个...
苹果跟安卓的系统区别 你有没有发现,手机的世界里,苹果和安卓就像是两个截然不同的星球?它们各有各的特色,各有各的粉丝,今天...
安卓系统360抢红包,安卓系统... 你有没有发现,现在不管是聚会还是日常,抢红包已经成了大家不可或缺的娱乐活动呢!而在这其中,安卓系统的...
安卓系统手机wifi连不上wi... 亲爱的手机控们,你是否也有过这样的烦恼:明明家里WiFi信号满格,可就是连不上手机?别急,今天就来帮...
16s安卓系统,创新与变革的科... 你有没有发现,最近你的手机是不是变得越来越流畅了?没错,我要说的就是那个让无数安卓用户心动的16s安...
一加三安卓8.0系统,畅享智能... 你有没有听说最近手机圈里的一股新潮流?那就是一加三安卓8.0系统!这可不是什么小打小闹的更新,而是一...
查安卓系统文件管理,深度解析与... 你有没有想过,你的安卓手机里那些密密麻麻的文件,其实就像一个隐藏的宝藏库呢?今天,就让我带你一起探索...
好用的车机安卓系统,好用的车机... 你有没有发现,现在开车的时候,车机系统的重要性简直堪比手机里的操作系统呢!想象当你坐在驾驶座上,手握...
vivo是安卓系统还是ios系... 你有没有想过,手机里的那个小家伙,vivo,它到底是在安卓的海洋里遨游,还是在iOS的苹果园里悠闲地...
安卓手机连接到linux系统,... 你有没有想过,你的安卓手机竟然可以和Linux系统来个亲密接触呢?没错,就是那种让电脑世界都为之振奋...
wp系统可以装安卓软件,轻松体... 哇,你知道吗?现在wp系统也能装安卓软件啦!这可是个让人兴奋的消息,是不是感觉像打开了新世界的大门?...
导航linux系统和安卓系统哪... 你有没有想过,为什么你的手机、平板电脑或者智能手表上总是装着那个安卓系统?而你的车载导航、智能电视或...
安卓系统精简rom下载,轻松打... 你有没有想过,你的安卓手机其实可以更轻快、更流畅?没错,就是通过下载一个精简版的ROM系统!今天,就...
安卓系统能查找手机吗,如何查找... 你有没有遇到过手机不见了,心里那个急啊!别担心,今天就来跟你聊聊安卓系统里那个神奇的查找手机功能,让...
安卓系统的选词搜索,智能选词搜... 你有没有发现,在使用安卓手机的时候,有时候想找某个词,却怎么也找不到?别急,今天就来聊聊安卓系统的选...
悦联系统安卓大屏,引领智能交互... 你有没有发现,最近手机屏幕越来越大,仿佛整个世界都缩小到了掌心之间?这不,今天就来聊聊一个特别有意思...
旧手机刷系统新版安卓,轻松刷新... 你那台旧手机是不是已经有点儿力不从心了?别急,今天就来教你怎么给它来个焕然一新的变身——刷上新版安卓...