layers_wrapper.py 14.2 KB
Newer Older
Y
Yibing Liu 已提交
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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
"""
Wrappers for fluid.layers. It helps to easily share parameters between layers.
"""

import operator
from collections import OrderedDict

import paddle.fluid.layers as layers
import paddle.fluid.unique_name as unique_name
from paddle.fluid.param_attr import ParamAttr


def update_attr(attr, name, prefix=None, suffix="W"):
    if attr == False:
        return False

    if prefix:
        name = prefix + "." + name
    new_name = unique_name.generate(name + "." + suffix)
    if attr is None:
        attr = ParamAttr(name=new_name)
    elif attr.name is None:
        attr.name = new_name
    return attr


class BaseLayer(object):
    def __init__(self):
        self._parameters = OrderedDict()
        self._layers = OrderedDict()

    def __getattr__(self, name):
        if '_parameters' in self.__dict__:
            _parameters = self.__dict__['_parameters']
            if name in _parameters:
                return _parameters[name]
        if '_layers' in self.__dict__:
            _layers = self.__dict__['_layers']
            if name in _layers:
                return _layers[name]
        if name in self.__dict__:
            return self.__dict__[name]
        raise AttributeError("'{}' object has no attribute '{}'".format(
            type(self).__name__, name))

    def __setattr__(self, name, value):
        def remove_from(*dicts):
            for d in dicts:
                if name in d:
                    del d[name]

        if isinstance(value, ParamAttr):
            self._parameters[name] = value
            remove_from(self.__dict__, self._layers)
        elif isinstance(value, BaseLayer):
            self._layers[name] = value
            remove_from(self.__dict__, self._parameters)
        else:
            object.__setattr__(self, name, value)

    def __call__(self, *args, **kwargs):
        raise NotImplementedError


class LayerList(BaseLayer):
    def __init__(self, layers):
        super(LayerList, self).__init__()
        self += layers

    def _get_abs_string_index(self, idx):
        """Get the absolute index for the list of layers"""
        idx = operator.index(idx)
        if not (-len(self) <= idx < len(self)):
            raise IndexError('index {} is out of range'.format(idx))
        if idx < 0:
            idx += len(self)
        return str(idx)

    def __getitem__(self, idx):
        if isinstance(idx, slice):
            return self.__class__(list(self._layers.values())[idx])
        else:
            return self._layers[self._get_abs_string_index(idx)]

    def __setitem__(self, idx, layer):
        idx = self._get_abs_string_index(idx)
        return setattr(self, str(idx), layer)

    def __delitem__(self, idx):
        if isinstance(idx, slice):
            for k in range(len(self._layers))[idx]:
                delattr(self, str(k))
        else:
            delattr(self, self._get_abs_string_index(idx))
        # To preserve numbering, self._layers is being reconstructed with layers after deletion
        str_indices = [str(i) for i in range(len(self._layers))]
        self._layers = OrderedDict(
            list(zip(str_indices, self._layers.values())))

    def __len__(self):
        return len(self._layers)

    def __iter__(self):
        return iter(self._layers.values())

    def __iadd__(self, layers):
        return self.extend(layers)

    def extend(self, layers):
        if not isinstance(layers, (list, tuple)):
            raise TypeError("LayerList.extend should be called with a "
                            "list or tuple, but got " + type(layers).__name__)
        offset = len(self)
        for i, layer in enumerate(layers):
            self._layers[str(offset + i)] = layer
        return self


class Sequential(BaseLayer):
    def __init__(self, *layers):
        super(Sequential, self).__init__()
        for idx, layer in enumerate(layers):
            if not isinstance(layer, BaseLayer):
                raise TypeError("{} is not a BaseLayer subclass".format(
                    type(layer)))
            self._layers[str(idx)] = layer

    def __call__(self, input):
        for layer in self._layers.values():
            input = layer(input)
        return input


