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库是:
在这里插入图片描述

相关内容

热门资讯

省电手机推荐安卓系统,安卓系统... 手机这玩意儿,对于我们这些手机控来说,简直就是生活的必需品。但是,你知道吗?现在市面上那么多手机,要...
安卓系统衰落怎么恢复,探寻衰落... 你有没有发现,最近安卓系统好像有点儿“水土不服”了呢?曾经的霸主地位,如今似乎有些动摇。不过别急,今...
安卓系统手机应用锁,安全无忧的... 你有没有发现,现在手机里的秘密越来越多,是不是也跟小秘密一样,想要找个地方藏起来呢?没错,今天就要来...
安卓系统书院源app,安卓系统... 你有没有发现,手机里的安卓系统越来越智能了?今天,我要给你介绍一个特别有意思的书院源app,它可是安...
安卓系统8.1平板推荐,安卓8... 你有没有想过,拥有一款性能卓越、体验流畅的安卓系统8.1平板,简直就是移动办公和娱乐的完美搭档?没错...
谷歌不给华为安卓系统,探索替代... 你知道吗?最近科技圈可是炸开了锅!谷歌突然宣布,不给华为提供安卓系统了!这可不仅仅是两家公司之间的小...
选择安卓系统原因调查,揭秘安卓... 你有没有想过,为什么那么多人会选择安卓系统呢?是不是好奇他们到底看中了安卓的哪些“小秘密”?今天,就...
安卓系统的安全证书,守护移动安... 你知道吗?在咱们这个科技飞速发展的时代,手机已经成了我们生活中不可或缺的好伙伴。而说起手机,安卓系统...
谷歌安卓系统挣钱吗,如何通过它... 你有没有想过,那个无处不在的谷歌安卓系统,它到底是怎么赚钱的呢?没错,就是那个让我们的手机、平板、智...
GALGAME安卓换苹果系统,... 你有没有想过,那些在安卓手机上玩得如痴如醉的GALGAME,竟然也能在苹果系统上大放异彩?没错,就是...
华为宣布摆脱安卓系统,迈向自主... 哇,你知道吗?最近华为可是闹出了一个大新闻!那就是他们宣布要摆脱安卓系统,自己研发一套全新的操作系统...
安卓车机系统hcn,智能驾驶的... 你有没有发现,现在越来越多的汽车开始搭载智能化的车机系统了?这不,安卓车机系统HCN(Harmony...
超大平板安卓系统,创新体验与无... 你有没有想过,在这个科技飞速发展的时代,拥有一块超大平板电脑是多么酷炫的事情啊!想象那宽广的屏幕,无...
电脑装安卓系统步骤,电脑安装安... 你有没有想过,把安卓系统装在你的电脑上,是不是就像给电脑换了个新衣裳,瞬间变得时尚又实用呢?没错,今...
安卓系统视频存储软件,高效管理... 手机里的视频越来越多,是不是感觉存储空间不够用了?别急,今天就来给你安利几款安卓系统视频存储软件,让...
安卓系统如何连接奔驰,安卓系统... 你有没有想过,你的安卓手机和奔驰车之间也能来个亲密接触呢?没错,就是那种无缝连接的感觉,让你的手机和...
安卓系统emoji表情很少,探... 你知道吗?在手机世界里,emoji表情可是沟通的利器,它能让我们的聊天更加生动有趣。但是,你知道吗?...
安卓系统的德州游戏,刺激竞技体... 你有没有发现,安卓手机上的游戏世界越来越精彩了?尤其是那些德州游戏,简直让人停不下来!今天,就让我带...
xbox360安卓系统,探索跨... 你有没有想过,家里的老Xbox 360竟然也能变身成为安卓系统的超级玩家呢?没错,就是那个曾经陪伴我...
安卓系统怎么找云端,而是通过安... 你有没有想过,你的安卓手机里那些珍贵的照片、文件和笔记,其实都可以存放在云端,随时随地都能访问呢?没...