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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import numpy as np
  2. import pytest
  3. import megengine as mge
  4. import megengine.functional as F
  5. from megengine.core.tensor import dtype
  6. from megengine.distributed.helper import get_device_count_by_fork
  7. from megengine.functional.elemwise import _elemwise_multi_type, _elwise
  8. def quant(x, scale):
  9. x_dtype = dtype.qint8(scale)
  10. return x.astype(x_dtype)
  11. def fake_quant(x, scale):
  12. x = x / scale
  13. x = F.round(x)
  14. x = F.clip(x, -128, 127)
  15. x = x * scale
  16. return x
  17. @pytest.mark.parametrize("kind", ["ABS", "SIN", "SUB", "MUL", "FUSE_ADD_TANH"])
  18. def test_elemwise(kind):
  19. x1 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32"))
  20. x1_scale = np.float32(np.random.rand() + 1)
  21. x1 = fake_quant(x1, x1_scale)
  22. x1.q_dict["scale"] = x1_scale
  23. x1_int8 = quant(x1, x1_scale)
  24. x2 = mge.tensor(np.random.normal(size=(3, 3)).astype("float32"))
  25. x2_scale = np.float32(np.random.rand() + 1)
  26. x2 = fake_quant(x2, x2_scale)
  27. x2.q_dict["scale"] = x2_scale
  28. x2_int8 = quant(x2, x2_scale)
  29. output_scale = np.float32(np.random.rand() + 1)
  30. output_dtype = dtype.qint8(output_scale)
  31. quantized_kind = "Q" + kind
  32. if kind in ("ABS", "SIN"):
  33. desired_out = fake_quant(_elwise(x1, mode=kind), output_scale)
  34. actual_out = (
  35. _elemwise_multi_type(
  36. x1_int8, mode=quantized_kind, dtype=output_dtype
  37. ).numpy()
  38. * output_scale
  39. )
  40. else:
  41. desired_out = fake_quant(_elwise(x1, x2, mode=kind), output_scale)
  42. actual_out = (
  43. _elemwise_multi_type(
  44. x1_int8, x2_int8, mode=quantized_kind, dtype=output_dtype
  45. ).numpy()
  46. * output_scale
  47. )
  48. np.testing.assert_allclose(actual_out, desired_out.numpy())
  49. @pytest.mark.skipif(
  50. get_device_count_by_fork("gpu") > 0, reason="cuda does not support nchw int8"
  51. )
  52. def test_conv_bias():
  53. inp_scale = np.float32(np.random.rand() + 1)
  54. w_scale = np.float32(np.random.rand() + 1)
  55. outp_scale = np.float32(np.random.rand() + 1)
  56. inp_dtype = dtype.qint8(inp_scale)
  57. w_dtype = dtype.qint8(w_scale)
  58. b_dtype = dtype.qint32(inp_scale * w_scale)
  59. out_dtype = dtype.qint8(outp_scale)
  60. def run(
  61. N,
  62. IC,
  63. OC,
  64. IH,
  65. IW,
  66. KH,
  67. KW,
  68. PH,
  69. PW,
  70. SH,
  71. SW,
  72. has_bias=True,
  73. nonlinear_mode="IDENTITY",
  74. ):
  75. inp_v = np.random.normal(size=(N, IC, IH, IW))
  76. w_v = np.random.normal(size=(OC, IC, KH, KW))
  77. b_v = np.random.normal(size=(1, OC, 1, 1))
  78. inp_scale = dtype.get_scale(inp_dtype)
  79. w_scale = dtype.get_scale(w_dtype)
  80. b_scale = dtype.get_scale(b_dtype)
  81. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  82. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  83. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  84. inp_int8 = mge.tensor(inpv, dtype=inp_dtype)
  85. w_int8 = mge.Parameter(wv, dtype=w_dtype)
  86. b_int32 = mge.Parameter(bv, dtype=b_dtype)
  87. inp_fp32 = inp_int8.astype("float32")
  88. w_fp32 = w_int8.astype("float32")
  89. b_fp32 = b_int32.astype("float32")
  90. def convert_to_nchw4(var):
  91. var = F.reshape(
  92. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  93. )
  94. var = F.transpose(var, (0, 1, 3, 4, 2))
  95. return var
  96. def run_conv2d(inp, w, b):
  97. O = F.conv2d(
  98. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  99. )
  100. if nonlinear_mode == "RELU":
  101. return F.relu(O)
  102. else:
  103. return O
  104. def run_conv_bias(inp, w, b, format="NCHW"):
  105. b = b if has_bias else mge.Parameter(np.zeros_like(b.numpy()))
  106. if format == "NCHW4":
  107. inp = convert_to_nchw4(inp)
  108. w = convert_to_nchw4(w)
  109. b = convert_to_nchw4(b)
  110. return F.quantized.conv_bias_activation(
  111. inp,
  112. w,
  113. b,
  114. stride=(SH, SW),
  115. padding=(PH, PW),
  116. dtype=out_dtype,
  117. nonlinear_mode=nonlinear_mode,
  118. )
  119. format = "NCHW4" if mge.is_cuda_available() else "NCHW"
  120. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  121. expected = expected.astype(out_dtype).astype("float32")
  122. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  123. "float32"
  124. )
  125. if format == "NCHW4":
  126. result = F.transpose(result, (0, 1, 4, 2, 3))
  127. expected = F.flatten(expected)
  128. result = F.flatten(result)
  129. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  130. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  131. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  132. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  133. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  134. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  135. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  136. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "RELU")
  137. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "RELU")

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