MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / Sequential

Class Sequential

imperative/python/megengine/module/sequential.py:7–88  ·  view source on GitHub ↗

r"""A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in. Examples: .. testcode:: import numpy as np import megengine as mge impo

Source from the content-addressed store, hash-verified

5
6
7class Sequential(Module):
8 r"""A sequential container.
9 Modules will be added to it in the order they are passed in the constructor.
10 Alternatively, an ordered dict of modules can also be passed in.
11
12 Examples:
13
14 .. testcode::
15
16 import numpy as np
17 import megengine as mge
18 import megengine.module as M
19 import megengine.functional as F
20 from collections import OrderedDict
21
22 batch_size = 64
23 data = mge.tensor(np.zeros((batch_size, 28 * 28)), dtype=np.float32)
24 label = mge.tensor(np.zeros(batch_size,), dtype=np.int32)
25
26 net0 = M.Sequential(
27 M.Linear(28 * 28, 320),
28 M.Linear(320, 10)
29 )
30 pred0 = net0(data)
31
32 modules = OrderedDict()
33 modules["fc0"] = M.Linear(28 * 28, 320)
34 modules["fc1"] = M.Linear(320, 10)
35 net1 = M.Sequential(modules)
36 pred1 = net1(data)
37 """
38
39 def __init__(self, *args, **kwargs):
40 super().__init__(**kwargs)
41 self.layer_keys = []
42 if len(args) == 1 and isinstance(args[0], OrderedDict):
43 for key, module in args[0].items():
44 # self.add_module(key, module)
45 setattr(self, key, module)
46 self.layer_keys.append(key)
47 else:
48 for idx, module in enumerate(args):
49 # self.add_module(str(idx), module)
50 setattr(self, str(idx), module)
51 self.layer_keys.append(str(idx))
52
53 def __getitem__(self, idx):
54 if isinstance(idx, slice):
55 return self.__class__(
56 OrderedDict(zip(self.layer_keys[idx], self.layer_values[idx]))
57 )
58 else:
59 return getattr(self, self.layer_keys[idx])
60
61 def __setitem__(self, idx, module):
62 key = self.layer_keys[idx]
63 return setattr(self, key, module)
64

Callers 4

run_syncbnFunction · 0.90
__init__Method · 0.90
__init__Method · 0.90

Calls

no outgoing calls

Tested by 4

run_syncbnFunction · 0.72
__init__Method · 0.72
__init__Method · 0.72