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

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

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