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.3 kB

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

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