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.5 kB

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

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