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

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

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