rnn_impl.py 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15 16
import copy

17
import paddle
18
from paddle.fluid import layers, unique_name
19
from paddle.fluid.dygraph import Layer
20
from paddle.fluid.dygraph.layer_object_helper import LayerObjectHelper
21
from paddle.fluid.layers.control_flow import StaticRNN
22
import paddle
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

__all__ = ['BasicGRUUnit', 'basic_gru', 'BasicLSTMUnit', 'basic_lstm']


class BasicGRUUnit(Layer):
    """
    ****
    BasicGRUUnit class, using basic operators to build GRU
    The algorithm can be described as the equations below.

        .. math::
            u_t & = actGate(W_ux xu_{t} + W_uh h_{t-1} + b_u)

            r_t & = actGate(W_rx xr_{t} + W_rh h_{t-1} + b_r)

            m_t & = actNode(W_cx xm_t + W_ch dot(r_t, h_{t-1}) + b_m)

            h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t)

    Args:
        name_scope(string) : The name scope used to identify parameters and biases
        hidden_size (integer): The hidden size used in the Unit.
        param_attr(ParamAttr|None): The parameter attribute for the learnable
            weight matrix. Note:
            If it is set to None or one attribute of ParamAttr, gru_unit will
            create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr (ParamAttr|None): The parameter attribute for the bias
            of GRU unit.
52
            If it is set to None or one attribute of ParamAttr, gru_unit will
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
            create ParamAttr as bias_attr. If the Initializer of the bias_attr
            is not set, the bias is initialized zero. Default: None.
        gate_activation (function|None): The activation function for gates (actGate).
                                  Default: 'fluid.layers.sigmoid'
        activation (function|None): The activation function for cell (actNode).
                             Default: 'fluid.layers.tanh'
        dtype(string): data type used in this unit

    Examples:

        .. code-block:: python

            import paddle.fluid.layers as layers
            from paddle.fluid.contrib.layers import BasicGRUUnit

            input_size = 128
            hidden_size = 256
            input = layers.data( name = "input", shape = [-1, input_size], dtype='float32')
            pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32')

            gru_unit = BasicGRUUnit( "gru_unit", hidden_size )

            new_hidden = gru_unit( input, pre_hidden )

    """

79 80 81 82 83 84 85 86 87 88
    def __init__(
        self,
        name_scope,
        hidden_size,
        param_attr=None,
        bias_attr=None,
        gate_activation=None,
        activation=None,
        dtype='float32',
    ):
89
        super().__init__(name_scope, dtype)
90
        # reserve old school _full_name and _helper for static graph save load
91 92 93
        self._full_name = unique_name.generate(
            name_scope + "/" + self.__class__.__name__
        )
94
        self._helper = LayerObjectHelper(self._full_name)
95 96 97 98 99

        self._name = name_scope
        self._hiden_size = hidden_size
        self._param_attr = param_attr
        self._bias_attr = bias_attr
100 101
        self._gate_activation = gate_activation or paddle.nn.functional.sigmoid
        self._activation = activation or paddle.tanh
102 103 104 105
        self._dtype = dtype

    def _build_once(self, input, pre_hidden):
        self._input_size = input.shape[-1]
106
        assert self._input_size > 0
107

108 109 110 111 112 113 114 115 116
        if self._param_attr is not None and self._param_attr.name is not None:
            gate_param_attr = copy.deepcopy(self._param_attr)
            candidate_param_attr = copy.deepcopy(self._param_attr)
            gate_param_attr.name += "_gate"
            candidate_param_attr.name += "_candidate"
        else:
            gate_param_attr = self._param_attr
            candidate_param_attr = self._param_attr

117
        self._gate_weight = self.create_parameter(
118
            attr=gate_param_attr,
119
            shape=[self._input_size + self._hiden_size, 2 * self._hiden_size],
120 121
            dtype=self._dtype,
        )
122 123

        self._candidate_weight = self.create_parameter(
124
            attr=candidate_param_attr,
125
            shape=[self._input_size + self._hiden_size, self._hiden_size],
126 127
            dtype=self._dtype,
        )
128

