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_op.py 8.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. import megengine as mge
  11. import megengine.functional as F
  12. from megengine.core.tensor import dtype
  13. from megengine.device import get_device_count
  14. from megengine.functional.elemwise import _elemwise_multi_type, _elwise
  15. from megengine.module.quantized.conv import ConvTranspose2d
  16. from megengine.quantization import QuantMode, create_qparams
  17. def quant(x, scale):
  18. x_dtype = dtype.qint8(scale)
  19. return x.astype(x_dtype)
  20. def fake_quant(x, scale):
  21. x = x / scale
  22. x = F.round(x)
  23. x = F.clip(x, -128, 127)
  24. x = x * scale
  25. return x
  26. @pytest.mark.parametrize("kind", ["abs", "sin", "sub", "mul", "fuse_add_tanh"])
  27. def test_elemwise(kind):
  28. x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32"))
  29. x1_scale = np.float32(np.random.rand() + 1)
  30. x1 = fake_quant(x1, x1_scale)
  31. x1.qparams.update(create_qparams(QuantMode.SYMMERTIC, "qint8", x1_scale))
  32. x1_int8 = quant(x1, x1_scale)
  33. x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32"))
  34. x2_scale = np.float32(np.random.rand() + 1)
  35. x2 = fake_quant(x2, x2_scale)
  36. x2.qparams.update(create_qparams(QuantMode.SYMMERTIC, "qint8", x2_scale))
  37. x2_int8 = quant(x2, x2_scale)
  38. output_scale = np.float32(np.random.rand() + 1)
  39. output_dtype = dtype.qint8(output_scale)
  40. quantized_kind = "q" + kind
  41. if kind in ("abs", "sin"):
  42. desired_out = fake_quant(_elwise(x1, mode=kind), output_scale)
  43. actual_out = (
  44. _elemwise_multi_type(
  45. x1_int8, mode=quantized_kind, dtype=output_dtype
  46. ).numpy()
  47. * output_scale
  48. )
  49. else:
  50. desired_out = fake_quant(_elwise(x1, x2, mode=kind), output_scale)
  51. actual_out = (
  52. _elemwise_multi_type(
  53. x1_int8, x2_int8, mode=quantized_kind, dtype=output_dtype
  54. ).numpy()
  55. * output_scale
  56. )
  57. np.testing.assert_allclose(actual_out, desired_out.numpy())
  58. @pytest.mark.skipif(
  59. get_device_count("gpu") > 0, reason="cuda does not support nchw int8"
  60. )
  61. def test_conv_bias():
  62. inp_scale = np.float32(np.random.rand() + 1)
  63. w_scale = np.float32(np.random.rand() + 1)
  64. outp_scale = np.float32(np.random.rand() + 1)
  65. inp_dtype = dtype.qint8(inp_scale)
  66. w_dtype = dtype.qint8(w_scale)
  67. b_dtype = dtype.qint32(inp_scale * w_scale)
  68. out_dtype = dtype.qint8(outp_scale)
  69. def run(
  70. N,
  71. IC,
  72. OC,
  73. IH,
  74. IW,
  75. KH,
  76. KW,
  77. PH,
  78. PW,
  79. SH,
  80. SW,
  81. has_bias=True,
  82. nonlinear_mode="identity",
  83. ):
  84. inp_v = np.random.normal(size=(N, IC, IH, IW))
  85. w_v = np.random.normal(size=(OC, IC, KH, KW))
  86. b_v = np.random.normal(size=(1, OC, 1, 1))
  87. inp_scale = dtype.get_scale(inp_dtype)
  88. w_scale = dtype.get_scale(w_dtype)
  89. b_scale = dtype.get_scale(b_dtype)
  90. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  91. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  92. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  93. inp_int8 = mge.tensor(inpv, dtype=inp_dtype)
  94. w_int8 = mge.Parameter(wv, dtype=w_dtype)
  95. b_int32 = mge.Parameter(bv, dtype=b_dtype)
  96. inp_fp32 = inp_int8.astype("float32")
  97. w_fp32 = w_int8.astype("float32")
  98. b_fp32 = b_int32.astype("float32")
  99. def convert_to_nchw4(var):
  100. var = F.reshape(
  101. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  102. )
  103. var = F.transpose(var, (0, 1, 3, 4, 2))
  104. return var
  105. def run_conv2d(inp, w, b):
  106. O = F.conv2d(
  107. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  108. )
  109. if nonlinear_mode == "relu":
  110. return F.relu(O)
  111. else:
  112. return O
  113. def run_conv_bias(inp, w, b, format="NCHW"):
  114. b = b if has_bias else mge.Parameter(np.zeros_like(b.numpy()))
  115. if format == "NCHW4":
  116. inp = convert_to_nchw4(inp)
  117. w = convert_to_nchw4(w)
  118. b = convert_to_nchw4(b)
  119. return F.quantized.conv_bias_activation(
  120. inp,
  121. w,
  122. b,
  123. stride=(SH, SW),
  124. padding=(PH, PW),
  125. dtype=out_dtype,
  126. nonlinear_mode=nonlinear_mode,
  127. )
  128. format = "NCHW4" if mge.is_cuda_available() else "NCHW"
  129. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  130. expected = expected.astype(out_dtype).astype("float32")
  131. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  132. "float32"
  133. )
  134. if format == "NCHW4":
  135. result = F.transpose(result, (0, 1, 4, 2, 3))
  136. expected = F.flatten(expected)
  137. result = F.flatten(result)
  138. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  139. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  140. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  141. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  142. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  143. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  144. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  145. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "relu")
  146. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "relu")
  147. def test_conv_transpose2d():
  148. rng = np.random.RandomState(seed=2021)
  149. def test_func(
  150. N,
  151. IC,
  152. IH,
  153. IW,
  154. OC,
  155. KH,
  156. KW,
  157. SH,
  158. SW,
  159. PH,
  160. PW,
  161. DH,
  162. DW,
  163. groups=1,
  164. has_bias=True,
  165. conv_mode: str = "cross_correlation",
  166. compute_mode: str = "default",
  167. ):
  168. inp_scale = np.float32(rng.uniform(low=0.04, high=0.06))
  169. weight_scale = np.float32(rng.uniform(low=0.04, high=0.06))
  170. bias_scale = inp_scale * weight_scale
  171. out_scale = np.float32(rng.uniform(low=0.04, high=0.06))
  172. inp_dtype = dtype.qint8(inp_scale)
  173. weight_dtype = dtype.qint8(weight_scale)
  174. bias_dtype = dtype.qint32(bias_scale)
  175. out_dtype = dtype.qint8(out_scale)
  176. inp_fp32 = rng.uniform(low=-1, high=1, size=(N, IC, IH, IW)).astype(np.float32)
  177. weight_fp32 = rng.uniform(low=-1, high=1, size=(IC, OC, KH, KW)).astype(
  178. np.float32
  179. )
  180. bias_fp32 = rng.uniform(low=-1, high=1, size=(1, OC, 1, 1)).astype(np.float32)
  181. inp_int8 = dtype.convert_to_qint8(inp_fp32, inp_dtype)
  182. weight_int8 = dtype.convert_to_qint8(weight_fp32, weight_dtype)
  183. bias_int32 = dtype.convert_to_qint32(bias_fp32, bias_dtype)
  184. inp_int8 = mge.tensor(inp_int8, dtype=inp_dtype)
  185. weight_int8 = mge.Parameter(weight_int8, dtype=weight_dtype)
  186. bias_int32 = mge.Parameter(bias_int32, dtype=bias_dtype)
  187. inp_fp32 = inp_int8.astype("float32")
  188. weight_fp32 = weight_int8.astype("float32")
  189. bias_fp32 = bias_int32.astype("float32")
  190. expected = F.conv_transpose2d(
  191. inp_fp32,
  192. weight_fp32,
  193. bias_fp32 if has_bias else None,
  194. stride=(SH, SW),
  195. padding=(PH, PW),
  196. dilation=(DH, DW),
  197. groups=groups,
  198. conv_mode=conv_mode,
  199. compute_mode=compute_mode,
  200. )
  201. expected = dtype.convert_to_qint8(expected.numpy(), out_dtype)
  202. expected = dtype.convert_from_qint8(expected)
  203. conv_transpose2d = ConvTranspose2d(
  204. in_channels=IC,
  205. out_channels=OC,
  206. kernel_size=(KH, KW),
  207. stride=(SH, SW),
  208. padding=(PH, PW),
  209. dilation=(DH, DW),
  210. groups=groups,
  211. bias=has_bias,
  212. conv_mode=conv_mode,
  213. compute_mode=compute_mode,
  214. dtype=out_dtype,
  215. )
  216. conv_transpose2d.weight = mge.Parameter(weight_int8)
  217. if has_bias:
  218. conv_transpose2d.bias = mge.Parameter(bias_int32)
  219. result = conv_transpose2d.forward(inp_int8).numpy()
  220. result = dtype.convert_from_qint8(result)
  221. np.testing.assert_allclose(result, expected, atol=out_scale)
  222. test_func(1, 4, 1, 1, 4, 1, 1, 1, 1, 0, 0, 1, 1, 1, False)
  223. test_func(2, 4, 3, 1, 8, 1, 1, 1, 1, 0, 0, 1, 1, 1, False)
  224. test_func(4, 4, 16, 16, 8, 3, 3, 1, 1, 1, 1, 1, 1, 1, False)
  225. test_func(32, 64, 36, 28, 16, 3, 2, 1, 3, 1, 0, 1, 1, 1, False)

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