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 7.8 kB

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