129 130 131 132 133 134 135 136 137
        if self._bias_attr is not None and self._bias_attr.name is not None:
            gate_bias_attr = copy.deepcopy(self._bias_attr)
            candidate_bias_attr = copy.deepcopy(self._bias_attr)
            gate_bias_attr.name += "_gate"
            candidate_bias_attr.name += "_candidate"
        else:
            gate_bias_attr = self._bias_attr
            candidate_bias_attr = self._bias_attr

138 139 140 141 142 143 144 145 146 147 148 149
        self._gate_bias = self.create_parameter(
            attr=gate_bias_attr,
            shape=[2 * self._hiden_size],
            dtype=self._dtype,
            is_bias=True,
        )
        self._candidate_bias = self.create_parameter(
            attr=candidate_bias_attr,
            shape=[self._hiden_size],
            dtype=self._dtype,
            is_bias=True,
        )
150 151 152 153 154 155

    def forward(self, input, pre_hidden):
        concat_input_hidden = layers.concat([input, pre_hidden], 1)

        gate_input = layers.matmul(x=concat_input_hidden, y=self._gate_weight)

156
        gate_input = paddle.add(gate_input, self._gate_bias)
157 158 159 160 161 162

        gate_input = self._gate_activation(gate_input)
        r, u = layers.split(gate_input, num_or_sections=2, dim=1)

        r_hidden = r * pre_hidden

163 164 165
        candidate = layers.matmul(
            layers.concat([input, r_hidden], 1), self._candidate_weight
        )
166
        candidate = paddle.add(candidate, self._candidate_bias)
167 168 169 170 171 172 173

        c = self._activation(candidate)
        new_hidden = u * pre_hidden + (1 - u) * c

        return new_hidden


174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
def basic_gru(
    input,
    init_hidden,
    hidden_size,
    num_layers=1,
    sequence_length=None,
    dropout_prob=0.0,
    bidirectional=False,
    batch_first=True,
    param_attr=None,
    bias_attr=None,
    gate_activation=None,
    activation=None,
    dtype='float32',
    name='basic_gru',
):
190
    r"""
T
tianshuo78520a 已提交
191
    GRU implementation using basic operator, supports multiple layers and bidirectional gru.
192 193 194 195 196 197 198 199 200 201 202

    .. math::
            u_t & = actGate(W_ux xu_{t} + W_uh h_{t-1} + b_u)

            r_t & = actGate(W_rx xr_{t} + W_rh h_{t-1} + b_r)

            m_t & = actNode(W_cx xm_t + W_ch dot(r_t, h_{t-1}) + b_m)

            h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t)

    Args:
203 204
        input (Variable): GRU input tensor,
                       if batch_first = False, shape should be ( seq_len x batch_size x input_size )
205 206 207 208 209 210 211 212 213 214 215
                       if batch_first = True, shape should be ( batch_size x seq_len x hidden_size )
        init_hidden(Variable|None): The initial hidden state of the GRU
                       This is a tensor with shape ( num_layers x batch_size x hidden_size)
                       if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size)
                       and can be reshaped to tensor with ( num_layers x 2 x batch_size x hidden_size) to use.
                       If it's None, it will be set to all 0.
        hidden_size (int): Hidden size of the GRU
        num_layers (int): The total number of layers of the GRU
        sequence_length (Variabe|None): A Tensor (shape [batch_size]) stores each real length of each instance,
                        This tensor will be convert to a mask to mask the padding ids
                        If it's None means NO padding ids
216
        dropout_prob(float|0.0): Dropout prob, dropout ONLY works after rnn output of each layers,
217 218
                             NOT between time steps
        bidirectional (bool|False): If it is bidirectional
219 220 221 222 223
        batch_first (bool|True): The shape format of the input and output tensors. If true,
            the shape format should be :attr:`[batch_size, seq_len, hidden_size]`. If false,
            the shape format should be :attr:`[seq_len, batch_size, hidden_size]`. By default
            this function accepts input and emits output in batch-major form to be consistent
            with most of data format, though a bit less efficient because of extra transposes.
224 225 226 227 228 229 230
        param_attr(ParamAttr|None): The parameter attribute for the learnable
            weight matrix. Note:
            If it is set to None or one attribute of ParamAttr, gru_unit will
            create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr (ParamAttr|None): The parameter attribute for the bias
            of GRU unit.
231
            If it is set to None or one attribute of ParamAttr, gru_unit will
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            create ParamAttr as bias_attr. If the Initializer of the bias_attr
            is not set, the bias is initialized zero. Default: None.
        gate_activation (function|None): The activation function for gates (actGate).
                                  Default: 'fluid.layers.sigmoid'
        activation (function|None): The activation function for cell (actNode).
                             Default: 'fluid.layers.tanh'
        dtype(string): data type used in this unit
        name(string): name used to identify parameters and biases

    Returns:
        rnn_out(Tensor),last_hidden(Tensor)
            - rnn_out is result of GRU hidden, with shape (seq_len x batch_size x hidden_size) \
              if is_bidirec set to True, shape will be ( seq_len x batch_sze x hidden_size*2)
            - last_hidden is the hidden state of the last step of GRU \
              shape is ( num_layers x batch_size x hidden_size ) \
              if is_bidirec set to True, shape will be ( num_layers*2 x batch_size x hidden_size),
              can be reshaped to a tensor with shape( num_layers x 2 x batch_size x hidden_size)

    Examples:
        .. code-block:: python
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
            import paddle.fluid.layers as layers
            from paddle.fluid.contrib.layers import basic_gru

            batch_size = 20
            input_size = 128
            hidden_size = 256
            num_layers = 2
            dropout = 0.5
            bidirectional = True
            batch_first = False

            input = layers.data( name = "input", shape = [-1, batch_size, input_size], dtype='float32')
            pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32')
            sequence_length = layers.data( name="sequence_length", shape=[-1], dtype='int32')


            rnn_out, last_hidden = basic_gru( input, pre_hidden, hidden_size, num_layers = num_layers, \
                    sequence_length = sequence_length, dropout_prob=dropout, bidirectional = bidirectional, \
                    batch_first = batch_first)

    """

    fw_unit_list = []

    for i in range(num_layers):
        new_name = name + "_layers_" + str(i)