class Embedding(BaseLayer):
    def __init__(self,
                 size,
                 is_sparse=False,
                 is_distributed=False,
                 padding_idx=None,
                 param_attr=None,
                 dtype='float32',
                 name=None):
        super(Embedding, self).__init__()
        self.name = name or "Embedding"
        self.size = size
        self.is_sparse = is_sparse
        self.is_distributed = False
        self.padding_idx = padding_idx
        self.param_attr = update_attr(param_attr, self.name, suffix="W")
        self.dtype = dtype

    def __call__(self, input):
        return layers.embedding(
            input=input,
            size=self.size,
            is_sparse=self.is_sparse,
            is_distributed=self.is_distributed,
            padding_idx=self.padding_idx,
            param_attr=self.param_attr,
            dtype=self.dtype)


class FC(BaseLayer):
    def __init__(self,
                 size,
                 num_flatten_dims=1,
                 param_attr=None,
                 bias_attr=None,
                 act=None,
                 is_test=False,
                 name=None):
        super(FC, self).__init__()
        self.name = name or "FC"
        self.size = size
        self.num_flatten_dims = num_flatten_dims
        self.param_attr = update_attr(param_attr, self.name, suffix="W")
        self.bias_attr = update_attr(bias_attr, self.name, suffix="b")
        self.act = act
        self.is_test = False

    def __call__(self, input, name=None):
        assert not isinstance(input, (list, tuple))
        return layers.fc(input=input,
                         size=self.size,
                         num_flatten_dims=self.num_flatten_dims,
                         param_attr=self.param_attr,
                         bias_attr=self.bias_attr,
                         act=self.act,
                         is_test=self.is_test,
                         name=name)


class DynamicGRU(BaseLayer):
    def __init__(self,
                 hidden_dim,
                 param_attr=None,
                 bias_attr=None,
                 input_param_attr=None,
                 input_bias_attr=None,
                 is_reverse=False,
                 gate_activation='sigmoid',
                 candidate_activation='tanh',
                 origin_mode=False,
                 name=None):
        super(DynamicGRU, self).__init__()
        self.name = name or "DynamicGRU"
        self.hidden_dim = hidden_dim
        self.param_attr = update_attr(param_attr, self.name, suffix="hidden.W")
        self.bias_attr = update_attr(bias_attr, self.name, suffix="hidden.b")
        self.input_param_attr = update_attr(
            input_param_attr, self.name, suffix="input.W")
        self.input_bias_attr = update_attr(
            input_bias_attr, self.name, suffix="input.b")
        self.is_reverse = is_reverse
        self.gate_activation = gate_activation
        self.candidate_activation = candidate_activation
        self.origin_mode = origin_mode

    def __call__(self, input, state=None):
        gru_input = layers.fc(input=input,
                              size=self.hidden_dim * 3,
                              param_attr=self.input_param_attr,
                              bias_attr=self.input_bias_attr)
        return layers.dynamic_gru(
            input=gru_input,
            size=self.hidden_dim,
            param_attr=self.param_attr,
            bias_attr=self.bias_attr,
            is_reverse=self.is_reverse,
            gate_activation=self.gate_activation,
            candidate_activation=self.candidate_activation,
            h_0=state,
            origin_mode=self.origin_mode)


