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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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_tensor_shape
  20. from megengine.functional.debug_param import set_conv_execution_strategy
  21. from megengine.jit import SublinearMemoryConfig
  22. from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module
  23. from megengine.optimizer import SGD
  24. from megengine.tensor import Tensor
  25. def get_gpu_name():
  26. try:
  27. gpu_info = subprocess.check_output(
  28. ["nvidia-smi", "--query-gpu=gpu_name", "--format=csv,noheader"]
  29. )
  30. gpu_info = gpu_info.decode("ascii").split("\n")[0]
  31. except:
  32. gpu_info = "None"
  33. return gpu_info
  34. def get_cpu_name():
  35. cpu_info = "None"
  36. try:
  37. cpu_info = subprocess.check_output(["cat", "/proc/cpuinfo"]).decode("ascii")
  38. for line in cpu_info.split("\n"):
  39. if "model name" in line:
  40. return re.sub(".*model name.*:", "", line, 1).strip()
  41. except:
  42. pass
  43. return cpu_info
  44. def get_xpu_name():
  45. if mge.is_cuda_available():
  46. return get_gpu_name()
  47. else:
  48. return get_cpu_name()
  49. class MnistNet(Module):
  50. def __init__(self, has_bn=False):
  51. super().__init__()
  52. self.conv0 = Conv2d(1, 20, kernel_size=5, bias=True)
  53. self.pool0 = AvgPool2d(2)
  54. self.conv1 = Conv2d(20, 20, kernel_size=5, bias=True)
  55. self.pool1 = AvgPool2d(2)
  56. self.fc0 = Linear(20 * 4 * 4, 500, bias=True)
  57. self.fc1 = Linear(500, 10, bias=True)
  58. self.bn0 = None
  59. self.bn1 = None
  60. if has_bn:
  61. self.bn0 = BatchNorm2d(20)
  62. self.bn1 = BatchNorm2d(20)
  63. def forward(self, x):
  64. x = self.conv0(x)
  65. if self.bn0:
  66. x = self.bn0(x)
  67. x = F.relu(x)
  68. x = self.pool0(x)
  69. x = self.conv1(x)
  70. if self.bn1:
  71. x = self.bn1(x)
  72. x = F.relu(x)
  73. x = self.pool1(x)
  74. x = F.flatten(x, 1)
  75. x = self.fc0(x)
  76. x = F.relu(x)
  77. x = self.fc1(x)
  78. return x
  79. def train(data, label, net, opt, gm):
  80. with gm:
  81. pred = net(data)
  82. loss = F.cross_entropy_with_softmax(pred, label)
  83. gm.backward(loss)
  84. return loss
  85. def update_model(model_path):
  86. """
  87. Update the dumped model with test cases for new reference values.
  88. The model with pre-trained weights is trained for one iter with the test data attached.
  89. The loss and updated net state dict is dumped.
  90. .. code-block:: python
  91. from test_correctness import update_model
  92. update_model('mnist_model_with_test.mge') # for gpu
  93. update_model('mnist_model_with_test_cpu.mge') # for cpu
  94. """
  95. net = MnistNet(has_bn=True)
  96. checkpoint = mge.load(model_path)
  97. net.load_state_dict(checkpoint["net_init"])
  98. lr = checkpoint["sgd_lr"]
  99. opt = SGD(net.parameters(), lr=lr)
  100. gm = ad.GradManager().attach(net.parameters())
  101. data = Tensor(checkpoint["data"], dtype=np.float32)
  102. label = Tensor(checkpoint["label"], dtype=np.int32)
  103. opt.clear_grad()
  104. loss = train(data, label, net, opt, gm)
  105. opt.step()
  106. xpu_name = get_xpu_name()
  107. checkpoint.update(
  108. {"net_updated": net.state_dict(), "loss": loss.numpy(), "xpu": xpu_name}
  109. )
  110. mge.save(checkpoint, model_path)
  111. def run_train(
  112. model_path, use_jit, use_symbolic, sublinear_memory_config=None, max_err=None,
  113. ):
  114. """
  115. Load the model with test cases and run the training for one iter.
  116. The loss and updated weights are compared with reference value to verify the correctness.
  117. Dump a new file with updated result by calling update_model
  118. if you think the test fails due to numerical rounding errors instead of bugs.
  119. Please think twice before you do so.
  120. """
  121. net = MnistNet(has_bn=True)
  122. checkpoint = mge.load(model_path)
  123. net.load_state_dict(checkpoint["net_init"])
  124. lr = checkpoint["sgd_lr"]
  125. opt = SGD(net.parameters(), lr=lr)
  126. gm = ad.GradManager().attach(net.parameters())
  127. data = Tensor(checkpoint["data"], dtype=np.float32)
  128. label = Tensor(checkpoint["label"], dtype=np.int32)
  129. if max_err is None:
  130. max_err = 1e-5
  131. train_func = train
  132. if use_jit:
  133. train_func = jit.trace(
  134. train_func,
  135. symbolic=use_symbolic,
  136. sublinear_memory_config=sublinear_memory_config,
  137. )
  138. opt.clear_grad()
  139. loss = train_func(data, label, net, opt, gm)
  140. opt.step()
  141. np.testing.assert_allclose(loss.numpy(), checkpoint["loss"], atol=max_err)
  142. for param, param_ref in zip(
  143. net.state_dict().items(), checkpoint["net_updated"].items()
  144. ):
  145. assert param[0] == param_ref[0]
  146. np.testing.assert_allclose(param[1], param_ref[1], atol=max_err)
  147. def run_eval(
  148. model_path, use_symbolic, sublinear_memory_config=None, max_err=None,
  149. ):
  150. """
  151. Load the model with test cases and run the training for one iter.
  152. The loss and updated weights are compared with reference value to verify the correctness.
  153. Dump a new file with updated result by calling update_model
  154. if you think the test fails due to numerical rounding errors instead of bugs.
  155. Please think twice before you do so.
  156. """
  157. net = MnistNet(has_bn=True)
  158. checkpoint = mge.load(model_path)
  159. net.load_state_dict(checkpoint["net_init"])
  160. data = Tensor(checkpoint["data"], dtype=np.float32)
  161. def eval_fun(data, *, net=None):
  162. pred = net(data)
  163. return pred
  164. refer_value = eval_fun(data, net=net)
  165. eval_fun = jit.trace(eval_fun, symbolic=use_symbolic)
  166. for _ in range(3):
  167. new_value = eval_fun(data, net=net)
  168. np.testing.assert_allclose(new_value.numpy(), refer_value.numpy(), atol=max_err)
  169. def test_correctness():
  170. if mge.is_cuda_available():
  171. model_name = "mnist_model_with_test.mge"
  172. else:
  173. model_name = "mnist_model_with_test_cpu.mge"
  174. model_path = os.path.join(os.path.dirname(__file__), model_name)
  175. set_conv_execution_strategy("HEURISTIC_REPRODUCIBLE")
  176. run_train(model_path, False, False, max_err=1e-5)
  177. run_train(model_path, True, False, max_err=1e-5)
  178. run_train(model_path, True, True, max_err=1e-5)
  179. # sublinear
  180. config = SublinearMemoryConfig(genetic_nr_iter=10)
  181. run_train(
  182. model_path, True, True, sublinear_memory_config=config, max_err=1e-5,
  183. )
  184. run_eval(model_path, False, max_err=1e-7)
  185. run_eval(model_path, True, max_err=1e-7)

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