279 280 281 282 283 284 285 286 287 288
        if param_attr is not None and param_attr.name is not None:
            layer_param_attr = copy.deepcopy(param_attr)
            layer_param_attr.name += "_fw_w_" + str(i)
        else:
            layer_param_attr = param_attr
        if bias_attr is not None and bias_attr.name is not None:
            layer_bias_attr = copy.deepcopy(bias_attr)
            layer_bias_attr.name += "_fw_b_" + str(i)
        else:
            layer_bias_attr = bias_attr
289
        fw_unit_list.append(
290 291 292 293 294 295 296 297 298 299
            BasicGRUUnit(
                new_name,
                hidden_size,
                layer_param_attr,
                layer_bias_attr,
                gate_activation,
                activation,
                dtype,
            )
        )
300 301 302 303 304
    if bidirectional:
        bw_unit_list = []

        for i in range(num_layers):
            new_name = name + "_reverse_layers_" + str(i)
305 306 307 308 309 310 311 312 313 314 315
            if param_attr is not None and param_attr.name is not None:
                layer_param_attr = copy.deepcopy(param_attr)
                layer_param_attr.name += "_bw_w_" + str(i)
            else:
                layer_param_attr = param_attr
            if bias_attr is not None and bias_attr.name is not None:
                layer_bias_attr = copy.deepcopy(bias_attr)
                layer_bias_attr.name += "_bw_b_" + str(i)
            else:
                layer_bias_attr = bias_attr

316
            bw_unit_list.append(
317 318 319 320 321 322 323 324 325 326
                BasicGRUUnit(
                    new_name,
                    hidden_size,
                    layer_param_attr,
                    layer_bias_attr,
                    gate_activation,
                    activation,
                    dtype,
                )
            )
327 328

    if batch_first:
329
        input = paddle.transpose(input, [1, 0, 2])
330 331 332

    mask = None
    if sequence_length:
2
201716010711 已提交
333
        max_seq_len = paddle.shape(input)[0]
334 335 336
        mask = layers.sequence_mask(
            sequence_length, maxlen=max_seq_len, dtype='float32'
        )
337
        mask = paddle.transpose(mask, [1, 0])
338 339 340 341 342

    direc_num = 1
    if bidirectional:
        direc_num = 2
    if init_hidden:
343
        init_hidden = paddle.reshape(
344 345
            init_hidden, shape=[num_layers, direc_num, -1, hidden_size]
        )
346

347 348 349
    def get_single_direction_output(
        rnn_input, unit_list, mask=None, direc_index=0
    ):
