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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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. from megengine import tensor
  13. from megengine.core.autodiff.grad import Grad
  14. from megengine.core.tensor.function import Function
  15. from megengine.core.tensor.utils import make_shape_tuple
  16. from megengine.quantization.fake_quant import TQT_Function
  17. from megengine.quantization.internal_fake_quant import *
  18. from megengine.quantization.utils import QuantMode, fake_quant_tensor
  19. class numpy_TQT_Function:
  20. def __init__(self, lowerbound, upperbound):
  21. super().__init__()
  22. self.lowerbound = lowerbound
  23. self.upperbound = upperbound
  24. def forward(self, inp, scale):
  25. t = 2 ** scale
  26. # t = F.maximum(t, 1e-4)
  27. inp_scaled = inp / t
  28. inp_clipped = np.maximum(
  29. np.minimum(inp_scaled, self.upperbound), self.lowerbound
  30. )
  31. inp_rounded = np.round(inp_clipped)
  32. inp_flq = inp_rounded * t
  33. self.saved_tensors = (inp_scaled, inp_rounded, t)
  34. return inp_flq
  35. def backward(self, grad_inp_flq):
  36. (inp_scaled, inp_rounded, t) = self.saved_tensors
  37. mask_clip = (inp_scaled < -0.5 + self.lowerbound) + (
  38. inp_scaled > self.upperbound + 0.5
  39. ) # mask for accumulating the gradients of |data_scaled|>L
  40. mask_quant = np.abs(
  41. mask_clip - 1
  42. ) # mask for accumulating the gradients with |data_scaled|<=L
  43. grad_quant = (
  44. grad_inp_flq * mask_quant * (inp_rounded - inp_scaled)
  45. ) # gradient within |data_scaled|<=L
  46. grad_clip = (
  47. grad_inp_flq * mask_clip * inp_rounded
  48. ) # gradient with | data_scaled|>L
  49. grad_s = grad_clip.sum() + grad_quant.sum()
  50. # dL/ds = dL/dt * t * ln(2)
  51. grad_s = grad_s * t * np.log(2)
  52. grad_inp = grad_inp_flq * mask_quant
  53. return grad_inp, grad_s
  54. def test_TQT():
  55. f = TQT_Function(-127, 127)
  56. nf = numpy_TQT_Function(-127, 127)
  57. def check_inp(a, b, c, a_np, b_np, c_np):
  58. np.testing.assert_allclose(
  59. f.forward(a, b).numpy(),
  60. nf.forward(a_np, b_np).astype("float32"),
  61. rtol=1e-6,
  62. atol=1e-6,
  63. )
  64. c1, c2 = f.backward(c)
  65. c1_np, c2_np = nf.backward(c_np)
  66. np.testing.assert_allclose(c1.numpy(), c1_np.astype("float32"), rtol=1e-6)
  67. np.testing.assert_allclose(c2.numpy(), c2_np.astype("float32"), rtol=5e-5)
  68. a_np = np.random.random((4, 3)).astype("float32")
  69. b_np = np.random.random((1)).astype("float32")
  70. a = tensor(a_np)
  71. b = tensor(b_np)
  72. check_inp(a, b, b, a_np, b_np, b_np)
  73. def _save_to(self, name="grad"):
  74. def callback(tensor, grad):
  75. setattr(self, name, grad)
  76. return callback
  77. class Round(Function):
  78. def forward(self, x):
  79. return F.round(x)
  80. def backward(self, output_grads):
  81. return output_grads
  82. def fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax):
  83. oup = Round()(inp / scale) + zero_point
  84. oup = F.minimum(F.maximum(oup, qmin), qmax)
  85. oup = (oup - zero_point) * scale
  86. return oup
  87. def test_fakequant():
  88. qmin = -126
  89. qmax = 129
  90. def run(zero_point, scale):
  91. q_dict = {}
  92. q_dict["mode"] = QuantMode.ASYMMERTIC
  93. q_dict["scale"] = scale
  94. q_dict["zero_point"] = zero_point
  95. inp_data = np.random.uniform(low=-512.0, high=512.0, size=(1, 32, 32, 32))
  96. inp = tensor(inp_data, dtype=np.float32)
  97. # test forward
  98. oup = fake_quant_tensor(inp, qmin, qmax, q_dict).numpy()
  99. oup_gt = fake_quant_tensor_gt(inp, scale, zero_point, qmin, qmax).numpy()
  100. assert np.allclose(oup, oup_gt)
  101. assert oup.shape == oup_gt.shape
  102. # test backward
  103. x = tensor(inp_data, dtype=np.float32)
  104. grad = Grad().wrt(x, callback=_save_to(x))
  105. y = fake_quant_tensor(x, qmin, qmax, q_dict)
  106. grad(y, tensor(F.ones_like(x)))
  107. x1 = tensor(inp_data, dtype=np.float32)
  108. grad = Grad().wrt(x1, callback=_save_to(x1))
  109. y1 = fake_quant_tensor_gt(x1, scale, zero_point, qmin, qmax)
  110. grad(y1, tensor(F.ones_like(x1)))
  111. assert np.allclose(x.grad.numpy(), x1.grad.numpy())
  112. assert make_shape_tuple(x.grad.shape) == make_shape_tuple(x1.grad.shape)
  113. zero_point = tensor([1.0], dtype=np.float32)
  114. scale = tensor([4.0], dtype=np.float32)
  115. run(zero_point, scale)
  116. zero_point = tensor(1.0 * np.ones((1, 32, 1, 1)), dtype=np.float32)
  117. scale = tensor(4.0 * np.ones((1, 32, 1, 1)), dtype=np.float32)
  118. run(zero_point, scale)

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