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

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

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