350 351 352 353 354 355 356 357 358 359 360
        rnn = StaticRNN()
        with rnn.step():
            step_input = rnn.step_input(rnn_input)

            if mask:
                step_mask = rnn.step_input(mask)

            for i in range(num_layers):
                if init_hidden:
                    pre_hidden = rnn.memory(init=init_hidden[i, direc_index])
                else:
361 362 363 364 365
                    pre_hidden = rnn.memory(
                        batch_ref=rnn_input,
                        shape=[-1, hidden_size],
                        ref_batch_dim_idx=1,
                    )
366 367 368 369 370

                new_hidden = unit_list[i](step_input, pre_hidden)

                if mask:
                    new_hidden = layers.elementwise_mul(
371 372 373 374
                        new_hidden, step_mask, axis=0
                    ) - layers.elementwise_mul(
                        pre_hidden, (step_mask - 1), axis=0
                    )
375 376 377 378 379
                rnn.update_memory(pre_hidden, new_hidden)

                rnn.step_output(new_hidden)

                step_input = new_hidden
380
                if dropout_prob is not None and dropout_prob > 0.0:
381 382
                    step_input = layers.dropout(
                        step_input,
383 384
                        dropout_prob=dropout_prob,
                    )
385 386 387 388 389 390 391 392 393 394 395 396 397

            rnn.step_output(step_input)

        rnn_out = rnn()

        last_hidden_array = []
        rnn_output = rnn_out[-1]
        for i in range(num_layers):
            last_hidden = rnn_out[i]
            last_hidden = last_hidden[-1]
            last_hidden_array.append(last_hidden)

        last_hidden_output = layers.concat(last_hidden_array, axis=0)
398
        last_hidden_output = paddle.reshape(
399 400
            last_hidden_output, shape=[num_layers, -1, hidden_size]
        )
401 402 403 404

        return rnn_output, last_hidden_output
        # seq_len, batch_size, hidden_size

405 406 407
    fw_rnn_out, fw_last_hidden = get_single_direction_output(
        input, fw_unit_list, mask, direc_index=0
    )
408 409

    if bidirectional:
410
        bw_input = paddle.reverse(input, axis=[0])
411 412
        bw_mask = None
        if mask:
413
            bw_mask = paddle.reverse(mask, axis=[0])
414 415 416
        bw_rnn_out, bw_last_hidden = get_single_direction_output(
            bw_input, bw_unit_list, bw_mask, direc_index=1
        )
417

418
        bw_rnn_out = paddle.reverse(bw_rnn_out, axis=[0])
419 420 421 422

        rnn_out = layers.concat([fw_rnn_out, bw_rnn_out], axis=2)
        last_hidden = layers.concat([fw_last_hidden, bw_last_hidden], axis=1)

423
        last_hidden = paddle.reshape(
424 425
            last_hidden, shape=[num_layers * direc_num, -1, hidden_size]
        )
426 427

        if batch_first:
428
            rnn_out = paddle.transpose(rnn_out, [1, 0, 2])
429 430 431 432 433 434 435
        return rnn_out, last_hidden
    else:

        rnn_out = fw_rnn_out
        last_hidden = fw_last_hidden

        if batch_first:
436
            rnn_out = paddle.transpose(rnn_out, [1, 0, 2])
437 438 439 440

        return rnn_out, last_hidden


