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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 sys
  11. import numpy as np
  12. import megengine as mge
  13. import megengine.functional as F
  14. from megengine import jit, tensor
  15. from megengine.functional.debug_param import set_conv_execution_strategy
  16. from megengine.module import BatchNorm2d, Conv2d, Linear, MaxPool2d, Module
  17. from megengine.optimizer import SGD
  18. from megengine.test import assertTensorClose
  19. class MnistNet(Module):
  20. def __init__(self, has_bn=False):
  21. super().__init__()
  22. self.conv0 = Conv2d(1, 20, kernel_size=5, bias=True)
  23. self.pool0 = MaxPool2d(2)
  24. self.conv1 = Conv2d(20, 20, kernel_size=5, bias=True)
  25. self.pool1 = MaxPool2d(2)
  26. self.fc0 = Linear(20 * 4 * 4, 500, bias=True)
  27. self.fc1 = Linear(500, 10, bias=True)
  28. self.bn0 = None
  29. self.bn1 = None
  30. if has_bn:
  31. self.bn0 = BatchNorm2d(20)
  32. self.bn1 = BatchNorm2d(20)
  33. def forward(self, x):
  34. x = self.conv0(x)
  35. if self.bn0:
  36. x = self.bn0(x)
  37. x = F.relu(x)
  38. x = self.pool0(x)
  39. x = self.conv1(x)
  40. if self.bn1:
  41. x = self.bn1(x)
  42. x = F.relu(x)
  43. x = self.pool1(x)
  44. x = F.flatten(x, 1)
  45. x = self.fc0(x)
  46. x = F.relu(x)
  47. x = self.fc1(x)
  48. return x
  49. def train(data, label, net, opt):
  50. pred = net(data)
  51. loss = F.cross_entropy_with_softmax(pred, label)
  52. opt.backward(loss)
  53. return loss
  54. def update_model(model_path):
  55. """
  56. Update the dumped model with test cases for new reference values
  57. """
  58. net = MnistNet(has_bn=True)
  59. checkpoint = mge.load(model_path)
  60. net.load_state_dict(checkpoint["net_init"])
  61. lr = checkpoint["sgd_lr"]
  62. opt = SGD(net.parameters(), lr=lr)
  63. data = tensor(dtype=np.float32)
  64. label = tensor(dtype=np.int32)
  65. data.set_value(checkpoint["data"])
  66. label.set_value(checkpoint["label"])
  67. opt.zero_grad()
  68. loss = train(data, label, net=net, opt=opt)
  69. opt.step()
  70. checkpoint.update({"net_updated": net.state_dict(), "loss": loss.numpy()})
  71. mge.save(checkpoint, model_path)
  72. def run_test(model_path, use_jit, use_symbolic):
  73. """
  74. Load the model with test cases and run the training for one iter.
  75. The loss and updated weights are compared with reference value to verify the correctness.
  76. The model with pre-trained weights is trained for one iter and the net state dict is dumped.
  77. The test cases is appended to the model file. The reference result is obtained
  78. by running the train for one iter.
  79. Dump a new file with updated result by calling update_model
  80. if you think the test fails due to numerical rounding errors instead of bugs.
  81. Please think twice before you do so.
  82. """
  83. net = MnistNet(has_bn=True)
  84. checkpoint = mge.load(model_path)
  85. net.load_state_dict(checkpoint["net_init"])
  86. lr = checkpoint["sgd_lr"]
  87. opt = SGD(net.parameters(), lr=lr)
  88. data = tensor(dtype=np.float32)
  89. label = tensor(dtype=np.int32)
  90. data.set_value(checkpoint["data"])
  91. label.set_value(checkpoint["label"])
  92. max_err = 0.0
  93. train_func = train
  94. if use_jit:
  95. train_func = jit.trace(train_func, symbolic=use_symbolic)
  96. opt.zero_grad()
  97. loss = train_func(data, label, net=net, opt=opt)
  98. opt.step()
  99. assertTensorClose(loss.numpy(), checkpoint["loss"], max_err=max_err)
  100. for param, param_ref in zip(
  101. net.state_dict().items(), checkpoint["net_updated"].items()
  102. ):
  103. assert param[0] == param_ref[0]
  104. assertTensorClose(param[1], param_ref[1], max_err=max_err)
  105. def test_correctness():
  106. if mge.is_cuda_available():
  107. model_name = "mnist_model_with_test.mge"
  108. else:
  109. model_name = "mnist_model_with_test_cpu.mge"
  110. model_path = os.path.join(os.path.dirname(__file__), model_name)
  111. set_conv_execution_strategy("HEURISTIC_REPRODUCIBLE")
  112. run_test(model_path, False, False)
  113. run_test(model_path, True, False)
  114. run_test(model_path, True, True)

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

Contributors (1)