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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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 os
  10. import tempfile
  11. from collections import OrderedDict
  12. from io import BytesIO
  13. import numpy as np
  14. import pytest
  15. import megengine as mge
  16. import megengine.functional as F
  17. from megengine import Parameter, Tensor, tensor
  18. from megengine.module import (
  19. BatchNorm1d,
  20. BatchNorm2d,
  21. Conv1d,
  22. Conv2d,
  23. Dropout,
  24. Linear,
  25. MaxPool2d,
  26. Module,
  27. Sequential,
  28. Softmax,
  29. )
  30. from megengine.quantization.quantize import quantize, quantize_qat
  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. def has_gpu(num=1):
  42. try:
  43. mgb.comp_node("gpu{}".format(num - 1))
  44. except mgb.MegBrainError:
  45. return False
  46. return True
  47. def randomNp(*args):
  48. for arg in args:
  49. assert isinstance(arg, int)
  50. return np.random.random(args)
  51. def randomTorch(*args):
  52. import torch # pylint: disable=import-outside-toplevel
  53. for arg in args:
  54. assert isinstance(arg, int)
  55. return torch.tensor(randomNp(*args), dtype=torch.float32)
  56. def graph_mode(*modes):
  57. if not set(modes).issubset({"eager", "static"}):
  58. raise ValueError("graph mode must be in (eager, static)")
  59. def decorator(func):
  60. def wrapper(*args, **kwargs):
  61. if "eager" in set(modes):
  62. func(*args, **kwargs)
  63. if "static" in set(modes):
  64. with Graph() as cg:
  65. cg.set_option("eager_evaluation", False)
  66. func(*args, **kwargs)
  67. return wrapper
  68. return decorator
  69. def _default_compare_fn(x, y):
  70. np.testing.assert_allclose(x.numpy(), y, rtol=1e-6)
  71. def opr_test(
  72. cases,
  73. func,
  74. mode=("eager", "static", "dynamic_shape"),
  75. compare_fn=_default_compare_fn,
  76. ref_fn=None,
  77. **kwargs
  78. ):
  79. """
  80. mode: the list of test mode which are eager, static and dynamic_shape
  81. will test all the cases if None.
  82. func: the function to run opr.
  83. compare_fn: the function to compare the result and expected, use np.testing.assert_allclose if None.
  84. ref_fn: the function to generate expected data, should assign output if None.
  85. cases: the list which have dict element, the list length should be 2 for dynamic shape test.
  86. and the dict should have input,
  87. and should have output if ref_fn is None.
  88. should use list for multiple inputs and outputs for each case.
  89. kwargs: The additional kwargs for opr func.
  90. simple examples:
  91. dtype = np.float32
  92. cases = [{"input": [10, 20]}, {"input": [20, 30]}]
  93. opr_test(cases,
  94. F.eye,
  95. ref_fn=lambda n, m: np.eye(n, m).astype(dtype),
  96. dtype=dtype)
  97. """
  98. def check_results(results, expected):
  99. if not isinstance(results, Tuple):
  100. results = (results,)
  101. for r, e in zip(results, expected):
  102. compare_fn(r, e)
  103. def get_trace_fn(func, enabled, symbolic):
  104. jit.trace.enabled = enabled
  105. return jit.trace(func, symbolic=symbolic)
  106. def get_param(cases, idx):
  107. case = cases[idx]
  108. inp = case.get("input", None)
  109. outp = case.get("output", None)
  110. if inp is None:
  111. raise ValueError("the test case should have input")
  112. if not isinstance(inp, List):
  113. inp = (inp,)
  114. else:
  115. inp = tuple(inp)
  116. if ref_fn is not None and callable(ref_fn):
  117. outp = ref_fn(*inp)
  118. if outp is None:
  119. raise ValueError("the test case should have output or reference function")
  120. if not isinstance(outp, List):
  121. outp = (outp,)
  122. else:
  123. outp = tuple(outp)
  124. return inp, outp
  125. if not set(mode).issubset({"eager", "static", "dynamic_shape"}):
  126. raise ValueError("opr test mode must be in (eager, static, dynamic_shape)")
  127. if len(cases) == 0:
  128. raise ValueError("should give one case at least")
  129. if "dynamic_shape" in set(mode):
  130. if len(cases) != 2:
  131. raise ValueError("should give 2 cases for dynamic shape test")
  132. if not callable(func):
  133. raise ValueError("the input func should be callable")
  134. inp, outp = get_param(cases, 0)
  135. def run(*args, **kwargs):
  136. return func(*args, **kwargs)
  137. if "eager" in set(mode):
  138. f = get_trace_fn(run, False, False)
  139. results = f(*inp, **kwargs)
  140. check_results(results, outp)
  141. if "static" in set(mode) or "dynamic_shape" in set(mode):
  142. f = get_trace_fn(run, True, True)
  143. results = f(*inp, **kwargs)
  144. check_results(results, outp)
  145. if "dynamic_shape" in set(mode):
  146. inp, outp = get_param(cases, 1)
  147. results = f(*inp, **kwargs)
  148. check_results(results, outp)
  149. class MyModule(Module):
  150. class InnerModule(Module):
  151. def __init__(self):
  152. super().__init__()
  153. self.bn = BatchNorm2d(4)
  154. def forward(self, x):
  155. return self.bn(x)
  156. def __init__(self):
  157. super().__init__()
  158. self.i = self.InnerModule()
  159. self.bn = BatchNorm2d(4)
  160. self.param = Parameter(np.ones(1, dtype=np.float32))
  161. self.buff = Tensor(np.ones(1, dtype=np.float32))
  162. def forward(self, x):
  163. x = self.i(x)
  164. x = self.bn(x)
  165. return x
  166. def test_module_api():
  167. m = MyModule()
  168. assert list(m.children()) == [m.bn, m.i]
  169. assert list(m.named_children()) == [("bn", m.bn), ("i", m.i)]
  170. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  171. assert list(m.named_modules()) == [
  172. ("", m),
  173. ("bn", m.bn),
  174. ("i", m.i),
  175. ("i.bn", m.i.bn),
  176. ]
  177. assert list(m.named_modules(prefix="x")) == [
  178. ("x", m),
  179. ("x.bn", m.bn),
  180. ("x.i", m.i),
  181. ("x.i.bn", m.i.bn),
  182. ]
  183. assert list(m.buffers()) == [
  184. m.bn.running_mean,
  185. m.bn.running_var,
  186. m.buff,
  187. m.i.bn.running_mean,
  188. m.i.bn.running_var,
  189. ]
  190. assert list(m.buffers(recursive=False)) == [m.buff]
  191. assert list(m.named_buffers()) == [
  192. ("bn.running_mean", m.bn.running_mean),
  193. ("bn.running_var", m.bn.running_var),
  194. ("buff", m.buff),
  195. ("i.bn.running_mean", m.i.bn.running_mean),
  196. ("i.bn.running_var", m.i.bn.running_var),
  197. ]
  198. assert list(m.parameters()) == [
  199. m.bn.bias,
  200. m.bn.weight,
  201. m.i.bn.bias,
  202. m.i.bn.weight,
  203. m.param,
  204. ]
  205. assert list(m.named_parameters()) == [
  206. ("bn.bias", m.bn.bias),
  207. ("bn.weight", m.bn.weight),
  208. ("i.bn.bias", m.i.bn.bias),
  209. ("i.bn.weight", m.i.bn.weight),
  210. ("param", m.param),
  211. ]
  212. m.eval()
  213. assert (
  214. m.training == False
  215. and m.bn.training == False
  216. and m.i.training == False
  217. and m.i.bn.training == False
  218. )
  219. m.bn.train()
  220. assert m.training == False and m.bn.training == True and m.i.bn.training == False
  221. m.eval()
  222. m.i.train()
  223. assert (
  224. m.training == False
  225. and m.bn.training == False
  226. and m.i.training == True
  227. and m.i.bn.training == True
  228. )
  229. m.eval()
  230. m.train()
  231. assert m.training == True and m.bn.training == True and m.i.bn.training == True
  232. def fn(m):
  233. m.training = False
  234. m.apply(fn)
  235. assert m.bn.training == False and m.i.bn.training == False
  236. def test_module_api_reuse_submodule():
  237. m = MyModule()
  238. m.h = m.i # pylint: disable=attribute-defined-outside-init
  239. assert list(m.modules()) == [m, m.bn, m.i, m.i.bn]
  240. assert list(m.named_modules()) == [
  241. ("", m),
  242. ("bn", m.bn),
  243. ("h", m.i),
  244. ("h.bn", m.i.bn),
  245. ]
  246. def test_module_api_iterable_stability():
  247. m = MyModule()
  248. l = list(m.modules())
  249. for _ in range(100):
  250. assert list(m.modules()) == l
  251. def test_module_api_hooks():
  252. net = MyModule()
  253. pre_hook_num = 0
  254. post_hook_num = 0
  255. hooks = []
  256. def pre_hook(module, inputs):
  257. nonlocal pre_hook_num
  258. pre_hook_num += 1
  259. modified_inputs = tuple(inp + 1 for inp in inputs)
  260. return modified_inputs
  261. def post_hook(module, inputs, outputs):
  262. nonlocal post_hook_num
  263. post_hook_num += 1
  264. outputs += 1
  265. return outputs
  266. net.apply(lambda module: hooks.append(module.register_forward_pre_hook(pre_hook)))
  267. net.apply(lambda module: hooks.append(module.register_forward_hook(post_hook)))
  268. shape = (1, 4, 1, 1)
  269. x = tensor(np.zeros(shape, dtype=np.float32))
  270. y = net(x)
  271. assert pre_hook_num == 4
  272. assert post_hook_num == 4
  273. mean1 = Parameter(np.zeros(shape), dtype=np.float32)
  274. bn1 = F.batch_norm(
  275. x + 3, mean1, Parameter(np.ones(shape), dtype=np.float32), training=True
  276. )
  277. np.testing.assert_allclose(
  278. net.i.bn.running_mean.numpy(), mean1.numpy(),
  279. )
  280. mean2 = Parameter(np.zeros(shape), dtype=np.float32)
  281. bn2 = F.batch_norm(
  282. bn1 + 3, mean2, Parameter(np.ones(shape), dtype=np.float32), training=True
  283. )
  284. np.testing.assert_allclose(
  285. net.bn.running_mean.numpy(), mean2.numpy(),
  286. )
  287. np.testing.assert_allclose((bn2 + 2).numpy(), y.numpy())
  288. assert len(hooks) == 8
  289. for handler in hooks:
  290. handler.remove()
  291. y = net(x)
  292. assert pre_hook_num == 4
  293. assert post_hook_num == 4
  294. class MyModule2(Module):
  295. class InnerModule(Module):
  296. def __init__(self):
  297. super().__init__()
  298. self.bn = BatchNorm2d(4)
  299. self.test_bool_key = {True: 1, False: 0}
  300. def forward(self, x):
  301. x = self.bn(x)
  302. def __init__(self):
  303. super().__init__()
  304. self.bn = BatchNorm2d(4)
  305. self.a = [
  306. BatchNorm2d(4),
  307. {"x": BatchNorm2d(4), "y": [BatchNorm2d(4), self.InnerModule()], "z": 0},
  308. (self.InnerModule(),),
  309. ]
  310. def forward(self, x):
  311. return x
  312. def test_expand_structure():
  313. m = MyModule2()
  314. assert list(m.named_modules()) == [
  315. ("", m),
  316. ("a.0", m.a[0]),
  317. ("a.1.x", m.a[1]["x"]),
  318. ("a.1.y.0", m.a[1]["y"][0]),
  319. ("a.1.y.1", m.a[1]["y"][1]),
  320. ("a.1.y.1.bn", m.a[1]["y"][1].bn),
  321. ("a.2.0", m.a[2][0]),
  322. ("a.2.0.bn", m.a[2][0].bn),
  323. ("bn", m.bn),
  324. ]
  325. def test_flatten_others():
  326. def be_others(obj):
  327. return not isinstance(obj, (Tensor, Module))
  328. m = MyModule2()
  329. assert len(list(m._flatten(with_key=True, predicate=be_others))) == 0
  330. def test_flatten_with_parent():
  331. m = MyModule2()
  332. assert list(m.named_modules(with_parent=True)) == [
  333. ("", m, None),
  334. ("a.0", m.a[0], m),
  335. ("a.1.x", m.a[1]["x"], m),
  336. ("a.1.y.0", m.a[1]["y"][0], m),
  337. ("a.1.y.1", m.a[1]["y"][1], m),
  338. ("a.1.y.1.bn", m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  339. ("a.2.0", m.a[2][0], m),
  340. ("a.2.0.bn", m.a[2][0].bn, m.a[2][0]),
  341. ("bn", m.bn, m),
  342. ]
  343. assert list(m.modules(with_parent=True)) == [
  344. (m, None),
  345. (m.a[0], m),
  346. (m.a[1]["x"], m),
  347. (m.a[1]["y"][0], m),
  348. (m.a[1]["y"][1], m),
  349. (m.a[1]["y"][1].bn, m.a[1]["y"][1]),
  350. (m.a[2][0], m),
  351. (m.a[2][0].bn, m.a[2][0]),
  352. (m.bn, m),
  353. ]
  354. class MyModule3(Module):
  355. class InnerModule(Module):
  356. def __init__(self):
  357. super().__init__()
  358. self.bn = BatchNorm2d(4)
  359. def forward(self, x):
  360. x = self.bn(x)
  361. def __init__(self):
  362. super().__init__()
  363. self.bn = BatchNorm2d(4)
  364. self.seq = Sequential(BatchNorm2d(4), self.InnerModule(),)
  365. def forward(self, x):
  366. return x
  367. def test_module_api_with_sequential():
  368. m = MyModule3()
  369. assert list(m.named_modules()) == [
  370. ("", m),
  371. ("bn", m.bn),
  372. ("seq", m.seq),
  373. ("seq.0", m.seq[0]),
  374. ("seq.1", m.seq[1]),
  375. ("seq.1.bn", m.seq[1].bn),
  376. ]
  377. def test_sequential_named_children():
  378. modules = OrderedDict()
  379. modules["name0"] = Linear(20, 10)
  380. modules["name1"] = Linear(10, 5)
  381. modules["name2"] = Linear(5, 1)
  382. m = Sequential(modules)
  383. l = list(m.named_children())
  384. assert l[0][0] == "name0"
  385. assert l[1][0] == "name1"
  386. assert l[2][0] == "name2"
  387. def test_state_dict():
  388. data_shape = (2, 28)
  389. data = tensor(np.random.random(data_shape))
  390. mlp = MLP()
  391. pred0 = mlp(data)
  392. with BytesIO() as fout:
  393. mge.save(mlp.state_dict(), fout)
  394. fout.seek(0)
  395. state_dict = mge.load(fout)
  396. state_dict["extra"] = None
  397. mlp1 = MLP()
  398. mlp1.load_state_dict(state_dict, strict=False)
  399. pred1 = mlp1(data)
  400. np.testing.assert_allclose(pred0.numpy(), pred1.numpy(), atol=5e-6)
  401. with pytest.raises(KeyError):
  402. mlp1.load_state_dict(state_dict)
  403. del state_dict["extra"]
  404. del state_dict["dense0.bias"]
  405. with pytest.raises(KeyError):
  406. mlp1.load_state_dict(state_dict)
  407. class AssertModule(Module):
  408. def __init__(self):
  409. super().__init__()
  410. self.error_tensor_key = {True: tensor([]), False: 0}
  411. def forward(self, x):
  412. return x
  413. def test_assert_message():
  414. m = AssertModule()
  415. with pytest.raises(
  416. AssertionError, match="keys for Tensor and Module must be str, error key: True"
  417. ):
  418. list(m._flatten())
  419. class Simple(Module):
  420. def __init__(self):
  421. super().__init__()
  422. self.conv0 = Conv2d(1, 1, kernel_size=3, bias=False)
  423. self.conv1 = Conv2d(1, 1, kernel_size=3, bias=False)
  424. self.conv1.weight = self.conv0.weight
  425. def forward(self, inputs):
  426. pass
  427. def test_shared_param():
  428. net = Simple()
  429. assert net.conv0.weight is net.conv1.weight
  430. data = tensor(np.random.random((1, 1, 8, 8)).astype(np.float32))
  431. np.testing.assert_allclose(net.conv0(data).numpy(), net.conv1(data).numpy())
  432. with BytesIO() as f:
  433. mge.save(net, f)
  434. f.seek(0)
  435. net1 = mge.load(f)
  436. assert net1.conv0.weight is net1.conv1.weight
  437. np.testing.assert_allclose(net1.conv0(data).numpy(), net1.conv1(data).numpy())
  438. with BytesIO() as f:
  439. mge.save(net.conv0, f)
  440. f.seek(0)
  441. conv0 = mge.load(f)
  442. with BytesIO() as f:
  443. mge.save(net.conv1, f)
  444. f.seek(0)
  445. conv1 = mge.load(f)
  446. assert conv0.weight is not conv1.weight
  447. np.testing.assert_allclose(conv0(data).numpy(), conv1(data).numpy())
  448. class Simple2(Module):
  449. def __init__(self):
  450. super().__init__()
  451. self.conv1 = Conv1d(1, 1, kernel_size=3, bias=False)
  452. self.conv0 = Conv1d(1, 1, kernel_size=3, bias=False)
  453. self.conv1.weight = self.conv0.weight
  454. def forward(self, inputs):
  455. pass
  456. def test_shared_param_1d():
  457. net = Simple2()
  458. assert net.conv0.weight is net.conv1.weight
  459. data = tensor(np.random.random((1, 1, 8)).astype(np.float32))
  460. np.testing.assert_allclose(net.conv0(data).numpy(), net.conv1(data).numpy())
  461. with BytesIO() as f:
  462. mge.save(net, f)
  463. f.seek(0)
  464. net1 = mge.load(f)
  465. assert net1.conv0.weight is net1.conv1.weight
  466. np.testing.assert_allclose(net1.conv0(data).numpy(), net1.conv1(data).numpy())
  467. with BytesIO() as f:
  468. mge.save(net.conv0, f)
  469. f.seek(0)
  470. conv0 = mge.load(f)
  471. with BytesIO() as f:
  472. mge.save(net.conv1, f)
  473. f.seek(0)
  474. conv1 = mge.load(f)
  475. assert conv0.weight is not conv1.weight
  476. np.testing.assert_allclose(conv0(data).numpy(), conv1(data).numpy())
  477. def test_pickle_module():
  478. data_shape = (2, 28)
  479. data = tensor(np.random.random(data_shape))
  480. mlp = MLP()
  481. # pickle before forward
  482. with BytesIO() as fout:
  483. mge.save(mlp, fout)
  484. fout.seek(0)
  485. mlp1 = mge.load(fout)
  486. pred0 = mlp1(data)
  487. pred1 = mlp(data)
  488. # pickle after forward
  489. with BytesIO() as fout:
  490. mge.save(mlp, fout)
  491. fout.seek(0)
  492. mlp1 = mge.load(fout)
  493. pred2 = mlp1(data)
  494. np.testing.assert_allclose(pred0.numpy(), pred1.numpy(), atol=5e-6)
  495. np.testing.assert_allclose(pred0.numpy(), pred2.numpy(), atol=5e-6)
  496. @pytest.mark.skip(reason="under development")
  497. def test_dump_model():
  498. data_shape = (2, 28)
  499. data = Tensor(np.random.random(data_shape))
  500. mlp = MLP()
  501. pred = mlp(data)
  502. f = tempfile.NamedTemporaryFile(delete=False)
  503. f_name = f.name
  504. try:
  505. mge.dump(pred, f_name)
  506. finally:
  507. f.close()
  508. os.unlink(f_name)
  509. def test_load_quantized():
  510. from megengine.core.tensor import dtype
  511. data_shape = (2, 28)
  512. data = tensor(np.random.random(data_shape), dtype="float32")
  513. data = data.astype(dtype.qint8(0.1))
  514. mlp = MLP()
  515. quantize_qat(mlp)
  516. quantize(mlp)
  517. mlp.dense0.weight = Parameter(mlp.dense0.weight.astype(dtype.qint8(0.001)).numpy())
  518. mlp.dense1.weight = Parameter(mlp.dense1.weight.astype(dtype.qint8(0.0002)).numpy())
  519. mlp.eval()
  520. pred0 = mlp(data)
  521. with BytesIO() as fout:
  522. mge.save(mlp.state_dict(), fout)
  523. fout.seek(0)
  524. checkpoint = mge.load(fout)
  525. # change mlp weight.
  526. mlp.dense0.weight = Parameter(
  527. mlp.dense0.weight.astype(dtype.qint8(0.00001)).numpy()
  528. )
  529. mlp.dense1.weight = Parameter(
  530. mlp.dense1.weight.astype(dtype.qint8(0.2)).numpy()
  531. )
  532. mlp.load_state_dict(checkpoint)
  533. pred1 = mlp(data)
  534. np.testing.assert_allclose(
  535. pred0.astype("float32").numpy(), pred1.astype("float32").numpy(), atol=5e-6
  536. )
  537. def test_repr_basic():
  538. # test whether __repr__ can output correct information
  539. class ConvModel(Module):
  540. def __init__(self):
  541. super().__init__()
  542. self.conv1 = Conv2d(3, 128, 3, stride=2, bias=False)
  543. self.conv2 = Conv2d(3, 128, 3, padding=1, bias=False)
  544. self.conv3 = Conv2d(3, 128, 3, dilation=2, bias=False)
  545. self.bn1 = BatchNorm2d(128)
  546. self.bn2 = BatchNorm1d(128)
  547. self.dropout = Dropout(drop_prob=0.1)
  548. self.softmax = Softmax(axis=100)
  549. self.pooling = MaxPool2d(kernel_size=2, padding=0)
  550. self.submodule1 = Sequential(Dropout(drop_prob=0.1), Softmax(axis=100),)
  551. self.fc1 = Linear(512, 1024)
  552. def forward(self, inputs):
  553. pass
  554. ground_truth = (
  555. "ConvModel(\n"
  556. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), stride=(2, 2), bias=False)\n"
  557. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), padding=(1, 1), bias=False)\n"
  558. " (conv3): Conv2d(3, 128, kernel_size=(3, 3), dilation=(2, 2), bias=False)\n"
  559. " (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.9, affine=True, track_running_stats=True)\n"
  560. " (bn2): BatchNorm1d(128, eps=1e-05, momentum=0.9, affine=True, track_running_stats=True)\n"
  561. " (dropout): Dropout(drop_prob=0.1)\n (softmax): Softmax(axis=100)\n"
  562. " (pooling): MaxPool2d(kernel_size=2, stride=2, padding=0)\n"
  563. " (submodule1): Sequential(\n"
  564. " (0): Dropout(drop_prob=0.1)\n"
  565. " (1): Softmax(axis=100)\n )\n"
  566. " (fc1): Linear(in_features=512, out_features=1024, bias=True)\n"
  567. ")"
  568. )
  569. net = ConvModel()
  570. output = net.__repr__()
  571. assert output == ground_truth
  572. def test_repr_module_reassign():
  573. # test whether __repr__ can deal with module reassign
  574. class ConvModel1(Module):
  575. def __init__(self):
  576. super().__init__()
  577. self.conv1 = Conv2d(3, 128, 3, bias=False)
  578. self.conv2 = Conv2d(3, 128, 3, padding=1, bias=False)
  579. self.conv1 = Conv2d(3, 256, 3, dilation=2, bias=False)
  580. def forward(self, inputs):
  581. pass
  582. ground_truth = (
  583. "ConvModel1(\n"
  584. " (conv1): Conv2d(3, 256, kernel_size=(3, 3), dilation=(2, 2), bias=False)\n"
  585. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), padding=(1, 1), bias=False)\n"
  586. ")"
  587. )
  588. net = ConvModel1()
  589. output = net.__repr__()
  590. assert output == ground_truth
  591. def test_repr_module_rereference():
  592. # test whether __repr__ can deal with module re-reference
  593. class ConvModel2(Module):
  594. def __init__(self):
  595. super().__init__()
  596. self.conv1 = Conv2d(3, 128, 3, bias=False)
  597. self.conv2 = self.conv1
  598. self.conv3 = self.conv1
  599. def forward(self, inputs):
  600. pass
  601. ground_truth = (
  602. "ConvModel2(\n"
  603. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  604. " (conv2): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  605. " (conv3): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  606. ")"
  607. )
  608. net = ConvModel2()
  609. output = net.__repr__()
  610. assert output == ground_truth
  611. def test_repr_module_delete():
  612. # test whether __repr__ can deal with module delete
  613. class ConvModel3(Module):
  614. def __init__(self):
  615. super().__init__()
  616. self.conv1 = Conv2d(3, 128, 3, bias=False)
  617. self.softmax = Softmax(100)
  618. def forward(self, inputs):
  619. pass
  620. ground_truth = (
  621. "ConvModel3(\n"
  622. " (conv1): Conv2d(3, 128, kernel_size=(3, 3), bias=False)\n"
  623. ")"
  624. )
  625. net = ConvModel3()
  626. del net.softmax
  627. output = net.__repr__()
  628. assert output == ground_truth

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