441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
def basic_lstm(
    input,
    init_hidden,
    init_cell,
    hidden_size,
    num_layers=1,
    sequence_length=None,
    dropout_prob=0.0,
    bidirectional=False,
    batch_first=True,
    param_attr=None,
    bias_attr=None,
    gate_activation=None,
    activation=None,
    forget_bias=1.0,
    dtype='float32',
    name='basic_lstm',
):
459
    r"""
T
tianshuo78520a 已提交
460
    LSTM implementation using basic operators, supports multiple layers and bidirectional LSTM.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

    .. math::
           i_t &= \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_i)

           f_t &= \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_f + forget_bias )

           o_t &= \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_o)

           \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + b_c)

           c_t &= f_t \odot c_{t-1} + i_t \odot \\tilde{c_t}

           h_t &= o_t \odot tanh(c_t)

    Args:
476 477
        input (Variable): lstm input tensor,
                       if batch_first = False, shape should be ( seq_len x batch_size x input_size )
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                       if batch_first = True, shape should be ( batch_size x seq_len x hidden_size )
        init_hidden(Variable|None): The initial hidden state of the LSTM
                       This is a tensor with shape ( num_layers x batch_size x hidden_size)
                       if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size)
                       and can be reshaped to a tensor with shape ( num_layers x 2 x batch_size x hidden_size) to use.
                       If it's None, it will be set to all 0.
        init_cell(Variable|None): The initial hidden state of the LSTM
                       This is a tensor with shape ( num_layers x batch_size x hidden_size)
                       if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size)
                       and can be reshaped to a tensor with shape ( num_layers x 2 x batch_size x hidden_size) to use.
                       If it's None, it will be set to all 0.
        hidden_size (int): Hidden size of the LSTM
        num_layers (int): The total number of layers of the LSTM
        sequence_length (Variabe|None): A tensor (shape [batch_size]) stores each real length of each instance,
                        This tensor will be convert to a mask to mask the padding ids
                        If it's None means NO padding ids
494
        dropout_prob(float|0.0): Dropout prob, dropout ONLY work after rnn output of each layers,
495 496
                             NOT between time steps
        bidirectional (bool|False): If it is bidirectional
497 498 499 500 501
        batch_first (bool|True): The shape format of the input and output tensors. If true,
            the shape format should be :attr:`[batch_size, seq_len, hidden_size]`. If false,
            the shape format should be :attr:`[seq_len, batch_size, hidden_size]`. By default
            this function accepts input and emits output in batch-major form to be consistent
            with most of data format, though a bit less efficient because of extra transposes.
502 503 504 505 506 507 508
        param_attr(ParamAttr|None): The parameter attribute for the learnable
            weight matrix. Note:
            If it is set to None or one attribute of ParamAttr, lstm_unit will
            create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr (ParamAttr|None): The parameter attribute for the bias
            of LSTM unit.
509
            If it is set to None or one attribute of ParamAttr, lstm_unit will
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            create ParamAttr as bias_attr. If the Initializer of the bias_attr
            is not set, the bias is initialized zero. Default: None.
        gate_activation (function|None): The activation function for gates (actGate).
                                  Default: 'fluid.layers.sigmoid'
        activation (function|None): The activation function for cell (actNode).
                             Default: 'fluid.layers.tanh'
        forget_bias (float|1.0) : Forget bias used to compute the forget gate
        dtype(string): Data type used in this unit
        name(string): Name used to identify parameters and biases

    Returns:
        rnn_out(Tensor), last_hidden(Tensor), last_cell(Tensor)
            - rnn_out is the result of LSTM hidden, shape is (seq_len x batch_size x hidden_size) \
              if is_bidirec set to True, it's shape will be ( seq_len x batch_sze x hidden_size*2)
            - last_hidden is the hidden state of the last step of LSTM \
              with shape ( num_layers x batch_size x hidden_size ) \
              if is_bidirec set to True, it's shape will be ( num_layers*2 x batch_size x hidden_size),
              and can be reshaped to a tensor ( num_layers x 2 x batch_size x hidden_size)  to use.
            - last_cell is the hidden state of the last step of LSTM \
              with shape ( num_layers x batch_size x hidden_size ) \
              if is_bidirec set to True, it's shape will be ( num_layers*2 x batch_size x hidden_size),
              and can be reshaped to a tensor ( num_layers x 2 x batch_size x hidden_size)  to use.

    Examples:
        .. code-block:: python
535

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
            import paddle.fluid.layers as layers
            from paddle.fluid.contrib.layers import basic_lstm

            batch_size = 20
            input_size = 128
            hidden_size = 256
            num_layers = 2
            dropout = 0.5
            bidirectional = True
            batch_first = False

            input = layers.data( name = "input", shape = [-1, batch_size, input_size], dtype='float32')
            pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32')
            pre_cell = layers.data( name = "pre_cell", shape=[-1, hidden_size], dtype='float32')
            sequence_length = layers.data( name="sequence_length", shape=[-1], dtype='int32')

            rnn_out, last_hidden, last_cell = basic_lstm( input, pre_hidden, pre_cell, \
                    hidden_size, num_layers = num_layers, \
                    sequence_length = sequence_length, dropout_prob=dropout, bidirectional = bidirectional, \
                    batch_first = batch_first)

    """
    fw_unit_list = []

    for i in range(num_layers):
        new_name = name + "_layers_" + str(i)
