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.

test_fake_quant.py 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import numpy as np
  10. import pytest
  11. import megengine as mge
  12. import megengine.functional as F
  13. from megengine import tensor
  14. from megengine.core.autodiff.grad import Function, Grad
  15. from megengine.core.tensor.dtype import QuantDtypeMeta
  16. from megengine.core.tensor.utils import make_shape_tuple
  17. from megengine.quantization.internal_fake_quant import *
  18. from megengine.quantization.utils import (
  19. QuantMode,
  20. create_qparams,
  21. fake_quant_tensor,
  22. lsq_forward,
  23. tqt_forward,
  24. )
  25. class TQT_numpy:
  26. def __init__(self, lowerbound, upperbound):
  27. super().__init__()
  28. self.lowerbound = lowerbound
  29. self.upperbound = upperbound
  30. def forward(self, inp, scale):
  31. t = 2 ** scale
  32. # t = F.maximum(t, 1e-4)
  33. inp_scaled = inp / t
  34. inp_clipped = np.maximum(
  35. np.minimum(inp_scaled, self.upperbound), self.lowerbound
  36. )
  37. inp_rounded = np.round(inp_clipped)
  38. inp_flq = inp_rounded * t
  39. self.saved_tensors = (inp_scaled, inp_rounded, t)
  40. return inp_flq
  41. def backward(self, grad_inp_flq):
  42. (inp_scaled, inp_rounded, t) = self.saved_tensors
  43. mask_clip = (inp_scaled < -0.5 + self.lowerbound) + (
  44. inp_scaled > self.upperbound + 0.5
  45. ) # mask for accumulating the gradients of |data_scaled|>L
  46. mask_quant = np.abs(
  47. mask_clip - 1
  48. ) # mask for accumulating the gradients with |data_scaled|<=L
  49. grad_quant = (
  50. grad_inp_flq * mask_quant * (inp_rounded - inp_scaled)
  51. ) # gradient within |data_scaled|<=L
  52. grad_clip = (
  53. grad_inp_flq * mask_clip * inp_rounded
  54. ) # gradient with | data_scaled|>L
  55. grad_s = grad_clip.sum() + grad_quant.sum()
  56. # dL/ds = dL/dt * t * ln(2)
  57. grad_s = grad_s * t * np.log(2)
  58. grad_inp = grad_inp_flq * mask_quant
  59. return grad_inp, grad_s
  60. def test_tqt():
  61. g = []
  62. def cb(grad):
  63. g.append(grad)
  64. x = np.random.randint(-128, 128, size=(1, 2, 3, 4)).astype("float32")
  65. s = np.random.rand(1) - 1
  66. g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32")
  67. n = TQT_numpy(-127, 127)
  68. y_np = n.forward(x, s)
  69. g_x_np, g_s_np = n.backward(g_y)
  70. x = mge.tensor(x, dtype="float32")
  71. s = mge.tensor(s, dtype="float32")
  72. g_y = mge.tensor(g_y, dtype="float32")
  73. with Grad() as grad:
  74. grad.wrt(x, s, callback=cb)
  75. y = tqt_forward(-127, 127, x, s)
  76. grad(y, g_y)
  77. g_x, g_s = g
  78. np.testing.assert_allclose(y.numpy(), y_np, rtol=1e-5, atol=1e-5)
  79. np.testing.assert_allclose(g_x.numpy(), g_x_np, rtol=1e-5, atol=1e-5)
  80. np.testing.assert_allclose(g_s.numpy(), g_s_np, rtol=5e-5, atol=5e-5)
  81. def _save_to(self, name="grad"):
  82. def callback(grad):
  83. setattr(self, name, grad)
  84. return callback
  85. class Round(Function):
  86. def forward(self, x):
  87. return F.round(x)
  88. def backward(self, output_grads):
  89. return output_grads
  90. def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax):
  91. oup = Round()(inp / scale) + zero_point
  92. oup = F.minimum(F.maximum(oup, qmin), qmax)
  93. oup = (oup - zero_point) * scale
  94. return oup
  95. def test_fakequant():
  96. qmin = -126
  97. qmax = 129
  98. test_dtype = QuantDtypeMeta("test_qint8", None, "int8", qmin, qmax)
  99. def run(zero_point, scale):
  100. qparams = create_qparams(QuantMode.ASYMMERTIC, test_dtype, scale, zero_point)
  101. inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32))
  102. inp = tensor(inp_data, dtype=np.float32)
  103. # test forward
  104. oup = fake_quant_tensor(inp, qparams).numpy()
  105. oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy()
  106. assert np.allclose(oup, oup_gt)
  107. assert oup.shape == oup_gt.shape
  108. # test backward
  109. x = tensor(inp_data, dtype=np.float32)
  110. with Grad() as grad:
  111. grad.wrt(x, callback=_save_to(x))
  112. y = fake_quant_tensor(x, qparams)
  113. grad(y, tensor(F.ones_like(x)))
  114. x1 = tensor(inp_data, dtype=np.float32)
  115. with Grad() as grad:
  116. grad.wrt(x1, callback=_save_to(x1))
  117. y1 = fake_quant_tensor_gt(x1, scale, zero_point, qmin, qmax)
  118. grad(y1, tensor(F.ones_like(x1)))
  119. assert np.allclose(x.grad.numpy(), x1.grad.numpy())
  120. assert make_shape_tuple(x.grad.shape) == make_shape_tuple(x1.grad.shape)
  121. # test nan
  122. x = F.full((1, 32, 3, 3), np.nan)
  123. y = fake_quant_tensor(x, qparams).numpy()
  124. assert np.isnan(y).all()
  125. zero_point = tensor([1.0], dtype=np.float32)
  126. scale = tensor([4.0], dtype=np.float32)
  127. run(zero_point, scale)
  128. zero_point = tensor(1.0 * np.ones((1, 32, 1, 1)), dtype=np.float32)
  129. scale = tensor(4.0 * np.ones((1, 32, 1, 1)), dtype=np.float32)
  130. run(zero_point, scale)
  131. class LSQ_numpy:
  132. def __init__(self, lowerbound, upperbound):
  133. super().__init__()
  134. self.lowerbound = lowerbound
  135. self.upperbound = upperbound
  136. def forward(self, inp, scale, zero_point, grad_scale):
  137. inp_scaled = inp / scale + zero_point
  138. inp_clipped = np.maximum(
  139. np.minimum(inp_scaled, self.upperbound), self.lowerbound
  140. )
  141. inp_rounded = np.floor(inp_clipped + 0.5)
  142. inp_flq = (inp_rounded - zero_point) * scale
  143. self.saved_tensors = (inp_scaled, inp_rounded, scale, grad_scale)
  144. return inp_flq
  145. def backward(self, grad_inp_flq):
  146. (inp_scaled, inp_rounded, scale, grad_scale) = self.saved_tensors
  147. ind_small = inp_scaled < self.lowerbound
  148. ind_big = inp_scaled > self.upperbound
  149. ind_middle = np.logical_xor(ind_small, ind_big)
  150. ind_middle = np.abs(ind_middle - 1)
  151. grad_s = (
  152. ind_small * self.lowerbound
  153. + ind_big * self.upperbound
  154. + ind_middle * (-inp_scaled + inp_rounded)
  155. )
  156. grad_s = grad_s * grad_scale * grad_inp_flq
  157. grad_s = grad_s.sum()
  158. grad_inp = grad_inp_flq * ind_middle
  159. return grad_inp, grad_s
  160. def test_lsq():
  161. g = []
  162. def cb(grad):
  163. g.append(grad)
  164. # FIXME: use random number when LSQ is fixed
  165. # x = np.random.randint(-128, 128, size=(1, 2, 3, 4)).astype("float32")
  166. # s = np.random.rand(1)
  167. x = np.array(
  168. [
  169. [
  170. [
  171. [4.0, 38.0, -121.0, 38.0],
  172. [15.0, -115.0, -112.0, 24.0],
  173. [23.0, -65.0, 109.0, -115.0],
  174. ],
  175. [
  176. [-66.0, -90.0, -45.0, -101.0],
  177. [68.0, -98.0, 108.0, -79.0],
  178. [54.0, 63.0, -10.0, -50.0],
  179. ],
  180. ]
  181. ],
  182. dtype="float32",
  183. )
  184. s = np.array([0.02918224], dtype="float32")
  185. eps = np.array([1e-5], dtype="float32")
  186. s = np.abs(s) if np.abs(s) > eps else eps
  187. zero_point = np.array([1.0], dtype="float32")
  188. grad_s = np.array([2.0], dtype="float32")
  189. g_y = np.ones(shape=(1, 2, 3, 4), dtype="float32")
  190. n = LSQ_numpy(-127, 127)
  191. y_np = n.forward(x, s, zero_point, grad_s)
  192. g_x_np, g_s_np = n.backward(g_y)
  193. x = mge.tensor(x, dtype="float32")
  194. s = mge.tensor(s, dtype="float32")
  195. zero_point = mge.tensor(zero_point, dtype="float32")
  196. grad_s = mge.tensor(grad_s, dtype="float32")
  197. g_y = mge.tensor(g_y, dtype="float32")
  198. with Grad() as grad:
  199. grad.wrt(x, s, callback=cb)
  200. y = lsq_forward(-127, 127, x, s, zero_point, grad_s)
  201. grad(y, g_y)
  202. g_x, g_s = g
  203. np.testing.assert_allclose(y.numpy(), y_np, rtol=1e-7, atol=1e-7)
  204. np.testing.assert_allclose(g_x.numpy(), g_x_np, rtol=1e-7, atol=1e-7)
  205. np.testing.assert_allclose(g_s.numpy(), g_s_np, rtol=5e-7, atol=5e-7)