You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

observer.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import math
  9. from abc import abstractmethod
  10. from enum import Enum
  11. import numpy as np
  12. from .. import functional as F
  13. from .._internal.dtype import _metadata_dict, get_quantized_dtype
  14. from ..core import Buffer, Function, tensor
  15. from ..jit import sideeffect
  16. from ..module import Module
  17. class Round(Function):
  18. def forward(self, x):
  19. return x.round()
  20. def backward(self, output_grads):
  21. return output_grads
  22. class Observer(Module):
  23. r"""
  24. A base class for Observer Module.
  25. :param dtype: a string indicating to collect scale and zero_point of which dtype
  26. """
  27. def __init__(self, dtype="qint8"):
  28. super().__init__()
  29. if dtype not in _metadata_dict.keys():
  30. raise ValueError(
  31. "unknown dtype: {}, only support {}".format(
  32. dtype, _metadata_dict.keys()
  33. )
  34. )
  35. self.dtype = dtype
  36. self.qmin = _metadata_dict[dtype].qmin
  37. self.qmax = _metadata_dict[dtype].qmax
  38. self.enabled = True
  39. def get_dtype(self):
  40. q_dict = self.get_qparams()
  41. numpy_scale = None if "scale" not in q_dict else q_dict["scale"].numpy()[0]
  42. numpy_zero_point = (
  43. None if "zero_point" not in q_dict else q_dict["zero_point"].numpy()[0]
  44. )
  45. return get_quantized_dtype(self.dtype, numpy_scale, numpy_zero_point)
  46. def enable(self):
  47. self.enabled = True
  48. def disable(self):
  49. self.enabled = False
  50. def train(self, mode: bool = True, recursive: bool = True) -> None:
  51. super().train(mode, recursive)
  52. if mode:
  53. self.enable()
  54. else:
  55. self.disable()
  56. @abstractmethod
  57. def forward(self, x):
  58. pass
  59. @abstractmethod
  60. def get_qparams(self, **kwargs):
  61. pass
  62. class ObserverMode(Enum):
  63. SYMMERTIC = 1
  64. ASYMMERTIC = 2
  65. def create_observer_dict(mode):
  66. if mode == ObserverMode.SYMMERTIC:
  67. return {
  68. "mode": ObserverMode.SYMMERTIC,
  69. "scale": None,
  70. }
  71. else:
  72. return {
  73. "mode": ObserverMode.ASYMMERTIC,
  74. "scale": None,
  75. "zero_point": None,
  76. }
  77. class MinMaxObserver(Observer):
  78. def __init__(self, mode=ObserverMode.SYMMERTIC, eps=0.00001, dtype="qint8"):
  79. super().__init__(dtype)
  80. self.mode = mode
  81. self.min_val = Buffer(np.finfo(np.float32).max, dtype=np.float32)
  82. self.max_val = Buffer(np.finfo(np.float32).min, dtype=np.float32)
  83. self.scale_limit = eps
  84. def _calculate_qparams(self, inp_min_val, inp_max_val):
  85. min_val = F.minimum(0.0, inp_min_val)
  86. max_val = F.maximum(0.0, inp_max_val)
  87. q_dict = create_observer_dict(self.mode)
  88. if self.mode == ObserverMode.SYMMERTIC:
  89. symmetric_max_vals = F.maximum(-min_val, max_val)
  90. # use maximun to avoid scale too small at the begin
  91. q_dict["scale"] = F.maximum(
  92. symmetric_max_vals / ((self.qmax - self.qmin) / 2), self.scale_limit
  93. )
  94. # zero_point = self.zero_point
  95. else:
  96. # use maximun to avoid scale too small at the begin
  97. q_dict["scale"] = F.maximum(
  98. (max_val - min_val) / (self.qmax - self.qmin), self.scale_limit,
  99. )
  100. # caculate zero_point
  101. q_dict["zero_point"] = self.qmin - Round()((min_val / q_dict["scale"]))
  102. return q_dict
  103. def get_qparams(self):
  104. return self._calculate_qparams(self.min_val, self.max_val)
  105. def forward(self, x_orig):
  106. if self.enabled:
  107. # stop gradient
  108. x = F.zero_grad(x_orig)
  109. # find max and min
  110. F.add_update(
  111. self.min_val,
  112. F.minimum(self.min_val, x.min()),
  113. alpha=0.0,
  114. beta=1.0,
  115. bias=0.0,
  116. )
  117. F.add_update(
  118. self.max_val,
  119. F.maximum(self.max_val, x.max()),
  120. alpha=0.0,
  121. beta=1.0,
  122. bias=0.0,
  123. )
  124. return x_orig
  125. class ExponentialMovingAverageObserver(MinMaxObserver):
  126. def __init__(
  127. self, momentum=0.9, mode=ObserverMode.SYMMERTIC, eps=0.00001, dtype="qint8"
  128. ):
  129. super().__init__(mode, eps, dtype)
  130. self.momentum = Buffer(momentum)
  131. self.runtime_momentum = Buffer(0.0)
  132. def set_momentum(self, momentum):
  133. self.momentum.set_value(momentum)
  134. def forward(self, x_orig):
  135. if self.enabled:
  136. # stop gradient
  137. x = F.zero_grad(x_orig)
  138. # Exponential Moving Average
  139. tmp_min = (
  140. self.min_val * self.runtime_momentum
  141. + (1 - self.runtime_momentum) * x.min()
  142. )
  143. tmp_max = (
  144. self.max_val * self.runtime_momentum
  145. + (1 - self.runtime_momentum) * x.max()
  146. )
  147. F.add_update(self.min_val, tmp_min, alpha=0.0, beta=1.0, bias=0.0)
  148. F.add_update(self.max_val, tmp_max, alpha=0.0, beta=1.0, bias=0.0)
  149. F.add_update(
  150. self.runtime_momentum, self.momentum, alpha=0.0, beta=1.0, bias=0.0
  151. )
  152. return x_orig
  153. class HistogramObserver(MinMaxObserver):
  154. def __init__(
  155. self,
  156. bins=2048,
  157. upsample_rate=128,
  158. dtype="qint8",
  159. mode=ObserverMode.SYMMERTIC,
  160. eps=0.00001,
  161. ):
  162. super().__init__(mode, eps, dtype)
  163. self.bins = bins
  164. self.upsample_rate = upsample_rate
  165. self.dst_nbins = _metadata_dict[dtype].qmax - _metadata_dict[dtype].qmin + 1
  166. self.histogram = Buffer([0.0] * bins)
  167. def _non_linear_param_search(self):
  168. r"""Non-linear parameter search.
  169. An approximation for L2 error minimization for selecting min/max.
  170. By selecting new min/max, we filter out outliers in input distribution.
  171. """
  172. np_min_val = self.min_val.numpy()[0]
  173. np_max_val = self.max_val.numpy()[0]
  174. np_histogram = self.histogram.numpy()
  175. assert len(np_histogram) == self.bins, "bins mistmatch"
  176. bin_width = (np_max_val - np_min_val) / self.bins
  177. def _get_norm(delta_begin, delta_end, density, norm_type):
  178. r"""
  179. Compute the norm of the values uniformaly distributed between
  180. delta_begin and delta_end.
  181. norm = density * (integral_{begin, end} x^2)
  182. = density * (end^3 - begin^3) / 3
  183. """
  184. assert norm_type == "L2", "Only L2 norms are currently supported"
  185. norm = 0.0
  186. if norm_type == "L2":
  187. norm = (
  188. delta_end * delta_end * delta_end
  189. - delta_begin * delta_begin * delta_begin
  190. ) / 3
  191. return density * norm
  192. def _compute_quantization_error(next_start_bin, next_end_bin, norm_type):
  193. r"""
  194. Compute the quantization error if we use start_bin to end_bin as the
  195. min and max to do the quantization.
  196. """
  197. norm = 0.0
  198. dst_bin_width = (
  199. bin_width * (next_end_bin - next_start_bin + 1) / self.dst_nbins
  200. )
  201. if dst_bin_width == 0.0:
  202. return 0.0
  203. for src_bin in range(self.bins):
  204. # distances from the beginning of first dst_bin to the beginning and
  205. # end of src_bin
  206. src_bin_begin = (src_bin - next_start_bin) * bin_width
  207. src_bin_end = src_bin_begin + bin_width
  208. # which dst_bins the beginning and end of src_bin belong to?
  209. dst_bin_of_begin = min(
  210. self.dst_nbins - 1,
  211. max(0.0, math.floor(src_bin_begin / dst_bin_width)),
  212. )
  213. dst_bin_of_end = min(
  214. self.dst_nbins - 1,
  215. max(0.0, math.floor(src_bin_end / dst_bin_width)),
  216. )
  217. dst_bin_of_begin_center = (
  218. dst_bin_of_begin * dst_bin_width + dst_bin_width / 2
  219. )
  220. density = np_histogram[src_bin] / bin_width
  221. if dst_bin_of_begin == dst_bin_of_end:
  222. # if src_bin is entirely within 1 dst_bin
  223. delta_begin = src_bin_begin - dst_bin_of_begin_center
  224. delta_end = src_bin_end - dst_bin_of_begin_center
  225. norm = norm + _get_norm(delta_begin, delta_end, density, norm_type)
  226. else:
  227. delta_begin = src_bin_begin - dst_bin_of_begin_center
  228. delta_end = dst_bin_width / 2
  229. norm = norm + _get_norm(delta_begin, delta_end, density, norm_type)
  230. norm = norm + (dst_bin_of_end - dst_bin_of_begin - 1) * _get_norm(
  231. -dst_bin_width / 2, dst_bin_width / 2, density, norm_type
  232. )
  233. dst_bin_of_end_center = (
  234. dst_bin_of_end * dst_bin_width + dst_bin_width / 2
  235. )
  236. delta_begin = -dst_bin_width / 2
  237. delta_end = src_bin_end - dst_bin_of_end_center
  238. norm = norm + _get_norm(delta_begin, delta_end, density, norm_type)
  239. return norm
  240. # cumulative sum
  241. total = sum(np_histogram)
  242. cSum = np.cumsum(np_histogram, axis=0)
  243. stepsize = 1e-5 # granularity
  244. alpha = 0.0 # lower bound
  245. beta = 1.0 # upper bound
  246. start_bin = 0
  247. end_bin = self.bins - 1
  248. norm_min = float("inf")
  249. while alpha < beta:
  250. # Find the next step
  251. next_alpha = alpha + stepsize
  252. next_beta = beta - stepsize
  253. # find the left and right bins between the quantile bounds
  254. l = start_bin
  255. r = end_bin
  256. while l < end_bin and cSum[l] < next_alpha * total:
  257. l = l + 1
  258. while r > start_bin and cSum[r] > next_beta * total:
  259. r = r - 1
  260. # decide the next move
  261. next_start_bin = start_bin
  262. next_end_bin = end_bin
  263. if (l - start_bin) > (end_bin - r):
  264. # move the start bin
  265. next_start_bin = l
  266. alpha = next_alpha
  267. else:
  268. # move the end bin
  269. next_end_bin = r
  270. beta = next_beta
  271. if next_start_bin == start_bin and next_end_bin == end_bin:
  272. continue
  273. # calculate the quantization error using next_start_bin and next_end_bin
  274. norm = _compute_quantization_error(next_start_bin, next_end_bin, "L2")
  275. if norm > norm_min:
  276. break
  277. norm_min = norm
  278. start_bin = next_start_bin
  279. end_bin = next_end_bin
  280. new_min = self.min_val + bin_width * start_bin
  281. new_max = self.min_val + bin_width * (end_bin + 1)
  282. return new_min, new_max
  283. def get_qparams(self):
  284. new_min, new_max = self._non_linear_param_search()
  285. return self._calculate_qparams(new_min, new_max)
  286. def _combine_histograms(
  287. self, orig_hist, new_hist, upsample_rate, downsample_rate, start_idx, Nbins
  288. ):
  289. # First up-sample the histogram with new data by a factor of L
  290. # This creates an approximate probability density thats piecwise constant
  291. upsampled_histogram = new_hist.repeat(upsample_rate)
  292. # Now insert the upsampled histogram into the output
  293. # histogram, which is initialized with zeros.
  294. # The offset at which the histogram is introduced is determined
  295. # by the start index as the output histogram can cover a wider range
  296. histogram_with_output_range = np.zeros((Nbins * downsample_rate))
  297. histogram_with_output_range[
  298. start_idx : Nbins * upsample_rate + start_idx
  299. ] = upsampled_histogram
  300. # Compute integral histogram, double precision is needed to ensure
  301. # that there are no overflows
  302. integral_histogram = np.cumsum(histogram_with_output_range, 0)[
  303. downsample_rate - 1 :: downsample_rate
  304. ]
  305. # Finally perform interpolation
  306. shifted_integral_histogram = np.zeros((Nbins))
  307. shifted_integral_histogram[1:Nbins] = integral_histogram[0:-1]
  308. interpolated_histogram = (
  309. integral_histogram - shifted_integral_histogram
  310. ) / upsample_rate
  311. orig_hist = orig_hist + interpolated_histogram
  312. return orig_hist
  313. def _adjust_min_max(self, combined_min, combined_max, upsample_rate):
  314. # We ensure that:
  315. # (combined_max - combined_min)/(downsample_rate*Nbins) = (max - min)/(upsample_rate*Nbins)
  316. # This allows us to have a common grid of resolution s, where we can align
  317. # the input histogram
  318. # start_idx maps min_val to the histogram bin index.
  319. np_min_val = self.min_val.numpy()[0]
  320. np_max_val = self.max_val.numpy()[0]
  321. hist_bin_width = (np_max_val - np_min_val) / (self.bins * upsample_rate)
  322. downsample_rate = int(
  323. np.ceil((combined_max - combined_min) / (self.bins * hist_bin_width))
  324. )
  325. e = downsample_rate * (self.bins * hist_bin_width) - (
  326. combined_max - combined_min
  327. )
  328. combined_max = combined_max + e / 2
  329. combined_min = combined_min - e / 2
  330. start_idx = int(np.round((np_min_val - combined_min) / hist_bin_width))
  331. return combined_min, combined_max, downsample_rate, start_idx
  332. @sideeffect
  333. def sideeffect_forward(self, x_orig):
  334. x = x_orig.numpy()
  335. min_val = self.min_val.numpy()[0]
  336. max_val = self.max_val.numpy()[0]
  337. histogram = self.histogram.numpy()
  338. new_min = x.min()
  339. new_max = x.max()
  340. if min_val == 0 or max_val == 0:
  341. new_histogram, _ = np.histogram(x, self.bins, (new_min, new_max))
  342. else:
  343. new_min = min(new_min, min_val)
  344. new_max = max(new_max, max_val)
  345. # combine the existing histogram and new histogram into 1 histogram
  346. # We do this by first upsampling the histogram to a dense grid
  347. # and then downsampling the histogram efficiently
  348. (new_min, new_max, downsample_rate, start_idx,) = self._adjust_min_max(
  349. new_min, new_max, self.upsample_rate
  350. )
  351. new_histogram, _ = np.histogram(x, self.bins, (new_min, new_max))
  352. new_histogram = new_histogram.astype(np.float64)
  353. if new_min == min_val and new_max == max_val:
  354. new_histogram += histogram
  355. else:
  356. new_histogram = self._combine_histograms(
  357. new_histogram,
  358. histogram,
  359. self.upsample_rate,
  360. downsample_rate,
  361. start_idx,
  362. self.bins,
  363. )
  364. self.histogram.set_value(new_histogram)
  365. self.min_val.set_value(new_min)
  366. self.max_val.set_value(new_max)
  367. def forward(self, x_orig):
  368. self.sideeffect_forward(x_orig)
  369. return x_orig

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台