562 563 564 565 566 567 568 569 570 571
        if param_attr is not None and param_attr.name is not None:
            layer_param_attr = copy.deepcopy(param_attr)
            layer_param_attr.name += "_fw_w_" + str(i)
        else:
            layer_param_attr = param_attr
        if bias_attr is not None and bias_attr.name is not None:
            layer_bias_attr = copy.deepcopy(bias_attr)
            layer_bias_attr.name += "_fw_b_" + str(i)
        else:
            layer_bias_attr = bias_attr
572
        fw_unit_list.append(
573 574 575 576 577 578 579 580 581 582 583
            BasicLSTMUnit(
                new_name,
                hidden_size,
                param_attr=layer_param_attr,
                bias_attr=layer_bias_attr,
                gate_activation=gate_activation,
                activation=activation,
                forget_bias=forget_bias,
                dtype=dtype,
            )
        )
584 585 586 587 588
    if bidirectional:
        bw_unit_list = []

        for i in range(num_layers):
            new_name = name + "_reverse_layers_" + str(i)
589 590 591 592 593 594 595 596 597 598
            if param_attr is not None and param_attr.name is not None:
                layer_param_attr = copy.deepcopy(param_attr)
                layer_param_attr.name += "_bw_w_" + str(i)
            else:
                layer_param_attr = param_attr
            if bias_attr is not None and bias_attr.name is not None:
                layer_bias_attr = copy.deepcopy(bias_attr)
                layer_bias_attr.name += "_bw_b_" + str(i)
            else:
                layer_bias_attr = param_attr
599
            bw_unit_list.append(
600 601 602 603 604 605 606 607 608 609 610
                BasicLSTMUnit(
                    new_name,
                    hidden_size,
                    param_attr=layer_param_attr,
                    bias_attr=layer_bias_attr,
                    gate_activation=gate_activation,
                    activation=activation,
                    forget_bias=forget_bias,
                    dtype=dtype,
                )
            )
611 612

    if batch_first:
613
        input = paddle.transpose(input, [1, 0, 2])
614 615 616

    mask = None
    if sequence_length:
2
201716010711 已提交
617
        max_seq_len = paddle.shape(input)[0]
618 619 620
        mask = layers.sequence_mask(
            sequence_length, maxlen=max_seq_len, dtype='float32'
        )
621

622
        mask = paddle.transpose(mask, [1, 0])
623 624 625 626 627 628

    direc_num = 1
    if bidirectional:
        direc_num = 2
        # convert to [num_layers, 2, batch_size, hidden_size]
    if init_hidden:
629
        init_hidden = paddle.reshape(
630 631
            init_hidden, shape=[num_layers, direc_num, -1, hidden_size]
        )
632
        init_cell = paddle.reshape(
633 634
            init_cell, shape=[num_layers, direc_num, -1, hidden_size]
        )
635 636

    # forward direction
637 638 639
    def get_single_direction_output(
        rnn_input, unit_list, mask=None, direc_index=0
    ):
640 641 642 643 644 645 646 647 648 649 650 651
        rnn = StaticRNN()
        with rnn.step():
            step_input = rnn.step_input(rnn_input)

            if mask:
                step_mask = rnn.step_input(mask)

            for i in range(num_layers):
                if init_hidden:
                    pre_hidden = rnn.memory(init=init_hidden[i, direc_index])
                    pre_cell = rnn.memory(init=init_cell[i, direc_index])
                else:
652 653 654 655 656 657
                    pre_hidden = rnn.memory(
                        batch_ref=rnn_input, shape=[-1, hidden_size]
                    )
                    pre_cell = rnn.memory(
                        batch_ref=rnn_input, shape=[-1, hidden_size]
                    )
658

659 660 661
                new_hidden, new_cell = unit_list[i](
                    step_input, pre_hidden, pre_cell
                )
662 663 664

                if mask:
                    new_hidden = layers.elementwise_mul(
665 666 667 668
                        new_hidden, step_mask, axis=0
                    ) - layers.elementwise_mul(
                        pre_hidden, (step_mask - 1), axis=0
                    )
