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_quantize.py 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 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 numpy as np
  9. import pytest
  10. from megengine import Parameter, Tensor
  11. from megengine import module as Float
  12. from megengine.module import qat as QAT
  13. from megengine.module import quantized as Q
  14. from megengine.quantization import (
  15. min_max_fakequant_qconfig,
  16. passive_qconfig,
  17. tqt_qconfig,
  18. )
  19. from megengine.quantization.fake_quant import TQT, FakeQuantize
  20. from megengine.quantization.observer import MinMaxObserver, PassiveObserver
  21. from megengine.quantization.quantize import (
  22. _get_quantable_module_names,
  23. apply_easy_quant,
  24. disable_fake_quant,
  25. disable_observer,
  26. enable_fake_quant,
  27. enable_observer,
  28. propagate_qconfig,
  29. quantize,
  30. quantize_qat,
  31. reset_qconfig,
  32. )
  33. class Net(Float.Module):
  34. def __init__(self):
  35. super().__init__()
  36. self.quant = Float.QuantStub()
  37. self.linear = Float.Linear(3, 3)
  38. self.dequant = Float.DequantStub()
  39. self.linear.bias[...] = Parameter(np.random.rand(3))
  40. def forward(self, x):
  41. x = self.quant(x)
  42. x = self.linear(x)
  43. x = self.dequant(x)
  44. return x
  45. class QATNet(Float.Module):
  46. def __init__(self):
  47. super().__init__()
  48. self.quant = QAT.QuantStub()
  49. self.linear = QAT.Linear(3, 3)
  50. self.dequant = QAT.DequantStub()
  51. self.linear.bias[...] = Parameter(np.random.rand(3))
  52. def forward(self, x):
  53. x = self.quant(x)
  54. x = self.linear(x)
  55. x = self.dequant(x)
  56. return x
  57. def test_propagate_qconfig():
  58. net = QATNet()
  59. propagate_qconfig(net, min_max_fakequant_qconfig)
  60. assert all(
  61. [
  62. net.quant.weight_observer is None,
  63. net.quant.weight_fake_quant is None,
  64. isinstance(net.quant.act_observer, MinMaxObserver),
  65. isinstance(net.quant.act_fake_quant, FakeQuantize),
  66. isinstance(net.linear.weight_observer, MinMaxObserver),
  67. isinstance(net.linear.weight_fake_quant, FakeQuantize),
  68. isinstance(net.linear.act_observer, MinMaxObserver),
  69. isinstance(net.linear.act_fake_quant, FakeQuantize),
  70. net.dequant.weight_observer is None,
  71. net.dequant.weight_fake_quant is None,
  72. net.dequant.act_observer is None,
  73. net.dequant.act_observer is None,
  74. ]
  75. )
  76. def init_qat_net():
  77. net = QATNet()
  78. propagate_qconfig(net, min_max_fakequant_qconfig)
  79. min_val = np.random.randint(-127, 0, size=(3,))
  80. max_val = np.random.randint(1, 127, size=(3,))
  81. net.quant.act_observer.min_val[...] = Parameter(min_val[0])
  82. net.quant.act_observer.max_val[...] = Parameter(max_val[0])
  83. net.linear.weight_observer.min_val[...] = Parameter(min_val[1])
  84. net.linear.weight_observer.max_val[...] = Parameter(max_val[1])
  85. net.linear.act_observer.min_val[...] = Parameter(min_val[2])
  86. net.linear.act_observer.max_val[...] = Parameter(max_val[2])
  87. return net
  88. def test_reset_qconfig():
  89. qat_net = init_qat_net()
  90. new_qat_net = reset_qconfig(qat_net, passive_qconfig)
  91. assert (
  92. new_qat_net.linear.get_weight_qparams() == qat_net.linear.get_weight_qparams()
  93. )
  94. assert (
  95. new_qat_net.linear.get_activation_qparams()
  96. == qat_net.linear.get_activation_qparams()
  97. )
  98. def test_enable_and_disable_observer():
  99. net = init_qat_net()
  100. enable_observer(net)
  101. assert net.quant.act_observer.enabled == True
  102. assert net.linear.weight_observer.enabled == True
  103. assert net.linear.act_observer.enabled == True
  104. disable_observer(net)
  105. assert net.quant.act_observer.enabled == False
  106. assert net.linear.weight_observer.enabled == False
  107. assert net.linear.act_observer.enabled == False
  108. def test_enable_and_disable_fake_quant():
  109. net = init_qat_net()
  110. disable_fake_quant(net)
  111. assert net.quant.act_fake_quant.enabled == False
  112. assert net.linear.weight_fake_quant.enabled == False
  113. assert net.linear.act_fake_quant.enabled == False
  114. enable_fake_quant(net)
  115. assert net.quant.act_fake_quant.enabled == True
  116. assert net.linear.weight_fake_quant.enabled == True
  117. assert net.linear.act_fake_quant.enabled == True
  118. def init_observer(module, data):
  119. enable_observer(module)
  120. disable_fake_quant(module)
  121. module(data)
  122. disable_observer(module)
  123. enable_fake_quant(module)
  124. def test_enable_and_disable_all():
  125. x = Tensor(np.random.randint(1, 10, size=(3, 3)).astype(np.float32))
  126. net = Net()
  127. y1 = net(x).numpy()
  128. net = quantize_qat(net, min_max_fakequant_qconfig)
  129. init_observer(net, x)
  130. y2 = net(x).numpy()
  131. disable_fake_quant(net)
  132. y3 = net(x).numpy()
  133. enable_fake_quant(net)
  134. y4 = net(x).numpy()
  135. np.testing.assert_allclose(y1, y3)
  136. np.testing.assert_allclose(y2, y4)
  137. with pytest.raises(AssertionError):
  138. np.testing.assert_allclose(y2, y3)
  139. def test_quantize_qat():
  140. net = Net()
  141. qat_net = quantize_qat(net, inplace=False, qconfig=min_max_fakequant_qconfig)
  142. assert isinstance(qat_net.quant, QAT.QuantStub)
  143. assert isinstance(qat_net.linear, QAT.Linear)
  144. assert isinstance(qat_net.dequant, QAT.DequantStub)
  145. def test_quantize():
  146. qat_net = init_qat_net()
  147. q_net = quantize(qat_net, inplace=False)
  148. assert isinstance(q_net.quant, Q.QuantStub)
  149. assert isinstance(q_net.linear, Q.Linear)
  150. assert isinstance(q_net.dequant, Q.DequantStub)
  151. def test_apply_easy_quant():
  152. qat_net = init_qat_net()
  153. data = Tensor(np.random.rand(2, 3, 3, 3), dtype=np.float32)
  154. eq_net = reset_qconfig(qat_net, passive_qconfig, inplace=False)
  155. apply_easy_quant(eq_net, data, 0.9, 1.1, 10)
  156. assert isinstance(eq_net.quant.act_observer, PassiveObserver)
  157. assert isinstance(eq_net.linear.weight_observer, PassiveObserver)
  158. assert isinstance(eq_net.linear.act_observer, PassiveObserver)
  159. assert eq_net.dequant.act_observer is None
  160. def test_apply_tqt():
  161. qat_net = init_qat_net()
  162. tqt_net = reset_qconfig(qat_net, tqt_qconfig, inplace=False)
  163. assert isinstance(tqt_net.quant.act_fake_quant, TQT)
  164. assert isinstance(tqt_net.linear.weight_fake_quant, TQT)
  165. assert isinstance(tqt_net.linear.act_fake_quant, TQT)
  166. assert tqt_net.dequant.act_fake_quant is None
  167. def test_get_quantable_module_names():
  168. # need to make sure names from Quantized and QAT are the same
  169. def _get_qat_module_names():
  170. def is_qat(key: str):
  171. value = getattr(QAT, key)
  172. return (
  173. isinstance(value, type)
  174. and issubclass(value, QAT.QATModule)
  175. and value != QAT.QATModule
  176. )
  177. # source should have all quantable modules' names
  178. quantable_module_names = [key for key in dir(QAT) if is_qat(key)]
  179. return quantable_module_names
  180. qat_module_names = _get_qat_module_names()
  181. quantized_module_names = _get_quantable_module_names()
  182. assert set(qat_module_names) == set(quantized_module_names)
  183. for key in qat_module_names:
  184. value = getattr(Float, key)
  185. assert (
  186. isinstance(value, type)
  187. and issubclass(value, Float.Module)
  188. and value != Float.Module
  189. )
  190. def test_disable_quantize():
  191. class Net(Float.Module):
  192. def __init__(self):
  193. super().__init__()
  194. self.conv = Float.ConvBnRelu2d(3, 3, 3)
  195. self.conv.disable_quantize()
  196. def forward(self, x):
  197. return self.conv(x)
  198. net = Net()
  199. qat_net = quantize_qat(net, inplace=False)
  200. assert isinstance(qat_net.conv, Float.ConvBnRelu2d)
  201. assert isinstance(qat_net.conv.conv, Float.Conv2d)
  202. def test_convert_with_custom_mapping():
  203. class FloatExample(Float.Module):
  204. def forward(self, x):
  205. return x
  206. class QATExample(QAT.QATModule):
  207. def forward(self, x):
  208. return x
  209. @classmethod
  210. def from_float_module(cls, float_module):
  211. return cls()
  212. class Net(Float.Module):
  213. def __init__(self):
  214. super().__init__()
  215. self.example = FloatExample()
  216. def forward(self, x):
  217. return self.example(x)
  218. net = Net()
  219. qat_net = quantize_qat(net, inplace=False, mapping={FloatExample: QATExample})
  220. assert isinstance(qat_net.example, QATExample)

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