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_qat_module.py 6.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import io
  2. from functools import partial
  3. from itertools import chain
  4. from typing import Callable
  5. import numpy as np
  6. import megengine as mge
  7. import megengine.functional as F
  8. import megengine.module as M
  9. import megengine.quantization as Q
  10. from megengine import Tensor
  11. from megengine.module.qat.module import QATModule
  12. from megengine.traced_module import TracedModule, trace_module
  13. def get_subattr(self: M.Module, name: str):
  14. if name == "":
  15. return self
  16. module_path, _, name = name.rpartition(".")
  17. if module_path == "":
  18. return getattr(self, name)
  19. module_names = module_path.split(".")
  20. for item in module_names:
  21. self = getattr(self, item)
  22. if not isinstance(self, M.Module):
  23. raise AttributeError("`{}` is not an Module".format(item))
  24. return getattr(self, name)
  25. class Myblcok(M.Module):
  26. def __init__(self,):
  27. super().__init__()
  28. self.conv0 = M.ConvBnRelu2d(3, 3, 3, 1, 1)
  29. self.conv1 = M.ConvBn2d(3, 3, 1, 1, 0)
  30. self.conv2 = M.ConvBn2d(3, 3, 1, 1, 0)
  31. self.add = M.Elemwise("FUSE_ADD_RELU")
  32. def forward(self, x):
  33. x = self.conv0(x)
  34. x0 = self.conv1(x)
  35. x1 = self.conv2(x)
  36. o = self.add(x0, x1)
  37. return o
  38. class MyModule(M.Module):
  39. def __init__(self):
  40. super().__init__()
  41. self.block0 = Myblcok()
  42. self.block1 = Myblcok()
  43. def forward(self, x):
  44. x = self.block0(x)
  45. x = self.block1(x)
  46. return x
  47. class MyMinMaxObserver(Q.MinMaxObserver):
  48. pass
  49. class MyTQT(Q.TQT):
  50. pass
  51. def get_lsq_config(lsq_cls):
  52. return Q.QConfig(
  53. weight_observer=None,
  54. act_observer=None,
  55. weight_fake_quant=partial(lsq_cls, dtype="qint8_narrow"),
  56. act_fake_quant=partial(lsq_cls, dtype="qint8"),
  57. )
  58. def get_observer_config(observer_cls):
  59. return Q.QConfig(
  60. weight_observer=partial(observer_cls, dtype="qint8_narrow"),
  61. act_observer=partial(observer_cls, dtype="qint8"),
  62. weight_fake_quant=None,
  63. act_fake_quant=None,
  64. )
  65. def get_qparams(mod: QATModule):
  66. weight_qparams, act_qparams = None, None
  67. if mod.act_observer is not None:
  68. act_qparams = mod.act_observer.get_qparams()
  69. if mod.act_fake_quant:
  70. act_qparams = mod.act_fake_quant.get_qparams()
  71. if mod.weight_observer is not None:
  72. weight_qparams = mod.weight_observer.get_qparams()
  73. if mod.weight_fake_quant:
  74. weight_qparams = mod.weight_fake_quant.get_qparams()
  75. return weight_qparams, act_qparams
  76. def check_qparams(qparmsa: Q.QParams, qparmsb: Q.QParams):
  77. assert qparmsa.dtype_meta == qparmsb.dtype_meta
  78. assert qparmsa.mode == qparmsb.mode
  79. np.testing.assert_equal(qparmsa.scale.numpy(), qparmsb.scale.numpy())
  80. if qparmsa.zero_point is not None:
  81. np.testing.assert_equal(qparmsa.zero_point.numpy(), qparmsb.zero_point.numpy())
  82. def build_observered_net(net: M.Module, observer_cls):
  83. qat_net = Q.quantize_qat(net, qconfig=get_observer_config(observer_cls))
  84. Q.enable_observer(qat_net)
  85. inp = Tensor(np.random.random(size=(5, 3, 32, 32)))
  86. qat_net(inp)
  87. Q.disable_observer(qat_net)
  88. return qat_net
  89. def build_fakequanted_net(net: QATModule, fakequant_cls):
  90. qat_net = Q.reset_qconfig(net, get_lsq_config(fakequant_cls))
  91. return qat_net
  92. def test_trace_qat():
  93. def _check_qat_module(qat_net: QATModule):
  94. inp = Tensor(np.random.random(size=(5, 3, 32, 32)))
  95. traced_net = trace_module(qat_net, inp)
  96. for name, qat_module in qat_net.named_modules():
  97. if not isinstance(qat_module, QATModule):
  98. continue
  99. traced_qat_module = get_subattr(traced_net, name)
  100. weight_qparams, act_qparams = get_qparams(qat_module)
  101. traced_weight_qparams, traced_act_qparams = get_qparams(traced_qat_module)
  102. if weight_qparams:
  103. check_qparams(weight_qparams, traced_weight_qparams)
  104. if act_qparams:
  105. check_qparams(act_qparams, traced_act_qparams)
  106. _check_qat_module(build_observered_net(MyModule(), Q.MinMaxObserver))
  107. _check_qat_module(build_observered_net(MyModule(), MyMinMaxObserver))
  108. _check_qat_module(
  109. build_fakequanted_net(build_observered_net(MyModule(), Q.MinMaxObserver), Q.TQT)
  110. )
  111. _check_qat_module(
  112. build_fakequanted_net(build_observered_net(MyModule(), Q.MinMaxObserver), MyTQT)
  113. )
  114. def test_load_param():
  115. def _check_param(moda: M.Module, modb: M.Module):
  116. for name, attr in chain(moda.named_parameters(), moda.named_buffers()):
  117. traced_attr = get_subattr(modb, name)
  118. np.testing.assert_equal(attr.numpy(), traced_attr.numpy())
  119. def _check_module(build_func: Callable):
  120. net = build_func()
  121. buffer = io.BytesIO()
  122. mge.save(net.state_dict(), buffer)
  123. buffer.seek(0)
  124. inp = Tensor(np.random.random(size=(5, 3, 32, 32)))
  125. traced_net = trace_module(build_func(), inp)
  126. traced_net.load_state_dict(mge.load(buffer))
  127. _check_param(net, traced_net)
  128. buffer.seek(0)
  129. traced_net = trace_module(build_func(), inp).flatten()
  130. traced_net.load_state_dict(mge.load(buffer))
  131. _check_param(net, traced_net)
  132. _check_module(lambda: MyModule())
  133. _check_module(lambda: build_observered_net(MyModule(), Q.MinMaxObserver))
  134. def test_qualname():
  135. def _check_qualname(net):
  136. inp = Tensor(np.random.random(size=(5, 3, 32, 32)))
  137. traced_net = trace_module(net, inp)
  138. base_qualname = traced_net.graph.qualname
  139. for node in traced_net.graph.nodes():
  140. qualname = node.qualname
  141. qualname = qualname[len(base_qualname) + 1 :]
  142. if qualname.endswith("]"):
  143. qualname = qualname.rsplit(".", 1)[0]
  144. if qualname.startswith("["):
  145. qualname = ""
  146. traced_attr = get_subattr(traced_net, qualname)
  147. orig_attr = get_subattr(net, qualname)
  148. assert traced_attr is not None
  149. assert orig_attr is not None
  150. _check_qualname(MyModule())
  151. _check_qualname(build_observered_net(MyModule(), Q.MinMaxObserver))

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