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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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. from collections import OrderedDict
  10. from io import BytesIO
  11. import numpy as np
  12. import pytest
  13. import megengine as mge
  14. import megengine.functional as F
  15. from megengine import Parameter, Tensor, tensor
  16. from megengine.module import (
  17. BatchNorm1d,
  18. BatchNorm2d,
  19. Conv1d,
  20. Conv2d,
  21. Dropout,
  22. Linear,
  23. MaxPool2d,
  24. Module,
  25. Sequential,
  26. Softmax,
  27. )
  28. from megengine.module.module import _access_structure
  29. from megengine.quantization.quantize import quantize, quantize_qat
  30. from megengine.traced_module import TracedModule, trace_module
  31. from megengine.utils.module_utils import get_expand_structure, set_expand_structure
  32. class MLP(Module):
  33. def __init__(self):
  34. super().__init__()
  35. self.dense0 = Linear(28, 50)
  36. self.dense1 = Linear(50, 20)
  37. def forward(self, x):
  38. x = self.dense0(x)
  39. x = F.relu(x)
  40. x = self.dense1(x)
  41. return x
  42. class MyModule(Module):
  43. class InnerModule(Module):
  44. def __init__(self):
  45. super().__init__()
  46. self.bn = BatchNorm2d(4)
  47. def forward(self, x):
  48. return self.bn(x)
  49. def __init__(self):
  50. super().__init__()
  51. self.i = self.InnerModule()
  52. self.bn = BatchNorm2d(4)
  53. self.param = Parameter(np.ones(1, dtype=np.float32))
  54. self.buff = Tensor(np.ones(1, dtype=np.float32))
  55. def forward(self, x):
  56. x = self.i(x)
  57. x = self.bn(x)
  58. return x
  59. @pytest.mark.parametrize("test_traced_module", [True, False])
  60. def test_module_api(test_traced_module):
  61. m = MyModule()
  62. if test_traced_module:
  63. buff = m.buff
  64. param = m.param
  65. m = trace_module(m, Tensor(np.random.random((1, 4, 16, 16))))
  66. assert "buff" not in m.__dict__
  67. assert "param" not in m.__dict__
  68. m.buff = buff
  69. m.param = param
  70. assert list(m.children()) == [m.bn, m.i]
  71. assert list(m.named_children()) == [("bn", m.bn), ("i", m.i)]
  72. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  73. assert list(m.named_modules()) == [
  74. ("", m),
  75. ("bn", m.bn),
  76. ("i", m.i),
  77. ("i.bn", m.i.bn),
  78. ]
  79. assert list(m.named_modules(prefix="x")) == [
  80. ("x", m),
  81. ("x.bn", m.bn),
  82. ("x.i", m.i),
  83. ("x.i.bn", m.i.bn),
  84. ]
  85. assert list(m.buffers()) == [
  86. m.bn.running_mean,
  87. m.bn.running_var,
  88. m.buff,
  89. m.i.bn.running_mean,
  90. m.i.bn.running_var,
  91. ]
  92. assert list(m.buffers(recursive=False)) == [m.buff]
  93. assert list(m.named_buffers()) == [
  94. ("bn.running_mean", m.bn.running_mean),
  95. ("bn.running_var", m.bn.running_var),
  96. ("buff", m.buff),
  97. ("i.bn.running_mean", m.i.bn.running_mean),
  98. ("i.bn.running_var", m.i.bn.running_var),
  99. ]
  100. assert list(m.parameters()) == [
  101. m.bn.bias,
  102. m.bn.weight,
  103. m.i.bn.bias,
  104. m.i.bn.weight,
  105. m.param,
  106. ]
  107. assert list(m.named_parameters()) == [
  108. ("bn.bias", m.bn.bias),
  109. ("bn.weight", m.bn.weight),
  110. ("i.bn.bias", m.i.bn.bias),
  111. ("i.bn.weight", m.i.bn.weight),
  112. ("param", m.param),
  113. ]
  114. assert list(m.tensors()) == [
  115. m.bn.bias,
  116. m.bn.running_mean,
  117. m.bn.running_var,
  118. m.bn.weight,
  119. m.buff,
  120. m.i.bn.bias,
  121. m.i.bn.running_mean,
  122. m.i.bn.running_var,
  123. m.i.bn.weight,
  124. m.param,
  125. ]
  126. assert list(m.named_tensors()) == [
  127. ("bn.bias", m.bn.bias),
  128. ("bn.running_mean", m.bn.running_mean),
  129. ("bn.running_var", m.bn.running_var),
  130. ("bn.weight", m.bn.weight),
  131. ("buff", m.buff),
  132. ("i.bn.bias", m.i.bn.bias),
  133. ("i.bn.running_mean", m.i.bn.running_mean),
  134. ("i.bn.running_var", m.i.bn.running_var),
  135. ("i.bn.weight", m.i.bn.weight),
  136. ("param", m.param),
  137. ]
  138. m.eval()
  139. assert (
  140. m.training == False
  141. and m.bn.training == False
  142. and m.i.training == False
  143. and m.i.bn.training == False
  144. )
  145. m.bn.train()
  146. assert m.training == False and m.bn.training == True and m.i.bn.training == False
  147. m.eval()
  148. m.i.train()
  149. assert (
  150. m.training == False
  151. and m.bn.training == False
  152. and m.i.training == True
  153. and m.i.bn.training == True
  154. )
  155. m.eval()
  156. m.train()
  157. assert m.training == True and m.bn.training == True and m.i.bn.training == True
  158. def fn(m):
  159. m.training = False
  160. m.apply(fn)
  161. assert m.bn.training == False and m.i.bn.training == False
  162. @pytest.mark.parametrize("test_traced_module", [True, False])
  163. def test_module_api_reuse_submodule(test_traced_module):
  164. m = MyModule()
  165. if test_traced_module:
  166. m = trace_module(m, Tensor(np.random.random((1, 4, 16, 16))))
  167. m.h = m.i # pylint: disable=attribute-defined-outside-init
  168. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  169. assert list(m.named_modules()) == [
  170. ("", m),
  171. ("bn", m.bn),
  172. ("h", m.i),
  173. ("h.bn", m.i.bn),
  174. ]
  175. @pytest.mark.parametrize("test_traced_module", [True, False])
  176. def test_module_api_iterable_stability(test_traced_module):
  177. m = MyModule()
  178. if test_traced_module:
  179. m = trace_module(m, Tensor(np.random.random((1, 4, 16, 16))))
  180. l = list(m.modules())
  181. for _ in range(100):
  182. assert list(m.modules()) == l
  183. @pytest.mark.parametrize("test_traced_module", [True, False])
  184. def test_module_api_hooks(test_traced_module):
  185. net = MyModule()
  186. if test_traced_module:
  187. net = trace_module(net, Tensor(np.zeros((1, 4, 1, 1))))
  188. pre_hook_num = 0
  189. post_hook_num = 0
  190. hooks = []
  191. def pre_hook(_, inputs):
  192. nonlocal pre_hook_num
  193. pre_hook_num += 1
  194. modified_inputs = tuple(inp + 1 for inp in inputs)
  195. return modified_inputs
  196. def post_hook(_, __, outputs):
  197. nonlocal post_hook_num
  198. post_hook_num += 1
  199. outputs += 1
  200. return outputs
  201. net.apply(lambda module: hooks.append(module.register_forward_pre_hook(pre_hook)))
  202. net.apply(lambda module: hooks.append(module.register_forward_hook(post_hook)))
  203. shape = (1, 4, 1, 1)
  204. x = tensor(np.zeros(shape, dtype=np.float32))
  205. y = net(x)
  206. assert pre_hook_num == 4
  207. assert post_hook_num == 4
  208. mean1 = Parameter(np.zeros(shape), dtype=np.float32)
  209. bn1 = F.batch_norm(
  210. x + 3, mean1, Parameter(np.ones(shape), dtype=np.float32), training=True
  211. )
  212. np.testing.assert_allclose(
  213. net.i.bn.running_mean.numpy(), mean1.numpy(),
  214. )
  215. mean2 = Parameter(np.zeros(shape), dtype=np.float32)
  216. bn2 = F.batch_norm(
  217. bn1 + 3, mean2, Parameter(np.ones(shape), dtype=np.float32), training=True
  218. )
  219. np.testing.assert_allclose(
  220. net.bn.running_mean.numpy(), mean2.numpy(),
  221. )
  222. np.testing.assert_allclose((bn2 + 2).numpy(), y.numpy())
  223. assert len(hooks) == 8
  224. for handler in hooks:
  225. handler.remove()
  226. y = net(x)
  227. assert pre_hook_num == 4
  228. assert post_hook_num == 4
  229. class MyModule2(Module):
  230. class InnerModule(Module):
  231. def __init__(self):
  232. super().__init__()
  233. self.bn = BatchNorm2d(4)
  234. self.test_bool_key = {True: 1, False: 0}
  235. def forward(self, x):
  236. x = self.bn(x)
  237. def __init__(self):
  238. super().__init__()
  239. self.bn = BatchNorm2d(4)
  240. self.a = [
  241. BatchNorm2d(4),
  242. {"x": BatchNorm2d(4), "y": [BatchNorm2d(4), self.InnerModule()], "z": 0},
  243. (self.InnerModule(),),
  244. ]
  245. def forward(self, x):
  246. return x
  247. def test_expand_structure():
  248. m = MyModule2()
  249. rst = [
  250. ("", m),
  251. ("a.0", m.a[0]),
  252. ("a.1.x", m.a[1]["x"]),
  253. ("a.1.y.0", m.a[1]["y"][0]),
  254. ("a.1.y.1", m.a[1]["y"][1]),
  255. ("a.1.y.1.bn", m.a[1]["y"][1].bn),
  256. ("a.2.0", m.a[2][0]),
  257. ("a.2.0.bn", m.a[2][0].bn),
  258. ("bn", m.bn),
  259. ]
  260. assert list(m.named_modules()) == rst
  261. for item in rst[1:]:
  262. assert get_expand_structure(m, item[0]) == item[1]
  263. for item in reversed(rst[1:]):
  264. if _access_structure(m, item[0], lambda p, k, o: isinstance(p, tuple)):
  265. continue
  266. set_expand_structure(m, item[0], "TEST_VALUE")
  267. assert get_expand_structure(m, item[0]) == "TEST_VALUE"
  268. def test_flatten_others():
  269. def be_others(obj):
  270. return not isinstance(obj, (Tensor, Module))
  271. m = MyModule2()
  272. assert len(list(m._flatten(with_key=True, predicate=be_others))) == 0
  273. def test_flatten_with_parent():
  274. m = MyModule2()
  275. assert list(m.named_modules(with_parent=True)) == [
  276. ("", m, None),
  277. ("a.0", m.a[0], m),
  278. ("a.1.x", m.a[1]["x"], m),
  279. ("a.1.y.0", m.a[1]["y"][0], m),
  280. ("a.1.y.1", m.a[1]["y"][1], m),
  281. ("a.1.y.1.bn", m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  282. ("a.2.0", m.a[2][0], m),
  283. ("a.2.0.bn", m.a[2][0].bn, m.a[2][0]),
  284. ("bn", m.bn, m),
  285. ]
  286. assert list(m.modules(with_parent=True)) == [
  287. (m, None),
  288. (m.a[0], m),
  289. (m.a[1]["x"], m),
  290. (m.a[1]["y"][0], m),
  291. (m.a[1]["y"][1], m),
  292. (m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  293. (m.a[2][0], m),
  294. (m.a[2][0].bn, m.a[2][0]),
  295. (m.bn, m),
  296. ]
  297. class MyModule3(Module):
  298. class InnerModule(Module):
  299. def __init__(self):
  300. super().__init__()
  301. self.bn = BatchNorm2d(4)
  302. def forward(self, x):
  303. x = self.bn(x)
  304. def __init__(self):
  305. super().__init__()
  306. self.bn = BatchNorm2d(4)
  307. self.seq = Sequential(BatchNorm2d(4), self.InnerModule(),)
  308. def forward(self, x):
  309. return x
  310. def test_module_api_with_sequential():
  311. m = MyModule3()
  312. assert list(m.named_modules()) == [
  313. ("", m),
  314. ("bn", m.bn),
  315. ("seq", m.seq),
  316. ("seq.0", m.seq[0]),
  317. ("seq.1", m.seq[1]),
  318. ("seq.1.bn", m.seq[1].bn),
  319. ]
  320. def test_sequential_named_children():
  321. modules = OrderedDict()
  322. modules["name0"] = Linear(20, 10)
  323. modules["name1"] = Linear(10, 5)
  324. modules["name2"] = Linear(5, 1)
  325. m = Sequential(modules)
  326. l = list(m.named_children())
  327. assert l[0][0] == "name0"
  328. assert l[1][0] == "name1"
  329. assert l[2][0] == "name2"
  330. def test_state_dict():
  331. data_shape = (2, 28)
  332. data = tensor(np.random.random(data_shape))
  333. mlp = MLP()
  334. pred0 = mlp(data)
  335. with BytesIO() as fout:
  336. mge.save(mlp.state_dict(), fout)
  337. fout.seek(0)
  338. state_dict = mge.load(fout)
  339. state_dict["extra"] = None
  340. mlp1 = MLP()
  341. mlp1.load_state_dict(state_dict, strict=False)
  342. pred1 = mlp1(data)
  343. np.testing.assert_allclose(pred0.numpy(), pred1.numpy(), atol=5e-6)
  344. with pytest.raises(KeyError):
  345. mlp1.load_state_dict(state_dict)
  346. del state_dict["extra"]
  347. del state_dict["dense0.bias"]
  348. with pytest.raises(KeyError):
  349. mlp1.load_state_dict(state_dict)
  350. class AssertModule(Module):
  351. def __init__(self):
  352. super().__init__()
  353. self.error_tensor_key = {True: tensor([]), False: 0}
  354. def forward(self, x):
  355. return x
  356. def test_assert_message():
  357. with pytest.raises(
  358. AssertionError, match="keys for Tensor and Module must be str, error key: True"
  359. ):
  360. m = AssertModule()
  361. list(m._flatten())
  362. class Simple(Module):
  363. def __init__(self):
  364. super().__init__()
  365. self.conv0 = Conv2d(1, 1, kernel_size=3, bias=False)
  366. self.conv1 = Conv2d(1, 1, kernel_size=3, bias=False)
  367. self.conv1.weight = self.conv0.weight
  368. def forward(self, inputs):
  369. x = self.conv0(inputs)
  370. y = self.conv1(inputs)
  371. return x + y
  372. @pytest.mark.parametrize("test_traced_module", [True, False])
  373. def test_shared_param(test_traced_module):
  374. net = Simple()
  375. if test_traced_module:
  376. net = trace_module(net, tensor(np.random.random((1, 1, 8, 8))))
  377. assert net.conv0.weight is net.conv1.weight
  378. data = tensor(np.random.random((1, 1, 8, 8)).astype(np.float32))
  379. np.testing.assert_allclose(net.conv0(data).numpy(), net.conv1(data).numpy())
  380. with BytesIO() as f:
  381. mge.save(net, f)
  382. f.seek(0)
  383. net1 = mge.load(f)
  384. assert net1.conv0.weight is net1.conv1.weight
  385. np.testing.assert_allclose(net1.conv0(data).numpy(), net1.conv1(data).numpy())
  386. with BytesIO() as f:
  387. mge.save(net.conv0, f)
  388. f.seek(0)
  389. conv0 = mge.load(f)
  390. with BytesIO() as f:
  391. mge.save(net.conv1, f)
  392. f.seek(0)
  393. conv1 = mge.load(f)
  394. assert conv0.weight is not conv1.weight
  395. np.testing.assert_allclose(conv0(data).numpy(), conv1(data).numpy())
  396. class Simple2(Module):
  397. def __init__(self):
  398. super().__init__()
  399. self.conv1 = Conv1d(1, 1, kernel_size=3, bias=False)
  400. self.conv0 = Conv1d(1, 1, kernel_size=3, bias=False)
  401. self.conv1.weight = self.conv0.weight
  402. def forward(self, inputs):
  403. pass
  404. def test_shared_param_1d():
  405. net = Simple2()
  406. assert net.conv0.weight is net.conv1.weight
  407. data = tensor(np.random.random((1, 1, 8)).astype(np.float32))
  408. np.testing.assert_allclose(net.conv0(data).numpy(), net.conv1(data).numpy())
  409. with BytesIO() as f:
  410. mge.save(net, f)
  411. f.seek(0)
  412. net1 = mge.load(f)
  413. assert net1.conv0.weight is net1.conv1.weight
  414. np.testing.assert_allclose(net1.conv0(data).numpy(), net1.conv1(data).numpy())
  415. with BytesIO() as f:
  416. mge.save(net.conv0, f)
  417. f.seek(0)
  418. conv0 = mge.load(f)
  419. with BytesIO() as f:
  420. mge.save(net.conv1, f)
  421. f.seek(0)
  422. conv1 = mge.load(f)
  423. assert conv0.weight is not conv1.weight
  424. np.testing.assert_allclose(conv0(data).numpy(), conv1(data).numpy())
  425. @pytest.mark.parametrize("test_traced_module", [True, False])
  426. def test_pickle_module(test_traced_module):
  427. data_shape = (2, 28)
  428. data = tensor(np.random.random(data_shape))
  429. mlp = MLP()
  430. pred_gt = mlp(data)
  431. if test_traced_module:
  432. mlp = trace_module(mlp, data)
  433. # pickle before forward
  434. with BytesIO() as fout:
  435. mge.save(mlp, fout)
  436. fout.seek(0)
  437. mlp1 = mge.load(fout)
  438. if test_traced_module:
  439. assert type(mlp1) == TracedModule
  440. pred0 = mlp1(data)
  441. pred1 = mlp(data)
  442. # pickle after forward
  443. with BytesIO() as fout:
  444. mge.save(mlp, fout)
  445. fout.seek(0)
  446. mlp1 = mge.load(fout)
  447. if test_traced_module:
  448. assert type(mlp1) == TracedModule
  449. pred2 = mlp1(data)
  450. np.testing.assert_allclose(pred_gt.numpy(), pred1.numpy(), atol=5e-6)
  451. np.testing.assert_allclose(pred0.numpy(), pred1.numpy(), atol=5e-6)
  452. np.testing.assert_allclose(pred0.numpy(), pred2.numpy(), atol=5e-6)
  453. def test_repr_basic():
  454. # test whether __repr__ can output correct information
  455. class ConvModel(Module):
  456. def __init__(self):
  457. super().__init__()
  458. self.conv1 = Conv2d(3, 128, 3, padding=1, bias=False)
  459. self.conv2 = Conv2d(3, 128, 3, dilation=2, bias=False)
  460. self.bn1 = BatchNorm1d(128)
  461. self.bn2 = BatchNorm2d(128)
  462. self.pooling = MaxPool2d(kernel_size=2, padding=0)
  463. modules = OrderedDict()
  464. modules["depthwise"] = Conv2d(256, 256, 3, 1, 0, groups=256, bias=False,)
  465. modules["pointwise"] = Conv2d(
  466. 256, 256, kernel_size=1, stride=1, padding=0, bias=True,
  467. )
  468. self.submodule1 = Sequential(modules)
  469. self.list1 = [Dropout(drop_prob=0.1), [Softmax(axis=100)]]
  470. self.tuple1 = (
  471. Dropout(drop_prob=0.1),
  472. (Softmax(axis=100), Dropout(drop_prob=0.2)),
  473. )
  474. self.dict1 = {"Dropout": Dropout(drop_prob=0.1)}
  475. self.fc1 = Linear(512, 1024)
  476. def forward(self, inputs):
  477. pass
  478. ground_truth = (
  479. "ConvModel(\n"
  480. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), padding=(1, 1), bias=False)\n"
  481. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), dilation=(2, 2), bias=False)\n"
  482. " (bn1): BatchNorm1d(128, eps=1e-05, momentum=0.9, affine=True, track_running_stats=True)\n"
  483. " (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.9, affine=True, track_running_stats=True)\n"
  484. " (pooling): MaxPool2d(kernel_size=2, stride=2, padding=0)\n"
  485. " (submodule1): Sequential(\n"
  486. " (depthwise): Conv2d(256, 256, kernel_size=(3, 3), groups=256, bias=False)\n"
  487. " (pointwise): Conv2d(256, 256, kernel_size=(1, 1))\n"
  488. " )\n"
  489. " (list1.0): Dropout(drop_prob=0.1)\n"
  490. " (list1.1.0): Softmax(axis=100)\n"
  491. " (tuple1.0): Dropout(drop_prob=0.1)\n"
  492. " (tuple1.1.0): Softmax(axis=100)\n"
  493. " (tuple1.1.1): Dropout(drop_prob=0.2)\n"
  494. " (dict1.Dropout): Dropout(drop_prob=0.1)\n"
  495. " (fc1): Linear(in_features=512, out_features=1024, bias=True)\n"
  496. ")"
  497. )
  498. net = ConvModel()
  499. output = net.__repr__()
  500. assert output == ground_truth
  501. def test_repr_module_reassign():
  502. # test whether __repr__ can deal with module reassign
  503. class ConvModel1(Module):
  504. def __init__(self):
  505. super().__init__()
  506. self.conv1 = Conv2d(3, 128, 3, bias=False)
  507. self.conv2 = Conv2d(3, 128, 3, padding=1, bias=False)
  508. self.conv1 = Conv2d(3, 256, 3, dilation=2, bias=False)
  509. def forward(self, inputs):
  510. pass
  511. ground_truth = (
  512. "ConvModel1(\n"
  513. " (conv1): Conv2d(3, 256, kernel_size=(3, 3), dilation=(2, 2), bias=False)\n"
  514. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), padding=(1, 1), bias=False)\n"
  515. ")"
  516. )
  517. net = ConvModel1()
  518. output = net.__repr__()
  519. assert output == ground_truth
  520. def test_repr_module_rereference():
  521. # test whether __repr__ can deal with module re-reference
  522. class ConvModel2(Module):
  523. def __init__(self):
  524. super().__init__()
  525. self.conv1 = Conv2d(3, 128, 3, bias=False)
  526. self.conv2 = self.conv1
  527. self.conv3 = self.conv1
  528. def forward(self, inputs):
  529. pass
  530. ground_truth = (
  531. "ConvModel2(\n"
  532. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  533. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  534. " (conv3): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  535. ")"
  536. )
  537. net = ConvModel2()
  538. output = net.__repr__()
  539. assert output == ground_truth
  540. def test_repr_module_delete():
  541. # test whether __repr__ can deal with module delete
  542. class ConvModel3(Module):
  543. def __init__(self):
  544. super().__init__()
  545. self.conv1 = Conv2d(3, 128, 3, bias=False)
  546. self.softmax = Softmax(100)
  547. def forward(self, inputs):
  548. pass
  549. ground_truth = (
  550. "ConvModel3(\n"
  551. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  552. ")"
  553. )
  554. net = ConvModel3()
  555. del net.softmax
  556. output = net.__repr__()
  557. assert output == ground_truth
  558. def test_repr_module_reset_attr():
  559. class ResetAttrModule(Module):
  560. def __init__(self, flag):
  561. super().__init__()
  562. if flag:
  563. self.a = None
  564. self.a = Linear(3, 5)
  565. else:
  566. self.a = Linear(3, 5)
  567. self.a = None
  568. def forward(self, x):
  569. if self.a:
  570. x = self.a(x)
  571. return x
  572. ground_truth = [
  573. (
  574. "ResetAttrModule(\n"
  575. " (a): Linear(in_features=3, out_features=5, bias=True)\n"
  576. ")"
  577. ),
  578. ("ResetAttrModule()"),
  579. ]
  580. m0 = ResetAttrModule(True)
  581. m1 = ResetAttrModule(False)
  582. output = [m0.__repr__(), m1.__repr__()]
  583. assert output == ground_truth

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