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

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

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