669
                    new_cell = layers.elementwise_mul(
670 671 672 673
                        new_cell, step_mask, axis=0
                    ) - layers.elementwise_mul(
                        pre_cell, (step_mask - 1), axis=0
                    )
674 675 676 677 678 679 680 681

                rnn.update_memory(pre_hidden, new_hidden)
                rnn.update_memory(pre_cell, new_cell)

                rnn.step_output(new_hidden)
                rnn.step_output(new_cell)

                step_input = new_hidden
682
                if dropout_prob is not None and dropout_prob > 0.0:
683 684 685
                    step_input = layers.dropout(
                        step_input,
                        dropout_prob=dropout_prob,
686 687
                        dropout_implementation='upscale_in_train',
                    )
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

            rnn.step_output(step_input)

        rnn_out = rnn()

        last_hidden_array = []
        last_cell_array = []
        rnn_output = rnn_out[-1]
        for i in range(num_layers):
            last_hidden = rnn_out[i * 2]
            last_hidden = last_hidden[-1]
            last_hidden_array.append(last_hidden)
            last_cell = rnn_out[i * 2 + 1]
            last_cell = last_cell[-1]
            last_cell_array.append(last_cell)

        last_hidden_output = layers.concat(last_hidden_array, axis=0)
705
        last_hidden_output = paddle.reshape(
706 707
            last_hidden_output, shape=[num_layers, -1, hidden_size]
        )
708
        last_cell_output = layers.concat(last_cell_array, axis=0)
709
        last_cell_output = paddle.reshape(
710 711
            last_cell_output, shape=[num_layers, -1, hidden_size]
        )
712 713 714 715 716

        return rnn_output, last_hidden_output, last_cell_output
        # seq_len, batch_size, hidden_size

    fw_rnn_out, fw_last_hidden, fw_last_cell = get_single_direction_output(
717 718
        input, fw_unit_list, mask, direc_index=0
    )
719 720

    if bidirectional:
721
        bw_input = paddle.reverse(input, axis=[0])
722 723
        bw_mask = None
        if mask:
724
            bw_mask = paddle.reverse(mask, axis=[0])
725
        bw_rnn_out, bw_last_hidden, bw_last_cell = get_single_direction_output(
726 727
            bw_input, bw_unit_list, bw_mask, direc_index=1
        )
728

729
        bw_rnn_out = paddle.reverse(bw_rnn_out, axis=[0])
730 731 732

        rnn_out = layers.concat([fw_rnn_out, bw_rnn_out], axis=2)
        last_hidden = layers.concat([fw_last_hidden, bw_last_hidden], axis=1)
733
        last_hidden = paddle.reshape(
734 735
            last_hidden, shape=[num_layers * direc_num, -1, hidden_size]
        )
736 737

        last_cell = layers.concat([fw_last_cell, bw_last_cell], axis=1)
738
        last_cell = paddle.reshape(
739 740
            last_cell, shape=[num_layers * direc_num, -1, hidden_size]
        )
741 742

        if batch_first:
743
            rnn_out = paddle.transpose(rnn_out, [1, 0, 2])
744 745 746 747 748 749 750 751
        return rnn_out, last_hidden, last_cell
    else:

        rnn_out = fw_rnn_out
        last_hidden = fw_last_hidden
        last_cell = fw_last_cell

        if batch_first:
752
            rnn_out = paddle.transpose(rnn_out, [1, 0, 2])
753 754 755 756 757

        return rnn_out, last_hidden, last_cell


