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_correctness.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. import numpy as np
  14. import pytest
  15. import megengine as mge
  16. import megengine.autodiff as ad
  17. import megengine.functional as F
  18. from megengine import jit
  19. from megengine.core._trace_option import set_symbolic_shape
  20. from megengine.core.tensor.utils import make_shape_tuple
  21. from megengine.functional.debug_param import set_conv_execution_strategy
  22. from megengine.jit import SublinearMemoryConfig
  23. from megengine.module import (
  24. AdaptiveAvgPool2d,
  25. AvgPool2d,
  26. BatchNorm2d,
  27. Conv2d,
  28. Linear,
  29. Module,
  30. )
  31. from megengine.optimizer import SGD
  32. from megengine.tensor import Tensor
  33. def get_gpu_name():
  34. try:
  35. gpu_info = subprocess.check_output(
  36. ["nvidia-smi", "--query-gpu=gpu_name", "--format=csv,noheader"]
  37. )
  38. gpu_info = gpu_info.decode("ascii").split("\n")[0]
  39. except:
  40. gpu_info = "None"
  41. return gpu_info
  42. def get_cpu_name():
  43. cpu_info = "None"
  44. try:
  45. cpu_info = subprocess.check_output(["cat", "/proc/cpuinfo"]).decode("ascii")
  46. for line in cpu_info.split("\n"):
  47. if "model name" in line:
  48. return re.sub(".*model name.*:", "", line, 1).strip()
  49. except:
  50. pass
  51. return cpu_info
  52. def get_xpu_name():
  53. if mge.is_cuda_available():
  54. return get_gpu_name()
  55. else:
  56. return get_cpu_name()
  57. class MnistNet(Module):
  58. def __init__(self, has_bn=False, use_adaptive_pooling=False):
  59. super().__init__()
  60. self.conv0 = Conv2d(1, 20, kernel_size=5, bias=True)
  61. if use_adaptive_pooling:
  62. self.pool0 = AdaptiveAvgPool2d(12)
  63. else:
  64. self.pool0 = AvgPool2d(2)
  65. self.conv1 = Conv2d(20, 20, kernel_size=5, bias=True)
  66. self.pool1 = AvgPool2d(2)
  67. self.fc0 = Linear(20 * 4 * 4, 500, bias=True)
  68. self.fc1 = Linear(500, 10, bias=True)
  69. self.bn0 = None
  70. self.bn1 = None
  71. if has_bn:
  72. self.bn0 = BatchNorm2d(20)
  73. self.bn1 = BatchNorm2d(20)
  74. def forward(self, x):
  75. x = self.conv0(x)
  76. if self.bn0:
  77. x = self.bn0(x)
  78. x = F.relu(x)
  79. x = self.pool0(x)
  80. x = self.conv1(x)
  81. if self.bn1:
  82. x = self.bn1(x)
  83. x = F.relu(x)
  84. x = self.pool1(x)
  85. x = F.flatten(x, 1)
  86. x = self.fc0(x)
  87. x = F.relu(x)
  88. x = self.fc1(x)
  89. return x
  90. def train(data, label, net, opt, gm):
  91. with gm:
  92. pred = net(data)
  93. loss = F.nn.cross_entropy(pred, label)
  94. gm.backward(loss)
  95. return loss
  96. def update_model(model_path):
  97. """
  98. Update the dumped model with test cases for new reference values.
  99. The model with pre-trained weights is trained for one iter with the test data attached.
  100. The loss and updated net state dict is dumped.
  101. .. code-block:: python
  102. from test_correctness import update_model
  103. update_model('mnist_model_with_test.mge') # for gpu
  104. update_model('mnist_model_with_test_cpu.mge') # for cpu
  105. """
  106. net = MnistNet(has_bn=True)
  107. checkpoint = mge.load(model_path)
  108. net.load_state_dict(checkpoint["net_init"])
  109. lr = checkpoint["sgd_lr"]
  110. opt = SGD(net.parameters(), lr=lr)
  111. gm = ad.GradManager().attach(net.parameters())
  112. data = Tensor(checkpoint["data"], dtype=np.float32)
  113. label = Tensor(checkpoint["label"], dtype=np.int32)
  114. opt.clear_grad()
  115. loss = train(data, label, net, opt, gm)
  116. opt.step()
  117. xpu_name = get_xpu_name()
  118. checkpoint.update(
  119. {"net_updated": net.state_dict(), "loss": loss.numpy(), "xpu": xpu_name}
  120. )
  121. mge.save(checkpoint, model_path)
  122. def run_train(
  123. model_path,
  124. use_jit,
  125. use_symbolic,
  126. sublinear_memory_config=None,
  127. max_err=None,
  128. use_adaptive_pooling=False,
  129. ):
  130. """
  131. Load the model with test cases and run the training for one iter.
  132. The loss and updated weights are compared with reference value to verify the correctness.
  133. Dump a new file with updated result by calling update_model
  134. if you think the test fails due to numerical rounding errors instead of bugs.
  135. Please think twice before you do so.
  136. """
  137. net = MnistNet(has_bn=True, use_adaptive_pooling=use_adaptive_pooling)
  138. checkpoint = mge.load(model_path)
  139. net.load_state_dict(checkpoint["net_init"])
  140. lr = checkpoint["sgd_lr"]
  141. opt = SGD(net.parameters(), lr=lr)
  142. gm = ad.GradManager().attach(net.parameters())
  143. data = Tensor(checkpoint["data"], dtype=np.float32)
  144. label = Tensor(checkpoint["label"], dtype=np.int32)
  145. if max_err is None:
  146. max_err = 1e-5
  147. train_func = train
  148. if use_jit:
  149. train_func = jit.trace(
  150. train_func,
  151. symbolic=use_symbolic,
  152. sublinear_memory_config=sublinear_memory_config,
  153. )
  154. opt.clear_grad()
  155. loss = train_func(data, label, net, opt, gm)
  156. opt.step()
  157. np.testing.assert_allclose(loss.numpy(), checkpoint["loss"], atol=max_err)
  158. for param, param_ref in zip(
  159. net.state_dict().items(), checkpoint["net_updated"].items()
  160. ):
  161. assert param[0] == param_ref[0]
  162. if "bn" in param[0]:
  163. ref = param_ref[1].reshape(param[1].shape)
  164. np.testing.assert_allclose(param[1], ref, atol=max_err)
  165. else:
  166. np.testing.assert_allclose(param[1], param_ref[1], atol=max_err)
  167. def run_eval(
  168. model_path,
  169. use_symbolic,
  170. sublinear_memory_config=None,
  171. max_err=None,
  172. use_adaptive_pooling=False,
  173. ):
  174. """
  175. Load the model with test cases and run the training for one iter.
  176. The loss and updated weights are compared with reference value to verify the correctness.
  177. Dump a new file with updated result by calling update_model
  178. if you think the test fails due to numerical rounding errors instead of bugs.
  179. Please think twice before you do so.
  180. """
  181. net = MnistNet(has_bn=True, use_adaptive_pooling=use_adaptive_pooling)
  182. checkpoint = mge.load(model_path)
  183. net.load_state_dict(checkpoint["net_init"])
  184. data = Tensor(checkpoint["data"], dtype=np.float32)
  185. def eval_fun(data, *, net=None):
  186. pred = net(data)
  187. return pred
  188. refer_value = eval_fun(data, net=net)
  189. eval_fun = jit.trace(eval_fun, symbolic=use_symbolic)
  190. for _ in range(3):
  191. new_value = eval_fun(data, net=net)
  192. np.testing.assert_allclose(new_value.numpy(), refer_value.numpy(), atol=max_err)
  193. def test_correctness():
  194. if mge.is_cuda_available():
  195. model_name = "mnist_model_with_test.mge"
  196. else:
  197. model_name = "mnist_model_with_test_cpu.mge"
  198. model_path = os.path.join(os.path.dirname(__file__), model_name)
  199. set_conv_execution_strategy("HEURISTIC_REPRODUCIBLE")
  200. run_train(model_path, False, False, max_err=1e-5)
  201. run_train(model_path, True, False, max_err=1e-5)
  202. run_train(model_path, True, True, max_err=1e-5)
  203. # sublinear
  204. config = SublinearMemoryConfig(genetic_nr_iter=10)
  205. run_train(
  206. model_path, True, True, sublinear_memory_config=config, max_err=1e-5,
  207. )
  208. run_eval(model_path, False, max_err=1e-7)
  209. run_eval(model_path, True, max_err=1e-7)
  210. def test_correctness_use_adaptive_pooling():
  211. if mge.is_cuda_available():
  212. model_name = "mnist_model_with_test.mge"
  213. else:
  214. model_name = "mnist_model_with_test_cpu.mge"
  215. model_path = os.path.join(os.path.dirname(__file__), model_name)
  216. set_conv_execution_strategy("HEURISTIC_REPRODUCIBLE")
  217. run_train(model_path, False, False, max_err=1e-5, use_adaptive_pooling=True)
  218. run_train(model_path, True, False, max_err=1e-5, use_adaptive_pooling=True)
  219. run_train(model_path, True, True, max_err=1e-5, use_adaptive_pooling=True)
  220. # sublinear
  221. config = SublinearMemoryConfig(genetic_nr_iter=10)
  222. run_train(
  223. model_path,
  224. True,
  225. True,
  226. sublinear_memory_config=config,
  227. max_err=1e-5,
  228. use_adaptive_pooling=True,
  229. )
  230. run_eval(model_path, False, max_err=1e-7, use_adaptive_pooling=True)
  231. run_eval(model_path, True, max_err=1e-7, use_adaptive_pooling=True)

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