class GRU(BaseLayer):
    def __init__(self,
                 hidden_dim,
                 num_layers=1,
                 bidirectional=False,
                 dropout=0.0,
                 name=None):
        super(GRU, self).__init__()
        if dropout > 0 and num_layers == 1:
            raise ValueError(
                "Non-zero dropout expects num_layers greater than 1")
        self.name = name or "GRU"
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.bidirectional = bidirectional
        self.num_directions = 2 if bidirectional else 1
        self.dropout = dropout
        rnns = []
        for l in range(num_layers):
            inners = []
            inners.append(
                DynamicGRU(
                    hidden_dim=hidden_dim, name="{}_l{}".format(self.name, l)))
            if bidirectional:
                inners.append(
                    DynamicGRU(
                        hidden_dim=hidden_dim,
                        name="{}_l{}_reverse".format(self.name, l),
                        is_reverse=True))
            rnns.append(LayerList(inners))
        self.rnns = LayerList(rnns)

    def __call__(self, input, hidden=None):
        if hidden is not None:
            assert len(hidden) == self.num_layers
            assert len(hidden[0]) == self.num_directions
        else:
            hidden = [[None] * self.num_directions] * self.num_layers
        new_hidden = []
        for l in range(self.num_layers):
            layer_output = []
            layer_hidden = []
            for i, inner in enumerate(self.rnns[l]):
                output = inner(input, hidden[l][i])
                layer_output.append(output)
                if inner.is_reverse:
                    layer_hidden.append(layers.sequence_first_step(output))
                else:
                    layer_hidden.append(layers.sequence_last_step(output))
            input = layers.concat(layer_output, axis=1)
            if self.dropout > 0 and l + 1 < self.num_layers:
                input = layers.dropout(
                    input,
                    dropout_prob=self.dropout,
                    dropout_implementation='upscale_in_train')
            new_hidden.append(layers.concat(layer_hidden, axis=1))
        return input, new_hidden


class GRUCell(BaseLayer):
    def __init__(self,
                 hidden_dim,
                 param_attr=None,
                 bias_attr=None,
                 input_param_attr=None,
                 input_bias_attr=None,
                 activation='tanh',
                 gate_activation='sigmoid',
                 origin_mode=False,
                 name=None):
        super(GRUCell, self).__init__()
        self.name = name or "GRUCell"
        self.hidden_dim = hidden_dim
        self.param_attr = update_attr(param_attr, self.name, suffix="hidden.W")
        self.bias_attr = update_attr(bias_attr, self.name, suffix="hidden.b")
        self.input_param_attr = update_attr(
            input_param_attr, self.name, suffix="input.W")
        self.input_bias_attr = update_attr(
            input_bias_attr, self.name, suffix="input.b")
        self.activation = activation
        self.gate_activation = gate_activation
        self.origin_mode = origin_mode

    def __call__(self, input, hidden):
        gru_input = layers.fc(input=input,
                              size=self.hidden_dim * 3,
                              param_attr=self.input_param_attr,
                              bias_attr=self.input_bias_attr)
        new_hidden, _, _ = layers.gru_unit(
            input=gru_input,
            hidden=hidden,
            size=self.hidden_dim * 3,
            param_attr=self.param_attr,
            bias_attr=self.bias_attr,
            activation=self.activation,
            gate_activation=self.gate_activation,
            origin_mode=self.origin_mode)
        return new_hidden, new_hidden


class StackedGRUCell(BaseLayer):
    def __init__(self, hidden_dim, num_layers=1, dropout=0.0, name=None):
        super(StackedGRUCell, self).__init__()
        if dropout > 0 and num_layers == 1:
            raise ValueError(
                "Non-zero dropout expects num_layers greater than 1")

        self.name = name or "StackedGRUCell"
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.dropout = dropout

        cells = [
            GRUCell(
                hidden_dim=hidden_dim, name="{}_l{}".format(self.name, l))
            for l in range(self.num_layers)
        ]
        self.cells = LayerList(cells)

    def __call__(self, input, hidden):
        assert len(hidden) == self.num_layers
        new_hidden = []
        for cell, hid in zip(self.cells, hidden):
            input, new_hid = cell(input, hid)
            new_hidden += [new_hid]
            if self.dropout > 0:
                input = layers.dropout(
                    input,
                    dropout_prob=self.dropout,
                    dropout_implementation='upscale_in_train')
        output = new_hidden[-1]
        return output, new_hidden


class Dropout(BaseLayer):
    def __init__(self, dropout_prob, is_test=False, seed=None, name=None):
        super(Dropout, self).__init__()
        self.dropout_prob = dropout_prob
        self.is_test = is_test
        self.seed = seed
        self.name = name

    def __call__(self, input):
        if self.dropout_prob > 0.0:
            return layers.dropout(
                input,
                dropout_prob=self.dropout_prob,
                is_test=self.is_test,
                seed=self.seed,
                name=self.name,
                dropout_implementation='upscale_in_train')
        else:
            return input