class BasicLSTMUnit(Layer):
758
    r"""
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    ****
    BasicLSTMUnit class, Using basic operator to build LSTM
    The algorithm can be described as the code below.

        .. math::

           i_t &= \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_i)

           f_t &= \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_f + forget_bias )

           o_t &= \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_o)

           \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + b_c)

           c_t &= f_t \odot c_{t-1} + i_t \odot \\tilde{c_t}

           h_t &= o_t \odot tanh(c_t)

        - $W$ terms denote weight matrices (e.g. $W_{ix}$ is the matrix
          of weights from the input gate to the input)
        - The b terms denote bias vectors ($bx_i$ and $bh_i$ are the input gate bias vector).
        - sigmoid is the logistic sigmoid function.
        - $i, f, o$ and $c$ are the input gate, forget gate, output gate,
          and cell activation vectors, respectively, all of which have the same size as
          the cell output activation vector $h$.
        - The :math:`\odot` is the element-wise product of the vectors.
        - :math:`tanh` is the activation functions.
        - :math:`\\tilde{c_t}` is also called candidate hidden state,
          which is computed based on the current input and the previous hidden state.

    Args:
        name_scope(string) : The name scope used to identify parameter and bias name
        hidden_size (integer): The hidden size used in the Unit.
        param_attr(ParamAttr|None): The parameter attribute for the learnable
            weight matrix. Note:
            If it is set to None or one attribute of ParamAttr, lstm_unit will
            create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with Xavier. Default: None.
        bias_attr (ParamAttr|None): The parameter attribute for the bias
            of LSTM unit.
799
            If it is set to None or one attribute of ParamAttr, lstm_unit will
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
            create ParamAttr as bias_attr. If the Initializer of the bias_attr
            is not set, the bias is initialized as zero. Default: None.
        gate_activation (function|None): The activation function for gates (actGate).
                                  Default: 'fluid.layers.sigmoid'
        activation (function|None): The activation function for cells (actNode).
                             Default: 'fluid.layers.tanh'
        forget_bias(float|1.0): forget bias used when computing forget gate
        dtype(string): data type used in this unit

    Examples:

        .. code-block:: python

            import paddle.fluid.layers as layers
            from paddle.fluid.contrib.layers import BasicLSTMUnit

            input_size = 128
            hidden_size = 256
            input = layers.data( name = "input", shape = [-1, input_size], dtype='float32')
            pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32')
            pre_cell = layers.data( name = "pre_cell", shape=[-1, hidden_size], dtype='float32')

            lstm_unit = BasicLSTMUnit( "gru_unit", hidden_size)

            new_hidden, new_cell = lstm_unit( input, pre_hidden, pre_cell )

    """

828 829 830 831 832 833 834 835 836 837 838
    def __init__(
        self,
        name_scope,
        hidden_size,
        param_attr=None,
        bias_attr=None,
        gate_activation=None,
        activation=None,
        forget_bias=1.0,
        dtype='float32',
    ):
839
        super().__init__(name_scope, dtype)
840
        # reserve old school _full_name and _helper for static graph save load
841 842 843
        self._full_name = unique_name.generate(
            name_scope + "/" + self.__class__.__name__
        )
844
        self._helper = LayerObjectHelper(self._full_name)
845 846 847 848 849

        self._name = name_scope
        self._hiden_size = hidden_size
        self._param_attr = param_attr
        self._bias_attr = bias_attr
850 851
        self._gate_activation = gate_activation or paddle.nn.functional.sigmoid
        self._activation = activation or paddle.tanh
852 853 854
        self._forget_bias = layers.fill_constant(
            [1], dtype=dtype, value=forget_bias
        )
855 856 857 858 859
        self._forget_bias.stop_gradient = False
        self._dtype = dtype

    def _build_once(self, input, pre_hidden, pre_cell):
        self._input_size = input.shape[-1]
860
        assert self._input_size > 0
861 862 863 864

        self._weight = self.create_parameter(
            attr=self._param_attr,
            shape=[self._input_size + self._hiden_size, 4 * self._hiden_size],
865 866
            dtype=self._dtype,
        )
867

868 869 870 871 872 873
        self._bias = self.create_parameter(
            attr=self._bias_attr,
            shape=[4 * self._hiden_size],
            dtype=self._dtype,
            is_bias=True,
        )
874 875 876 877 878

    def forward(self, input, pre_hidden, pre_cell):
        concat_input_hidden = layers.concat([input, pre_hidden], 1)
        gate_input = layers.matmul(x=concat_input_hidden, y=self._weight)

879
        gate_input = paddle.add(gate_input, self._bias)
880
        i, j, f, o = layers.split(gate_input, num_or_sections=4, dim=-1)
881 882
        new_cell = paddle.add(
            paddle.multiply(
883
                pre_cell,
884
                paddle.nn.functional.sigmoid(paddle.add(f, self._forget_bias)),
885
            ),
886
            paddle.multiply(paddle.nn.functional.sigmoid(i), paddle.tanh(j)),
887
        )
888
        new_hidden = paddle.tanh(new_cell) * paddle.nn.functional.sigmoid(o)
889 890

        return new_hidden, new_cell