|
| 1 | +import chainer |
| 2 | + |
| 3 | + |
| 4 | +class PickableSequentialChain(chainer.Chain): |
| 5 | + |
| 6 | + """A sequential chain that can pick intermediate layers. |
| 7 | +
|
| 8 | + Callable objects, such as :class:`chainer.Link` and |
| 9 | + :class:`chainer.Function`, can be registered to this chain with |
| 10 | + :meth:`init_scope`. |
| 11 | + This chain keeps the order of registrations and :meth:`__call__` |
| 12 | + executes callables in that order. |
| 13 | + A :class:`chainer.Link` object in the sequence will be added as |
| 14 | + a child link of this link. |
| 15 | +
|
| 16 | + :meth:`__call__` returns single or multiple layers that are picked up |
| 17 | + through a stream of computation. |
| 18 | + These layers can be specified by :obj:`pick`, which contains |
| 19 | + the names of the layers that are collected. |
| 20 | + When :obj:`pick` is a string, single layer is returned. |
| 21 | + When :obj:`pick` is an iterable of strings, a tuple of layers |
| 22 | + is returned. The order of the layers is the same as the order of |
| 23 | + the strings in :obj:`pick`. |
| 24 | + When :obj:`pick` is :obj:`None`, the last layer is returned. |
| 25 | +
|
| 26 | + Examples: |
| 27 | +
|
| 28 | + >>> import chainer.functions as F |
| 29 | + >>> import chainer.links as L |
| 30 | + >>> model = PickableSequentialChain() |
| 31 | + >>> with model.init_scope(): |
| 32 | + >>> model.l1 = L.Linear(None, 1000) |
| 33 | + >>> model.l1_relu = F.relu |
| 34 | + >>> model.l2 = L.Linear(None, 1000) |
| 35 | + >>> model.l2_relu = F.relu |
| 36 | + >>> model.l3 = L.Linear(None, 10) |
| 37 | + >>> # This is layer l3 |
| 38 | + >>> layer3 = model(x) |
| 39 | + >>> # The layers to be collected can be changed. |
| 40 | + >>> model.pick = ('l2_relu', 'l1_relu') |
| 41 | + >>> # These are layers l2_relu and l1_relu. |
| 42 | + >>> layer2, layer1 = model(x) |
| 43 | +
|
| 44 | + Parameters: |
| 45 | + pick (string or iterable of strings): |
| 46 | + Names of layers that are collected during |
| 47 | + the forward pass. |
| 48 | + layer_names (iterable of strings): |
| 49 | + Names of layers that can be collected from |
| 50 | + this chain. The names are ordered in the order |
| 51 | + of computation. |
| 52 | +
|
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self): |
| 56 | + super(PickableSequentialChain, self).__init__() |
| 57 | + self.layer_names = list() |
| 58 | + # Two attributes are initialized by the setter of pick. |
| 59 | + # self._pick -> None |
| 60 | + # self._return_tuple -> False |
| 61 | + self.pick = None |
| 62 | + |
| 63 | + def __setattr__(self, name, value): |
| 64 | + super(PickableSequentialChain, self).__setattr__(name, value) |
| 65 | + if self.within_init_scope and callable(value): |
| 66 | + self.layer_names.append(name) |
| 67 | + |
| 68 | + def __delattr__(self, name): |
| 69 | + if self._pick and name in self._pick: |
| 70 | + raise AttributeError( |
| 71 | + 'layer {:s} is registered to pick.'.format(name)) |
| 72 | + super(PickableSequentialChain, self).__delattr__(name) |
| 73 | + try: |
| 74 | + self.layer_names.remove(name) |
| 75 | + except ValueError: |
| 76 | + pass |
| 77 | + |
| 78 | + @property |
| 79 | + def pick(self): |
| 80 | + if self._pick is None: |
| 81 | + return None |
| 82 | + |
| 83 | + if self._return_tuple: |
| 84 | + return self._pick |
| 85 | + else: |
| 86 | + return self._pick[0] |
| 87 | + |
| 88 | + @pick.setter |
| 89 | + def pick(self, pick): |
| 90 | + if pick is None: |
| 91 | + self._return_tuple = False |
| 92 | + self._pick = None |
| 93 | + return |
| 94 | + |
| 95 | + if (not isinstance(pick, str) and |
| 96 | + all(isinstance(name, str) for name in pick)): |
| 97 | + return_tuple = True |
| 98 | + else: |
| 99 | + return_tuple = False |
| 100 | + pick = (pick,) |
| 101 | + if any(name not in self.layer_names for name in pick): |
| 102 | + raise ValueError('Invalid layer name') |
| 103 | + |
| 104 | + self._return_tuple = return_tuple |
| 105 | + self._pick = tuple(pick) |
| 106 | + |
| 107 | + def remove_unused(self): |
| 108 | + """Delete all layers that are not needed for the forward pass. |
| 109 | +
|
| 110 | + """ |
| 111 | + if self._pick is None: |
| 112 | + return |
| 113 | + |
| 114 | + # The biggest index among indices of the layers that are included |
| 115 | + # in pick. |
| 116 | + last_index = max(self.layer_names.index(name) for name in self._pick) |
| 117 | + for name in self.layer_names[last_index + 1:]: |
| 118 | + delattr(self, name) |
| 119 | + |
| 120 | + def __call__(self, x): |
| 121 | + """Forward this model. |
| 122 | +
|
| 123 | + Args: |
| 124 | + x (chainer.Variable or array): Input to the model. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + chainer.Variable or tuple of chainer.Variable: |
| 128 | + The returned layers are determined by :obj:`pick`. |
| 129 | +
|
| 130 | + """ |
| 131 | + if self._pick is None: |
| 132 | + pick = (self.layer_names[-1],) |
| 133 | + else: |
| 134 | + pick = self._pick |
| 135 | + |
| 136 | + # The biggest index among indices of the layers that are included |
| 137 | + # in pick. |
| 138 | + last_index = max(self.layer_names.index(name) for name in pick) |
| 139 | + |
| 140 | + layers = dict() |
| 141 | + h = x |
| 142 | + for name in self.layer_names[:last_index + 1]: |
| 143 | + h = self[name](h) |
| 144 | + if name in pick: |
| 145 | + layers[name] = h |
| 146 | + |
| 147 | + if self._return_tuple: |
| 148 | + layers = tuple(layers[name] for name in pick) |
| 149 | + else: |
| 150 | + layers = list(layers.values())[0] |
| 151 | + return layers |
0 commit comments