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_module.py 8.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 tempfile
  10. from io import BytesIO
  11. import numpy as np
  12. import pytest
  13. from helpers import MLP
  14. import megengine as mge
  15. from megengine.core import Buffer, Parameter, tensor
  16. from megengine.module import BatchNorm1d, BatchNorm2d, Conv2d, Module, Sequential
  17. from megengine.test import assertTensorClose
  18. class MyModule(Module):
  19. class InnerModule(Module):
  20. def __init__(self):
  21. super().__init__()
  22. self.bn = BatchNorm2d(4)
  23. def forward(self, x):
  24. x = self.bn(x)
  25. def __init__(self):
  26. super().__init__()
  27. self.i = self.InnerModule()
  28. self.bn = BatchNorm2d(4)
  29. self.param = Parameter(np.ones(1, dtype=np.float32))
  30. self.buff = Buffer(np.ones(1, dtype=np.float32))
  31. def forward(self, x):
  32. x = self.i(x)
  33. x = self.bn(x)
  34. return x
  35. def test_module_api():
  36. m = MyModule()
  37. assert list(m.children()) == [m.bn, m.i]
  38. assert list(m.named_children()) == [("bn", m.bn), ("i", m.i)]
  39. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  40. assert list(m.named_modules()) == [
  41. ("", m),
  42. ("bn", m.bn),
  43. ("i", m.i),
  44. ("i.bn", m.i.bn),
  45. ]
  46. assert list(m.named_modules(prefix="x")) == [
  47. ("x", m),
  48. ("x.bn", m.bn),
  49. ("x.i", m.i),
  50. ("x.i.bn", m.i.bn),
  51. ]
  52. assert list(m.buffers()) == [
  53. m.bn.running_mean,
  54. m.bn.running_var,
  55. m.buff,
  56. m.i.bn.running_mean,
  57. m.i.bn.running_var,
  58. ]
  59. assert list(m.buffers(recursive=False)) == [m.buff]
  60. assert list(m.named_buffers()) == [
  61. ("bn.running_mean", m.bn.running_mean),
  62. ("bn.running_var", m.bn.running_var),
  63. ("buff", m.buff),
  64. ("i.bn.running_mean", m.i.bn.running_mean),
  65. ("i.bn.running_var", m.i.bn.running_var),
  66. ]
  67. assert list(m.parameters()) == [
  68. m.bn.bias,
  69. m.bn.weight,
  70. m.i.bn.bias,
  71. m.i.bn.weight,
  72. m.param,
  73. ]
  74. assert list(m.named_parameters()) == [
  75. ("bn.bias", m.bn.bias),
  76. ("bn.weight", m.bn.weight),
  77. ("i.bn.bias", m.i.bn.bias),
  78. ("i.bn.weight", m.i.bn.weight),
  79. ("param", m.param),
  80. ]
  81. m.eval()
  82. assert (
  83. m.training == False
  84. and m.bn.training == False
  85. and m.i.training == False
  86. and m.i.bn.training == False
  87. )
  88. m.bn.train()
  89. assert m.training == False and m.bn.training == True and m.i.bn.training == False
  90. m.eval()
  91. m.i.train()
  92. assert (
  93. m.training == False
  94. and m.bn.training == False
  95. and m.i.training == True
  96. and m.i.bn.training == True
  97. )
  98. m.eval()
  99. m.train()
  100. assert m.training == True and m.bn.training == True and m.i.bn.training == True
  101. def fn(m):
  102. m.training = False
  103. m.apply(fn)
  104. assert m.bn.training == False and m.i.bn.training == False
  105. def test_module_api_reuse_submodule():
  106. m = MyModule()
  107. m.h = m.i # pylint: disable=attribute-defined-outside-init
  108. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  109. assert list(m.named_modules()) == [
  110. ("", m),
  111. ("bn", m.bn),
  112. ("h", m.i),
  113. ("h.bn", m.i.bn),
  114. ]
  115. def test_module_api_iterable_stability():
  116. m = MyModule()
  117. l = list(m.modules())
  118. for _ in range(100):
  119. assert list(m.modules()) == l
  120. class MyModule2(Module):
  121. class InnerModule(Module):
  122. def __init__(self):
  123. super().__init__()
  124. self.bn = BatchNorm2d(4)
  125. def forward(self, x):
  126. x = self.bn(x)
  127. def __init__(self):
  128. super().__init__()
  129. self.bn = BatchNorm2d(4)
  130. self.a = [
  131. BatchNorm2d(4),
  132. {"x": BatchNorm2d(4), "y": [BatchNorm2d(4), self.InnerModule()]},
  133. (self.InnerModule(),),
  134. ]
  135. def forward(self, x):
  136. return x
  137. def test_expand_structure():
  138. m = MyModule2()
  139. assert list(m.named_modules()) == [
  140. ("", m),
  141. ("a.0", m.a[0]),
  142. ("a.1.x", m.a[1]["x"]),
  143. ("a.1.y.0", m.a[1]["y"][0]),
  144. ("a.1.y.1", m.a[1]["y"][1]),
  145. ("a.1.y.1.bn", m.a[1]["y"][1].bn),
  146. ("a.2.0", m.a[2][0]),
  147. ("a.2.0.bn", m.a[2][0].bn),
  148. ("bn", m.bn),
  149. ]
  150. def test_flatten_with_parent():
  151. m = MyModule2()
  152. assert list(m.named_modules(with_parent=True)) == [
  153. ("", m, None),
  154. ("a.0", m.a[0], m),
  155. ("a.1.x", m.a[1]["x"], m),
  156. ("a.1.y.0", m.a[1]["y"][0], m),
  157. ("a.1.y.1", m.a[1]["y"][1], m),
  158. ("a.1.y.1.bn", m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  159. ("a.2.0", m.a[2][0], m),
  160. ("a.2.0.bn", m.a[2][0].bn, m.a[2][0]),
  161. ("bn", m.bn, m),
  162. ]
  163. assert list(m.modules(with_parent=True)) == [
  164. (m, None),
  165. (m.a[0], m),
  166. (m.a[1]["x"], m),
  167. (m.a[1]["y"][0], m),
  168. (m.a[1]["y"][1], m),
  169. (m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  170. (m.a[2][0], m),
  171. (m.a[2][0].bn, m.a[2][0]),
  172. (m.bn, m),
  173. ]
  174. class MyModule3(Module):
  175. class InnerModule(Module):
  176. def __init__(self):
  177. super().__init__()
  178. self.bn = BatchNorm2d(4)
  179. def forward(self, x):
  180. x = self.bn(x)
  181. def __init__(self):
  182. super().__init__()
  183. self.bn = BatchNorm2d(4)
  184. self.seq = Sequential(BatchNorm2d(4), self.InnerModule(),)
  185. def forward(self, x):
  186. return x
  187. def test_module_api_with_sequential():
  188. m = MyModule3()
  189. assert list(m.named_modules()) == [
  190. ("", m),
  191. ("bn", m.bn),
  192. ("seq", m.seq),
  193. ("seq.0", m.seq[0]),
  194. ("seq.1", m.seq[1]),
  195. ("seq.1.bn", m.seq[1].bn),
  196. ]
  197. def test_state_dict():
  198. data_shape = (2, 28)
  199. data = tensor()
  200. data.set_value(np.random.random(data_shape))
  201. mlp = MLP()
  202. pred0 = mlp(data)
  203. with BytesIO() as fout:
  204. mge.save(mlp.state_dict(), fout)
  205. fout.seek(0)
  206. state_dict = mge.load(fout)
  207. state_dict["extra"] = None
  208. mlp1 = MLP()
  209. mlp1.load_state_dict(state_dict, strict=False)
  210. pred1 = mlp1(data)
  211. assertTensorClose(pred0.numpy(), pred1.numpy(), max_err=5e-6)
  212. with pytest.raises(KeyError):
  213. mlp1.load_state_dict(state_dict)
  214. del state_dict["extra"]
  215. del state_dict["dense0.bias"]
  216. with pytest.raises(KeyError):
  217. mlp1.load_state_dict(state_dict)
  218. class Simple(Module):
  219. def __init__(self):
  220. super().__init__()
  221. self.conv0 = Conv2d(1, 1, kernel_size=3, bias=False)
  222. self.conv1 = Conv2d(1, 1, kernel_size=3, bias=False)
  223. self.conv1.weight = self.conv0.weight
  224. def forward(self, inputs):
  225. pass
  226. def test_shared_param():
  227. net = Simple()
  228. assert net.conv0.weight is net.conv1.weight
  229. data = tensor(np.random.random((1, 1, 8, 8)).astype(np.float32))
  230. assertTensorClose(net.conv0(data).numpy(), net.conv1(data).numpy())
  231. with BytesIO() as f:
  232. mge.save(net, f)
  233. f.seek(0)
  234. net1 = mge.load(f)
  235. assert net1.conv0.weight is net1.conv1.weight
  236. assertTensorClose(net1.conv0(data).numpy(), net1.conv1(data).numpy())
  237. with BytesIO() as f:
  238. mge.save(net.conv0, f)
  239. f.seek(0)
  240. conv0 = mge.load(f)
  241. with BytesIO() as f:
  242. mge.save(net.conv1, f)
  243. f.seek(0)
  244. conv1 = mge.load(f)
  245. assert conv0.weight is not conv1.weight
  246. assertTensorClose(conv0(data).numpy(), conv1(data).numpy())
  247. def test_pickle_module():
  248. data_shape = (2, 28)
  249. data = tensor()
  250. data.set_value(np.random.random(data_shape))
  251. mlp = MLP()
  252. # pickle before forward
  253. with BytesIO() as fout:
  254. mge.save(mlp, fout)
  255. fout.seek(0)
  256. mlp1 = mge.load(fout)
  257. pred0 = mlp1(data)
  258. pred1 = mlp(data)
  259. # pickle after forward
  260. with BytesIO() as fout:
  261. mge.save(mlp, fout)
  262. fout.seek(0)
  263. mlp1 = mge.load(fout)
  264. pred2 = mlp1(data)
  265. assertTensorClose(pred0.numpy(), pred1.numpy(), max_err=5e-6)
  266. assertTensorClose(pred0.numpy(), pred2.numpy(), max_err=5e-6)
  267. def test_dump_model():
  268. data_shape = (2, 28)
  269. data = tensor()
  270. data.set_value(np.random.random(data_shape))
  271. mlp = MLP()
  272. pred = mlp(data)
  273. with tempfile.NamedTemporaryFile() as f:
  274. mge.dump(pred, f.name)

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