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_trace_dump.py 4.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import contextlib
  9. import os
  10. import tempfile
  11. import numpy as np
  12. import pytest
  13. import megengine as mge
  14. import megengine.functional as F
  15. import megengine.module as M
  16. import megengine.optimizer as optim
  17. from megengine import tensor
  18. from megengine.autodiff import GradManager
  19. from megengine.jit import trace
  20. @contextlib.contextmanager
  21. def mkstemp():
  22. fd, path = tempfile.mkstemp()
  23. try:
  24. os.close(fd)
  25. yield path
  26. finally:
  27. os.remove(path)
  28. def minibatch_generator(batch_size):
  29. while True:
  30. inp_data = np.zeros((batch_size, 2))
  31. label = np.zeros(batch_size, dtype=np.int32)
  32. for i in range(batch_size):
  33. inp_data[i, :] = np.random.rand(2) * 2 - 1
  34. label[i] = 1 if np.prod(inp_data[i]) < 0 else 0
  35. yield {"data": inp_data.astype(np.float32), "label": label.astype(np.int32)}
  36. class XORNet(M.Module):
  37. def __init__(self):
  38. self.mid_dim = 14
  39. self.num_class = 2
  40. super().__init__()
  41. self.fc0 = M.Linear(self.num_class, self.mid_dim, bias=True)
  42. self.bn0 = M.BatchNorm1d(self.mid_dim)
  43. self.fc1 = M.Linear(self.mid_dim, self.mid_dim, bias=True)
  44. self.bn1 = M.BatchNorm1d(self.mid_dim)
  45. self.fc2 = M.Linear(self.mid_dim, self.num_class, bias=True)
  46. def forward(self, x):
  47. x = self.fc0(x)
  48. x = self.bn0(x)
  49. x = F.tanh(x)
  50. x = self.fc1(x)
  51. x = self.bn1(x)
  52. x = F.tanh(x)
  53. x = self.fc2(x)
  54. return x
  55. def test_xornet_trace_dump():
  56. net = XORNet()
  57. opt = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
  58. gm = GradManager().attach(net.parameters())
  59. batch_size = 64
  60. train_dataset = minibatch_generator(batch_size)
  61. val_dataset = minibatch_generator(batch_size)
  62. @trace
  63. def train_fun(data, label):
  64. with gm:
  65. net.train()
  66. pred = net(data)
  67. loss = F.nn.cross_entropy(pred, label)
  68. gm.backward(loss)
  69. return pred, loss
  70. @trace
  71. def val_fun(data, label):
  72. net.eval()
  73. pred = net(data)
  74. loss = F.nn.cross_entropy(pred, label)
  75. return pred, loss
  76. @trace(symbolic=True, capture_as_const=True)
  77. def pred_fun(data):
  78. net.eval()
  79. pred = net(data)
  80. pred_normalized = F.softmax(pred)
  81. return pred_normalized
  82. train_loss = []
  83. val_loss = []
  84. for step, minibatch in enumerate(train_dataset):
  85. if step > 100:
  86. break
  87. data = tensor(minibatch["data"])
  88. label = tensor(minibatch["label"])
  89. opt.clear_grad()
  90. _, loss = train_fun(data, label)
  91. train_loss.append((step, loss.numpy()))
  92. if step % 50 == 0:
  93. minibatch = next(val_dataset)
  94. _, loss = val_fun(data, label)
  95. loss = loss.numpy()
  96. val_loss.append((step, loss))
  97. print("Step: {} loss={}".format(step, loss))
  98. opt.step()
  99. test_data = np.array(
  100. [
  101. (0.5, 0.5),
  102. (0.3, 0.7),
  103. (0.1, 0.9),
  104. (-0.5, -0.5),
  105. (-0.3, -0.7),
  106. (-0.9, -0.1),
  107. (0.5, -0.5),
  108. (0.3, -0.7),
  109. (0.9, -0.1),
  110. (-0.5, 0.5),
  111. (-0.3, 0.7),
  112. (-0.1, 0.9),
  113. ]
  114. )
  115. data = tensor(test_data.astype(np.float32))
  116. out = pred_fun(data)
  117. pred_output = out.numpy()
  118. pred_label = np.argmax(pred_output, 1)
  119. with np.printoptions(precision=4, suppress=True):
  120. print("Predicated probability:")
  121. print(pred_output)
  122. with mkstemp() as out:
  123. pred_fun.dump(out, arg_names=["data"], output_names=["label"])
  124. def test_dump_bn_train_mode():
  125. @trace(symbolic=True, capture_as_const=True)
  126. def bn_train(data):
  127. pred = M.BatchNorm2d(10)(data).sum()
  128. return pred
  129. data = mge.tensor(np.random.random((10, 10, 10, 10)))
  130. bn_train(data)
  131. with pytest.raises(AssertionError):
  132. bn_train.dump("test.mge")

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