-
Notifications
You must be signed in to change notification settings - Fork 934
/
module.py
133 lines (102 loc) · 3.75 KB
/
module.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
## Task 0.4
## Modules
class Module:
"""
Attributes:
_modules (dict of name x :class:`Module`): Storage of the child modules
_parameters (dict of name x :class:`Parameter`): Storage of the module's parameters
mode (string): Mode of operation, can be {"train", "eval"}.
"""
def __init__(self):
self._modules = {}
self._parameters = {}
self.mode = "train"
def modules(self):
"Return the child modules of this module."
return self.__dict__["_modules"].values()
def train(self):
"Set the mode of this module and all descendent modules to `train`."
# TODO: Implement for Task 0.4.
raise NotImplementedError('Need to implement for Task 0.4')
def eval(self):
"Set the mode of this module and all descendent modules to `eval`."
# TODO: Implement for Task 0.4.
raise NotImplementedError('Need to implement for Task 0.4')
def named_parameters(self):
"""
Collect all the ancestor parameters of this module.
Returns:
dict: Each name (key) and :class:`Parameter` (value) under this module.
"""
# TODO: Implement for Task 0.4.
raise NotImplementedError('Need to implement for Task 0.4')
def parameters(self):
return self.named_parameters().values()
def add_parameter(self, k, v):
"""
Manually add a parameter. Useful helper for scalar parameters.
Args:
k (str): Local name of the parameter.
v (value): Value for the parameter.
Returns:
Parameter: Newly created parameter.
"""
val = Parameter(v)
self.__dict__["_parameters"][k] = val
return val
def __setattr__(self, key, val):
if isinstance(val, Parameter):
self.__dict__["_parameters"][key] = val
elif isinstance(val, Module):
self.__dict__["_modules"][key] = val
else:
super().__setattr__(key, val)
def __getattr__(self, key):
if key in self.__dict__["_parameters"]:
return self.__dict__["_parameters"][key]
if key in self.__dict__["_modules"]:
return self.__dict__["_modules"][key]
return self.__getattribute__(key)
def __call__(self, *args, **kwargs):
return self.forward(*args, **kwargs)
def forward(self):
assert False, "Not Implemented"
def __repr__(self):
def _addindent(s_, numSpaces):
s = s_.split("\n")
if len(s) == 1:
return s_
first = s.pop(0)
s = [(numSpaces * " ") + line for line in s]
s = "\n".join(s)
s = first + "\n" + s
return s
child_lines = []
for key, module in self._modules.items():
mod_str = repr(module)
mod_str = _addindent(mod_str, 2)
child_lines.append("(" + key + "): " + mod_str)
lines = child_lines
main_str = self.__class__.__name__ + "("
if lines:
# simple one-liner info, which most builtin Modules will use
main_str += "\n " + "\n ".join(lines) + "\n"
main_str += ")"
return main_str
class Parameter:
"""
A Parameter is a special container stored in a :class:`Module`.
It is designed to hold a :class:`Variable`, but we all it to hold
any value for testing.
"""
def __init__(self, x=None):
self.value = x
if hasattr(x, "requires_grad_"):
self.value.requires_grad_(True)
def update(self, x):
"Update the parameter value."
self.value = x
if hasattr(x, "requires_grad_"):
self.value.requires_grad_(True)
def __repr__(self):
return repr(self.value)