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