rnn.py 78.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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.

F
Feiyu Chan 已提交
15
import math
16
from collections.abc import Sequence
17
from functools import partial, reduce
F
Feiyu Chan 已提交
18

19
import numpy as np
20

F
Feiyu Chan 已提交
21
import paddle
22
from paddle import _C_ops, _legacy_C_ops, framework, in_dynamic_mode
23
from paddle.common_ops_import import Variable
24
from paddle.fluid.data_feeder import check_type, check_variable_and_dtype
25
from paddle.fluid.dygraph.base import NON_PERSISTABLE_VAR_NAME_SUFFIX
26 27 28 29 30
from paddle.fluid.framework import (
    default_startup_program,
    in_dygraph_mode,
    program_guard,
)
Z
zhiboniu 已提交
31
from paddle.framework import core
32 33
from paddle.nn import functional as F
from paddle.nn import initializer as I
L
liu zhengxi 已提交
34
from paddle.tensor.manipulation import tensor_array_to_tensor
35

36
from .container import LayerList
37
from .layers import Layer
Z
zhiboniu 已提交
38

39 40
__all__ = []

F
Feiyu Chan 已提交
41

42 43 44 45 46 47 48
def rnn(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
49
    **kwargs,
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
):
    r"""
    rnn creates a recurrent neural network specified by RNNCell `cell`,
    which performs :code:`cell.call()` (for dygraph mode :code:`cell.forward`)
    repeatedly until reaches to the maximum length of `inputs`.

    Parameters:
        cell(RNNCellBase): An instance of `RNNCellBase`.
        inputs(Tensor): the input sequences.
            If time_major is True, the shape is
            `[time_steps, batch_size, input_size]`
            else the shape is `[batch_size, time_steps, input_size]`.
        initial_states(Tensor|tuple|list, optional): the initial state of the
            rnn cell. Tensor or a possibly nested structure of tensors. If not
            provided, `cell.get_initial_states` would be called to produce
            the initial state. Defaults to None.
        sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
            or int32. The valid lengths of input sequences. Defaults to None.
            If `sequence_length` is not None, the inputs are treated as
            padded sequences. In each input sequence, elements whose time step
            index are not less than the valid length are treated as paddings.
        time_major (bool, optional): Whether the first dimension of the input means the
            time steps. Defaults to False.
        is_reverse (bool, optional): Indicate whether to calculate in the reverse
            order of input sequences. Defaults to False.
        **kwargs: Additional keyword arguments to pass to `forward` of the cell.

    Returns:
        outputs (Tensor|list|tuple): the output sequence. Tensor or nested
            structure of Tensors.
            If `time_major` is True, the shape of each tensor in outpus is
            `[time_steps, batch_size, hidden_size]`, else
            `[batch_size, time_steps, hidden_size]`.
        final_states (Tensor|list|tuple): final states. A (possibly nested structure of)
            tensor[s], representing the final state for RNN. It has the same
            structure of intial state. Each tensor in final states has the same
            shape and dtype as the corresponding tensor in initial states.

    Examples:

        .. code-block:: python

            import paddle
            paddle.disable_static()

            cell = paddle.nn.SimpleRNNCell(16, 32)

            inputs = paddle.rand((4, 23, 16))
            prev_h = paddle.randn((4, 32))
            outputs, final_states = paddle.nn.layer.rnn(cell, inputs, prev_h)

    """

103
    if in_dygraph_mode():
104 105 106 107 108 109 110
        return _rnn_dynamic_graph(
            cell,
            inputs,
            initial_states,
            sequence_length,
            time_major,
            is_reverse,
111
            **kwargs,
112 113 114 115 116 117 118 119 120
        )
    else:
        return _rnn_static_graph(
            cell,
            inputs,
            initial_states,
            sequence_length,
            time_major,
            is_reverse,
121
            **kwargs,
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
        )


class ArrayWrapper:
    def __init__(self, x):
        self.array = [x]

    def append(self, x):
        self.array.append(x)
        return self

    def __getitem__(self, item):
        return self.array.__getitem__(item)


def _maybe_copy(state, new_state, step_mask):
    """update rnn state or just pass the old state through"""
    new_state = paddle.tensor.math._multiply_with_axis(
        new_state, step_mask, axis=0
    ) + paddle.tensor.math._multiply_with_axis(state, (1 - step_mask), axis=0)
    return new_state


def _transpose_batch_time(x):
    perm = [1, 0] + list(range(2, len(x.shape)))
    return paddle.transpose(x, perm)


def _rnn_dynamic_graph(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
157
    **kwargs,
158 159
):
    time_step_index = 0 if time_major else 1
160
    flat_inputs = paddle.utils.flatten(inputs)
161 162 163 164 165 166 167 168
    time_steps = flat_inputs[0].shape[time_step_index]

    if initial_states is None:
        initial_states = cell.get_initial_states(
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )

    if not time_major:
169
        inputs = paddle.utils.map_structure(_transpose_batch_time, inputs)
170 171

    if sequence_length is not None:
172
        mask = paddle.static.nn.sequence_lod.sequence_mask(
173 174 175 176 177
            sequence_length, maxlen=time_steps, dtype=inputs.dtype
        )
        mask = paddle.transpose(mask, [1, 0])

    if is_reverse:
178 179 180
        inputs = paddle.utils.map_structure(
            lambda x: paddle.reverse(x, axis=[0]), inputs
        )
181 182 183 184 185 186 187 188 189
        mask = (
            paddle.reverse(mask, axis=[0])
            if sequence_length is not None
            else None
        )

    states = initial_states
    outputs = []
    for i in range(time_steps):
190
        step_inputs = paddle.utils.map_structure(lambda x: x[i], inputs)
191 192
        step_outputs, new_states = cell(step_inputs, states, **kwargs)
        if sequence_length is not None:
193
            new_states = paddle.utils.map_structure(
194 195 196 197
                partial(_maybe_copy, step_mask=mask[i]), states, new_states
            )
        states = new_states
        outputs = (
198
            paddle.utils.map_structure(lambda x: ArrayWrapper(x), step_outputs)
199
            if i == 0
200
            else paddle.utils.map_structure(
201 202 203 204
                lambda x, x_array: x_array.append(x), step_outputs, outputs
            )
        )

205
    final_outputs = paddle.utils.map_structure(
206 207 208 209
        lambda x: paddle.stack(x.array, axis=time_step_index), outputs
    )

    if is_reverse:
210
        final_outputs = paddle.utils.map_structure(
211 212 213 214 215 216 217 218 219 220 221 222 223 224
            lambda x: paddle.reverse(x, axis=time_step_index), final_outputs
        )

    final_states = new_states
    return final_outputs, final_states


def _rnn_static_graph(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
225
    **kwargs,
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
):
    check_type(inputs, 'inputs', (Variable, list, tuple), 'rnn')
    if isinstance(inputs, (list, tuple)):
        for i, input_x in enumerate(inputs):
            check_variable_and_dtype(
                input_x, 'inputs[' + str(i) + ']', ['float32', 'float64'], 'rnn'
            )
    check_type(
        initial_states,
        'initial_states',
        (Variable, list, tuple, type(None)),
        'rnn',
    )

    check_type(
        sequence_length, 'sequence_length', (Variable, type(None)), 'rnn'
    )

    def _switch_grad(x, stop=False):
        x.stop_gradient = stop
        return x

    if initial_states is None:
        initial_states = cell.get_initial_states(
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
252
    initial_states = paddle.utils.map_structure(_switch_grad, initial_states)
253 254

    if not time_major:
255
        inputs = paddle.utils.map_structure(_transpose_batch_time, inputs)
256

257
    max_seq_len = paddle.shape(paddle.utils.flatten(inputs)[0])[0]
258
    if sequence_length:
259
        mask = paddle.static.nn.sequence_lod.sequence_mask(
260 261
            sequence_length,
            maxlen=max_seq_len,
262
            dtype=paddle.utils.flatten(initial_states)[0].dtype,
263 264 265
        )
        mask = paddle.transpose(mask, [1, 0])
    if is_reverse:
266 267 268
        inputs = paddle.utils.map_structure(
            lambda x: paddle.reverse(x, axis=[0]), inputs
        )
269 270
        mask = paddle.reverse(mask, axis=[0]) if sequence_length else None

H
hong 已提交
271
    with paddle.fluid.framework.device_guard("cpu"):
272
        start_i = paddle.zeros([], dtype="int64")
H
hong 已提交
273 274 275 276
        end = max_seq_len

        end = paddle.cast(end, "int64")
        cond = start_i < end
277
    while_op = paddle.static.nn.control_flow.While(cond)
H
hong 已提交
278

279 280 281
    out_array = paddle.tensor.create_array(
        dtype=paddle.utils.flatten(inputs)[0].dtype
    )
H
hong 已提交
282

283
    init_array = paddle.utils.map_structure(
H
hong 已提交
284 285 286
        lambda x: paddle.tensor.create_array(dtype=x.dtype), initial_states
    )

287
    paddle.utils.map_structure(
H
hong 已提交
288 289 290 291 292 293 294 295
        lambda x, y: paddle.tensor.array_write(x, start_i, y),
        initial_states,
        init_array,
    )

    with while_op.block():
        step_in = inputs[start_i]
        # step_in = paddle.fluid.layers.Print( step_in, message="step in")
296
        pre_state = paddle.utils.map_structure(
H
hong 已提交
297 298 299 300
            lambda x: paddle.tensor.array_read(x, start_i), init_array
        )
        outputs, new_states = cell(step_in, pre_state, **kwargs)
        assert isinstance(outputs, paddle.fluid.framework.Variable)
301
        paddle.utils.assert_same_structure(new_states, pre_state)
302
        if sequence_length:
H
hong 已提交
303 304 305 306 307
            step_mask = paddle.unsqueeze(mask[start_i], 1)
            # new_states = map_structure(
            #     partial(_maybe_copy, step_mask=step_mask),
            #     pre_state, new_states
            # )
308
            new_states = paddle.utils.map_structure(
H
hong 已提交
309 310 311
                lambda x, y: (x * step_mask + y * (1.0 - step_mask)),
                new_states,
                pre_state,
312 313
            )

H
hong 已提交
314 315 316 317
        paddle.tensor.array_write(outputs, start_i, out_array)

        with paddle.fluid.framework.device_guard("cpu"):
            start_i = paddle.tensor.increment(x=start_i, value=1)
318
        paddle.utils.map_structure(
H
hong 已提交
319 320 321 322 323 324 325
            lambda x, y: paddle.tensor.array_write(x, start_i, y),
            new_states,
            init_array,
        )

        with paddle.fluid.framework.device_guard("cpu"):
            new_cond = paddle.tensor.less_than(start_i, end)
326
            paddle.assign(new_cond, cond)
H
hong 已提交
327

L
liu zhengxi 已提交
328
    out, _ = tensor_array_to_tensor(out_array, axis=0, use_stack=True)
329

330
    all_state = paddle.utils.map_structure(
L
liu zhengxi 已提交
331
        lambda x: tensor_array_to_tensor(x, axis=0, use_stack=True)[0],
H
hong 已提交
332 333 334
        init_array,
    )
    final_outputs = out
335
    final_states = paddle.utils.map_structure(lambda x: x[-1], all_state)
336 337

    if is_reverse:
338
        final_outputs = paddle.utils.map_structure(
339 340 341 342
            lambda x: paddle.reverse(x, axis=[0]), final_outputs
        )

    if not time_major:
343 344 345
        final_outputs = paddle.utils.map_structure(
            _transpose_batch_time, final_outputs
        )
346 347 348 349 350 351 352 353 354 355 356

    return (final_outputs, final_states)


def birnn(
    cell_fw,
    cell_bw,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
357
    **kwargs,
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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
):
    r"""
    birnn creates a bidirectional recurrent neural network specified by
    RNNCell `cell_fw` and `cell_bw`, which performs :code:`cell.call()`
    (for dygraph mode :code:`cell.forward`) repeatedly until reaches to
    the maximum length of `inputs` and then concat the outputs for both RNNs
    along the last axis.

    Parameters:
        cell_fw(RNNCellBase): An instance of `RNNCellBase`.
        cell_bw(RNNCellBase): An instance of `RNNCellBase`.
        inputs(Tensor): the input sequences.
            If time_major is True, the shape is
            `[time_steps, batch_size, input_size]`
            else the shape is `[batch_size, time_steps, input_size]`.
        initial_states(tuple, optional): A tuple of initial states of
            `cell_fw` and `cell_bw`.
            If not provided, `cell.get_initial_states` would be called to
            produce initial state for each cell. Defaults to None.
        sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
            or int32. The valid lengths of input sequences. Defaults to None.
            If `sequence_length` is not None, the inputs are treated as
            padded sequences. In each input sequence, elements whose time step
            index are not less than the valid length are treated as paddings.
        time_major (bool): Whether the first dimension of the input means the
            time steps. Defaults to False.
        **kwargs: Additional keyword arguments to pass to `forward` of each cell.

    Returns:
        outputs (Tensor): the outputs of the bidirectional RNN. It is the
            concatenation of the outputs from the forward RNN and backward
            RNN along the last axis.
            If time major is True, the shape is `[time_steps, batch_size, size]`,
            else the shape is `[batch_size, time_steps, size]`, where size is
            `cell_fw.hidden_size + cell_bw.hidden_size`.
        final_states (tuple): A tuple of the final states of the forward
            cell and backward cell.

    Examples:

        .. code-block:: python

            import paddle
            paddle.disable_static()

            cell_fw = paddle.nn.LSTMCell(16, 32)
            cell_bw = paddle.nn.LSTMCell(16, 32)

            inputs = paddle.rand((4, 23, 16))
            hf, cf = paddle.rand((4, 32)), paddle.rand((4, 32))
            hb, cb = paddle.rand((4, 32)), paddle.rand((4, 32))
            initial_states = ((hf, cf), (hb, cb))
            outputs, final_states = paddle.nn.layer.birnn(
                cell_fw, cell_bw, inputs, initial_states)

    """

    if initial_states is None:
        states_fw = cell_fw.get_initial_states(
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
        states_bw = cell_fw.get_initial_states(
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
    else:
        states_fw, states_bw = initial_states
    outputs_fw, states_fw = rnn(
        cell_fw,
        inputs,
        states_fw,
        sequence_length,
        time_major=time_major,
430
        **kwargs,
431 432 433 434 435 436 437 438 439
    )

    outputs_bw, states_bw = rnn(
        cell_bw,
        inputs,
        states_bw,
        sequence_length,
        time_major=time_major,
        is_reverse=True,
440
        **kwargs,
441 442
    )

443
    outputs = paddle.utils.map_structure(
444 445 446 447 448 449 450
        lambda x, y: paddle.concat([x, y], -1), outputs_fw, outputs_bw
    )

    final_states = (states_fw, states_bw)
    return outputs, final_states


F
Feiyu Chan 已提交
451 452 453 454 455
def split_states(states, bidirectional=False, state_components=1):
    r"""
    Split states of RNN network into possibly nested list or tuple of
    states of each RNN cells of the RNN network.

456
    Parameters:
F
Feiyu Chan 已提交
457 458
        states (Tensor|tuple|list): the concatenated states for RNN network.
            When `state_components` is 1, states in a Tensor with shape
459 460 461 462 463 464 465 466 467 468 469
            `(L*D, N, C)` where `L` is the number of layers of the RNN
            network, `D` is the number of directions of the RNN network(1
            for unidirectional RNNs and 2 for bidirectional RNNs), `N` is
            the batch size of the input to the RNN network, `C` is the
            hidden size of the RNN network.

            When `state_components` is larger than 1, `states` is a tuple of
            `state_components` Tensors that meet the requirements described
            above.

            For SimpleRNNs and GRUs, `state_components` is 1, and for LSTMs,
F
Feiyu Chan 已提交
470
            `state_components` is 2.
471
        bidirectional (bool): whether the state is of a bidirectional RNN
F
Feiyu Chan 已提交
472 473 474
            network. Defaults to False.
        state_components (int): the number of the components of the states. see
            `states` above. Defaults to 1.
475

F
Feiyu Chan 已提交
476
    Returns:
477 478 479
        A nested list or tuple of RNN cell states.
        If `bidirectional` is True, it can be indexed twice to get an RNN
        cell state. The first index indicates the layer, the second index
F
Feiyu Chan 已提交
480 481 482 483
        indicates the direction.
        If `bidirectional` is False, it can be indexed once to get an RNN
        cell state. The index indicates the layer.
        Note that if `state_components` is larger than 1, an RNN cell state
484
        can be indexed one more time to get a tensor of shape(N, C), where
F
Feiyu Chan 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        `N` is the batch size of the input to the RNN cell, and `C` is the
        hidden size of the RNN cell.
    """
    if state_components == 1:
        states = paddle.unstack(states)
        if not bidirectional:
            return states
        else:
            return list(zip(states[::2], states[1::2]))
    else:
        assert len(states) == state_components
        states = tuple([paddle.unstack(item) for item in states])
        if not bidirectional:
            return list(zip(*states))
        else:
            states = list(zip(*states))
            return list(zip(states[::2], states[1::2]))


def concat_states(states, bidirectional=False, state_components=1):
    r"""
506
    Concatenate a possibly nested list or tuple of RNN cell states into a
F
Feiyu Chan 已提交
507 508
    compact form.

509
    Parameters:
510 511 512 513
        states (list|tuple): a possibly nested list or tuple of RNN cell
            states.
            If `bidirectional` is True, it can be indexed twice to get an
            RNN cell state. The first index indicates the layer, the second
F
Feiyu Chan 已提交
514 515 516
            index indicates the direction.
            If `bidirectional` is False, it can be indexed once to get an RNN
            cell state. The index indicates the layer.
517 518 519 520 521
            Note that if `state_components` is larger than 1, an RNN cell
            state can be indexed one more time to get a tensor of shape(N, C),
            where `N` is the batch size of the input to the RNN cell, and
            `C` is the hidden size of the RNN cell.
        bidirectional (bool): whether the state is of a bidirectional RNN
F
Feiyu Chan 已提交
522 523 524
            network. Defaults to False.
        state_components (int): the number of the components of the states. see
            `states` above. Defaults to 1.
525

F
Feiyu Chan 已提交
526 527 528
    Returns:
        Concatenated states for RNN network.
        When `state_components` is 1, states in a Tensor with shape
529 530 531 532
        `(L\*D, N, C)` where `L` is the number of layers of the RNN
        network, `D` is the number of directions of the RNN network(1 for
        unidirectional RNNs and 2 for bidirectional RNNs), `N` is the batch
        size of the input to the RNN network, `C` is the hidden size of the
F
Feiyu Chan 已提交
533
        RNN network.
534

F
Feiyu Chan 已提交
535 536
    """
    if state_components == 1:
537
        return paddle.stack(paddle.utils.flatten(states))
F
Feiyu Chan 已提交
538
    else:
539
        states = paddle.utils.flatten(states)
F
Feiyu Chan 已提交
540 541 542
        componnets = []
        for i in range(state_components):
            componnets.append(states[i::state_components])
543
        return tuple([paddle.stack(item) for item in componnets])
F
Feiyu Chan 已提交
544 545 546 547 548 549 550 551 552


class RNNCellBase(Layer):
    r"""
    RNNCellBase is the base class for abstraction representing the calculations
    mapping the input and state to the output and new state. It is suitable to
    and mostly used in RNN.
    """

553 554 555
    def get_initial_states(
        self, batch_ref, shape=None, dtype=None, init_value=0.0, batch_dim_idx=0
    ):
F
Feiyu Chan 已提交
556 557 558
        r"""
        Generate initialized states according to provided shape, data type and
        value.
559 560

        Parameters:
561 562 563
            batch_ref (Tensor): A tensor, which shape would be used to
                determine the batch size, which is used to generate initial
                states. For `batch_ref`'s shape d, `d[batch_dim_idx]` is
F
Feiyu Chan 已提交
564
                treated as batch size.
565 566 567 568
            shape (list|tuple, optional): A (possibly nested structure of) shape[s],
                where a shape is a list/tuple of integer. `-1` (for batch size)
                will be automatically prepended if a shape does not starts with
                it. If None, property `state_shape` will be used. Defaults to
F
Feiyu Chan 已提交
569
                None.
570 571 572 573 574
            dtype (str|list|tuple, optional): A (possibly nested structure of)
                data type[s]. The structure must be same as that of `shape`,
                except when all tensors' in states has the same data type, a
                single data type can be used. If None and property `cell.state_shape`
                is not available, current default floating type of paddle is
F
Feiyu Chan 已提交
575
                used. Defaults to None.
576
            init_value (float, optional): A float value used to initialize states.
F
Feiyu Chan 已提交
577
                Defaults to 0.
578
            batch_dim_idx (int, optional): An integer indicating which
F
Feiyu Chan 已提交
579
                dimension of the of `batch_ref` represents batch. Defaults to 0.
580

F
Feiyu Chan 已提交
581
        Returns:
582
            init_states (Tensor|tuple|list): tensor of the provided shape and
F
Feiyu Chan 已提交
583 584 585 586
                dtype, or list of tensors that each satisfies the requirements,
                packed in the same structure as `shape` and `type` does.
        """
        # TODO: use inputs and batch_size
587
        batch_ref = paddle.utils.flatten(batch_ref)[0]
F
Feiyu Chan 已提交
588 589 590

        def _is_shape_sequence(seq):
            """For shape, list/tuple of integer is the finest-grained objection"""
591
            if isinstance(seq, (list, tuple)):
592 593 594
                if reduce(
                    lambda flag, x: isinstance(x, int) and flag, seq, True
                ):
F
Feiyu Chan 已提交
595 596 597 598
                    return False
            # TODO: Add check for the illegal
            if isinstance(seq, dict):
                return True
599
            return isinstance(seq, Sequence) and not isinstance(seq, str)
F
Feiyu Chan 已提交
600

601
        class Shape:
F
Feiyu Chan 已提交
602 603 604 605 606
            def __init__(self, shape):
                self.shape = shape if shape[0] == -1 else ([-1] + list(shape))

        # nested structure of shapes
        states_shapes = self.state_shape if shape is None else shape
607 608 609 610 611 612
        is_sequence_ori = paddle.utils.layers_utils.is_sequence
        paddle.utils.layers_utils.is_sequence = _is_shape_sequence
        states_shapes = paddle.utils.map_structure(
            lambda shape: Shape(shape), states_shapes
        )
        paddle.utils.layers_utils.is_sequence = is_sequence_ori
F
Feiyu Chan 已提交
613 614 615 616 617 618

        # nested structure of dtypes
        try:
            states_dtypes = self.state_dtype if dtype is None else dtype
        except NotImplementedError:
            states_dtypes = framework.get_default_dtype()
619 620 621 622 623
        if len(paddle.utils.flatten(states_dtypes)) == 1:
            dtype = paddle.utils.flatten(states_dtypes)[0]
            states_dtypes = paddle.utils.map_structure(
                lambda shape: dtype, states_shapes
            )
F
Feiyu Chan 已提交
624

625
        init_states = paddle.utils.map_structure(
626 627 628 629 630 631 632 633 634 635
            lambda shape, dtype: paddle.fluid.layers.fill_constant_batch_size_like(
                input=batch_ref,
                shape=shape.shape,
                dtype=dtype,
                value=init_value,
                input_dim_idx=batch_dim_idx,
            ),
            states_shapes,
            states_dtypes,
        )
F
Feiyu Chan 已提交
636 637 638 639 640 641 642
        return init_states

    @property
    def state_shape(self):
        r"""
        Abstract method (property).
        Used to initialize states.
643
        A (possiblely nested structure of) shape[s], where a shape is a
F
Feiyu Chan 已提交
644 645 646 647 648 649 650
        list/tuple of integers (-1 for batch size would be automatically
        inserted into a shape if shape is not started with it).
        Not necessary to be implemented if states are not initialized by
        `get_initial_states` or the `shape` argument is provided when using
        `get_initial_states`.
        """
        raise NotImplementedError(
651 652
            "Please add implementaion for `state_shape` in the used cell."
        )
F
Feiyu Chan 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665 666

    @property
    def state_dtype(self):
        r"""
        Abstract method (property).
        Used to initialize states.
        A (possiblely nested structure of) data types[s]. The structure must be
        same as that of `shape`, except when all tensors' in states has the same
        data type, a signle data type can be used.
        Not necessary to be implemented if states are not initialized
        by `get_initial_states` or the `dtype` argument is provided when using
        `get_initial_states`.
        """
        raise NotImplementedError(
667 668
            "Please add implementaion for `state_dtype` in the used cell."
        )
F
Feiyu Chan 已提交
669 670 671 672


class SimpleRNNCell(RNNCellBase):
    r"""
673
    Elman RNN (SimpleRNN) cell. Given the inputs and previous states, it
F
Feiyu Chan 已提交
674 675 676 677 678
    computes the outputs and updates states.

    The formula used is as follows:

    .. math::
679
        h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh})
680

F
Feiyu Chan 已提交
681
        y_{t} & = h_{t}
682

683
    where :math:`act` is for :attr:`activation`.
F
Feiyu Chan 已提交
684

685
    Please refer to `Finding Structure in Time
F
Feiyu Chan 已提交
686
    <https://crl.ucsd.edu/~elman/Papers/fsit.pdf>`_ for more details.
687

688
    Parameters:
F
Feiyu Chan 已提交
689 690
        input_size (int): The input size.
        hidden_size (int): The hidden size.
691
        activation (str, optional): The activation in the SimpleRNN cell.
F
Feiyu Chan 已提交
692
            It can be `tanh` or `relu`. Defaults to `tanh`.
693
        weight_ih_attr (ParamAttr, optional): The parameter attribute for
694
            :math:`weight_ih`. Default: None.
695
        weight_hh_attr(ParamAttr, optional): The parameter attribute for
696
            :math:`weight_hh`. Default: None.
697
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
698
            :math:`bias_ih`. Default: None.
699
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
700
            :math:`bias_hh`. Default: None.
701
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
702 703
            None). For more information, please refer to :ref:`api_guide_Name`.

704 705 706 707 708
    Variables:
        - **weight_ih** (Parameter): shape (hidden_size, input_size), input to hidden weight, corresponding to :math:`W_{ih}` in the formula.
        - **weight_hh** (Parameter): shape (hidden_size, hidden_size), hidden to hidden weight, corresponding to :math:`W_{hh}` in the formula.
        - **bias_ih** (Parameter): shape (hidden_size, ), input to hidden bias, corresponding to :math:`b_{ih}` in the formula.
        - **bias_hh** (Parameter): shape (hidden_size, ), hidden to hidden bias, corresponding to :math:`b_{hh}` in the formula.
709

F
Feiyu Chan 已提交
710
    Inputs:
711 712
        - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_{t}` in the formula.
        - **states** (Tensor, optional): shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.
F
Feiyu Chan 已提交
713 714

    Returns:
715 716
        - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
        - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula.
717

F
Feiyu Chan 已提交
718
    Notes:
719
        All the weights and bias are initialized with `Uniform(-std, std)` by default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`.
F
Feiyu Chan 已提交
720 721 722 723 724 725 726 727 728 729 730 731

    Examples:

        .. code-block:: python

            import paddle

            x = paddle.randn((4, 16))
            prev_h = paddle.randn((4, 32))

            cell = paddle.nn.SimpleRNNCell(16, 32)
            y, h = cell(x, prev_h)
732 733 734
            print(y.shape)

            #[4,32]
F
Feiyu Chan 已提交
735 736 737

    """

738 739 740 741 742 743 744 745 746 747 748
    def __init__(
        self,
        input_size,
        hidden_size,
        activation="tanh",
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
749
        super().__init__()
750 751
        if hidden_size <= 0:
            raise ValueError(
752 753 754 755
                "hidden_size of {} must be greater than 0, but now equals to {}".format(
                    self.__class__.__name__, hidden_size
                )
            )
F
Feiyu Chan 已提交
756 757 758 759
        std = 1.0 / math.sqrt(hidden_size)
        self.weight_ih = self.create_parameter(
            (hidden_size, input_size),
            weight_ih_attr,
760 761
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
762 763 764
        self.weight_hh = self.create_parameter(
            (hidden_size, hidden_size),
            weight_hh_attr,
765 766
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
767
        self.bias_ih = self.create_parameter(
768
            (hidden_size,),
F
Feiyu Chan 已提交
769 770
            bias_ih_attr,
            is_bias=True,
771 772
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
773
        self.bias_hh = self.create_parameter(
774
            (hidden_size,),
F
Feiyu Chan 已提交
775 776
            bias_hh_attr,
            is_bias=True,
777 778
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
779 780 781 782 783 784

        self.input_size = input_size
        self.hidden_size = hidden_size
        if activation not in ["tanh", "relu"]:
            raise ValueError(
                "activation for SimpleRNNCell should be tanh or relu, "
785 786
                "but get {}".format(activation)
            )
F
Feiyu Chan 已提交
787
        self.activation = activation
788
        self._activation_fn = paddle.tanh if activation == "tanh" else F.relu
F
Feiyu Chan 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804

    def forward(self, inputs, states=None):
        if states is None:
            states = self.get_initial_states(inputs, self.state_shape)
        pre_h = states
        i2h = paddle.matmul(inputs, self.weight_ih, transpose_y=True)
        if self.bias_ih is not None:
            i2h += self.bias_ih
        h2h = paddle.matmul(pre_h, self.weight_hh, transpose_y=True)
        if self.bias_hh is not None:
            h2h += self.bias_hh
        h = self._activation_fn(i2h + h2h)
        return h, h

    @property
    def state_shape(self):
805
        return (self.hidden_size,)
F
Feiyu Chan 已提交
806

807 808
    def extra_repr(self):
        s = '{input_size}, {hidden_size}'
809
        if self.activation != "tanh":
810 811 812
            s += ', activation={activation}'
        return s.format(**self.__dict__)

F
Feiyu Chan 已提交
813 814 815

class LSTMCell(RNNCellBase):
    r"""
816
    Long-Short Term Memory(LSTM) RNN cell. Given the inputs and previous states,
F
Feiyu Chan 已提交
817 818 819 820 821 822
    it computes the outputs and updates states.

    The formula used is as follows:

    .. math::
        i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi})
823

F
Feiyu Chan 已提交
824
        f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf})
825

F
Feiyu Chan 已提交
826
        o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho})
827 828 829 830 831 832 833

        \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg})

        c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t}

        h_{t} & = o_{t} * \tanh(c_{t})

F
Feiyu Chan 已提交
834 835
        y_{t} & = h_{t}

836
    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise
F
Feiyu Chan 已提交
837 838 839 840 841
    multiplication operator.

    Please refer to `An Empirical Exploration of Recurrent Network Architectures
    <http://proceedings.mlr.press/v37/jozefowicz15.pdf>`_ for more details.

842
    Parameters:
F
Feiyu Chan 已提交
843 844
        input_size (int): The input size.
        hidden_size (int): The hidden size.
845
        weight_ih_attr(ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
846
            `weight_ih`. Default: None.
847
        weight_hh_attr(ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
848
            `weight_hh`. Default: None.
849
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
850
            `bias_ih`. Default: None.
851
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
852
            `bias_hh`. Default: None.
853
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
854 855
            None). For more information, please refer to :ref:`api_guide_Name`.

856 857 858 859 860
    Variables:
        - **weight_ih** (Parameter): shape (4 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ii}, W_{if}, W_{ig}, W_{io}` in the formula.
        - **weight_hh** (Parameter): shape (4 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hi}, W_{hf}, W_{hg}, W_{ho}` in the formula.
        - **bias_ih** (Parameter): shape (4 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ii}, b_{if}, b_{ig}, b_{io}` in the formula.
        - **bias_hh** (Parameter): shape (4 * hidden_size, ), hidden to hidden bias, swhich corresponds to the concatenation of :math:`b_{hi}, b_{hf}, b_{hg}, b_{ho}` in the formula.
F
Feiyu Chan 已提交
861 862

    Inputs:
863
        - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_t` in the formula.
864
        - **states** (list|tuple, optional): a list/tuple of two tensors, each of shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}, c_{t-1}` in the formula. When states is None, zero state is used. Defaults to None.
F
Feiyu Chan 已提交
865 866

    Returns:
867 868
        - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
        - **states** (tuple): a tuple of two tensors, each of shape `[batch_size, hidden_size]`, the new hidden states, corresponding to :math:`h_{t}, c_{t}` in the formula.
F
Feiyu Chan 已提交
869 870

    Notes:
871 872
        All the weights and bias are initialized with `Uniform(-std, std)` by
        default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more
873
        information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`.
F
Feiyu Chan 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887

    Examples:

        .. code-block:: python

            import paddle

            x = paddle.randn((4, 16))
            prev_h = paddle.randn((4, 32))
            prev_c = paddle.randn((4, 32))

            cell = paddle.nn.LSTMCell(16, 32)
            y, (h, c) = cell(x, (prev_h, prev_c))

888 889 890 891 892 893 894 895
            print(y.shape)
            print(h.shape)
            print(c.shape)

            #[4,32]
            #[4,32]
            #[4,32]

F
Feiyu Chan 已提交
896 897
    """

898 899 900 901 902 903 904 905 906 907
    def __init__(
        self,
        input_size,
        hidden_size,
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
908
        super().__init__()
909 910
        if hidden_size <= 0:
            raise ValueError(
911 912 913 914
                "hidden_size of {} must be greater than 0, but now equals to {}".format(
                    self.__class__.__name__, hidden_size
                )
            )
F
Feiyu Chan 已提交
915 916 917 918
        std = 1.0 / math.sqrt(hidden_size)
        self.weight_ih = self.create_parameter(
            (4 * hidden_size, input_size),
            weight_ih_attr,
919 920
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
921 922 923
        self.weight_hh = self.create_parameter(
            (4 * hidden_size, hidden_size),
            weight_hh_attr,
924 925
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
926
        self.bias_ih = self.create_parameter(
927
            (4 * hidden_size,),
F
Feiyu Chan 已提交
928 929
            bias_ih_attr,
            is_bias=True,
930 931
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
932
        self.bias_hh = self.create_parameter(
933
            (4 * hidden_size,),
F
Feiyu Chan 已提交
934 935
            bias_hh_attr,
            is_bias=True,
936 937
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

        self.hidden_size = hidden_size
        self.input_size = input_size
        self._gate_activation = F.sigmoid
        self._activation = paddle.tanh

    def forward(self, inputs, states=None):
        if states is None:
            states = self.get_initial_states(inputs, self.state_shape)
        pre_hidden, pre_cell = states
        gates = paddle.matmul(inputs, self.weight_ih, transpose_y=True)
        if self.bias_ih is not None:
            gates = gates + self.bias_ih
        gates += paddle.matmul(pre_hidden, self.weight_hh, transpose_y=True)
        if self.bias_hh is not None:
            gates = gates + self.bias_hh

        chunked_gates = paddle.split(gates, num_or_sections=4, axis=-1)

        i = self._gate_activation(chunked_gates[0])
        f = self._gate_activation(chunked_gates[1])
        o = self._gate_activation(chunked_gates[3])
        c = f * pre_cell + i * self._activation(chunked_gates[2])
        h = o * self._activation(c)

        return h, (h, c)

    @property
    def state_shape(self):
        r"""
968 969 970
        The `state_shape` of LSTMCell is a tuple with two shapes:
        `((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
        automatically inserted into shape). These two shapes correspond
F
Feiyu Chan 已提交
971 972
        to :math:`h_{t-1}` and :math:`c_{t-1}` separately.
        """
973
        return ((self.hidden_size,), (self.hidden_size,))
F
Feiyu Chan 已提交
974

975 976 977
    def extra_repr(self):
        return '{input_size}, {hidden_size}'.format(**self.__dict__)

F
Feiyu Chan 已提交
978 979 980

class GRUCell(RNNCellBase):
    r"""
981
    Gated Recurrent Unit (GRU) RNN cell. Given the inputs and previous states,
F
Feiyu Chan 已提交
982 983 984 985
    it computes the outputs and updates states.

    The formula for GRU used is as follows:

986
    ..  math::
F
Feiyu Chan 已提交
987

988
        r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr})
989

990
        z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz})
991

992
        \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc}))
993 994 995

        h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t}

F
Feiyu Chan 已提交
996
        y_{t} & = h_{t}
997 998

    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise
F
Feiyu Chan 已提交
999 1000 1001 1002 1003 1004
    multiplication operator.

    Please refer to `An Empirical Exploration of Recurrent Network Architectures
    <http://proceedings.mlr.press/v37/jozefowicz15.pdf>`_ for more details.

    Parameters:
1005
        input_size (int): The input size.
F
Feiyu Chan 已提交
1006
        hidden_size (int): The hidden size.
1007
        weight_ih_attr(ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1008
            `weight_ih`. Default: None.
1009
        weight_hh_attr(ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1010
            `weight_hh`. Default: None.
1011
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1012
            `bias_ih`. Default: None.
1013
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1014
            `bias_hh`. Default: None.
1015
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
1016 1017
            None). For more information, please refer to :ref:`api_guide_Name`.

1018 1019 1020 1021 1022
    Variables:
        - **weight_ih** (Parameter): shape (3 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ir}, W_{iz}, W_{ic}` in the formula.
        - **weight_hh** (Parameter): shape (3 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hr}, W_{hz}, W_{hc}` in the formula.
        - **bias_ih** (Parameter): shape (3 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ir}, b_{iz}, b_{ic}` in the formula.
        - **bias_hh** (Parameter): shape (3 * hidden_size, ), hidden to hidden bias, swhich corresponds to the concatenation of :math:`b_{hr}, b_{hz}, b_{hc}` in the formula.
F
Feiyu Chan 已提交
1023 1024

    Inputs:
1025 1026
        - **inputs** (Tensor): A tensor with shape `[batch_size, input_size]`, corresponding to :math:`x_t` in the formula.
        - **states** (Tensor): A tensor with shape `[batch_size, hidden_size]`, corresponding to :math:`h_{t-1}` in the formula.
F
Feiyu Chan 已提交
1027 1028

    Returns:
1029 1030
        - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula.
        - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula.
1031

F
Feiyu Chan 已提交
1032
    Notes:
1033 1034
        All the weights and bias are initialized with `Uniform(-std, std)` by
        default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more
1035
        information about parameter initialization, please refer to s:ref:`api_fluid_ParamAttr`.
F
Feiyu Chan 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

    Examples:

        .. code-block:: python

            import paddle

            x = paddle.randn((4, 16))
            prev_h = paddle.randn((4, 32))

            cell = paddle.nn.GRUCell(16, 32)
            y, h = cell(x, prev_h)

1049 1050 1051 1052 1053 1054
            print(y.shape)
            print(h.shape)

            #[4,32]
            #[4,32]

F
Feiyu Chan 已提交
1055 1056
    """

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    def __init__(
        self,
        input_size,
        hidden_size,
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
1067
        super().__init__()
1068 1069
        if hidden_size <= 0:
            raise ValueError(
1070 1071 1072 1073
                "hidden_size of {} must be greater than 0, but now equals to {}".format(
                    self.__class__.__name__, hidden_size
                )
            )
F
Feiyu Chan 已提交
1074 1075 1076 1077
        std = 1.0 / math.sqrt(hidden_size)
        self.weight_ih = self.create_parameter(
            (3 * hidden_size, input_size),
            weight_ih_attr,
1078 1079
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
1080 1081 1082
        self.weight_hh = self.create_parameter(
            (3 * hidden_size, hidden_size),
            weight_hh_attr,
1083 1084
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
1085
        self.bias_ih = self.create_parameter(
1086
            (3 * hidden_size,),
F
Feiyu Chan 已提交
1087 1088
            bias_ih_attr,
            is_bias=True,
1089 1090
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
1091
        self.bias_hh = self.create_parameter(
1092
            (3 * hidden_size,),
F
Feiyu Chan 已提交
1093 1094
            bias_hh_attr,
            is_bias=True,
1095 1096
            default_initializer=I.Uniform(-std, std),
        )
F
Feiyu Chan 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

        self.hidden_size = hidden_size
        self.input_size = input_size
        self._gate_activation = F.sigmoid
        self._activation = paddle.tanh

    def forward(self, inputs, states=None):
        if states is None:
            states = self.get_initial_states(inputs, self.state_shape)

        pre_hidden = states
        x_gates = paddle.matmul(inputs, self.weight_ih, transpose_y=True)
        if self.bias_ih is not None:
            x_gates = x_gates + self.bias_ih
        h_gates = paddle.matmul(pre_hidden, self.weight_hh, transpose_y=True)
        if self.bias_hh is not None:
            h_gates = h_gates + self.bias_hh

        x_r, x_z, x_c = paddle.split(x_gates, num_or_sections=3, axis=1)
        h_r, h_z, h_c = paddle.split(h_gates, num_or_sections=3, axis=1)

        r = self._gate_activation(x_r + h_r)
        z = self._gate_activation(x_z + h_z)
        c = self._activation(x_c + r * h_c)  # apply reset gate after mm
        h = (pre_hidden - c) * z + c

        return h, h

    @property
    def state_shape(self):
        r"""
        The `state_shape` of GRUCell is a shape `[hidden_size]` (-1 for batch
        size would be automatically inserted into shape). The shape corresponds
        to the shape of :math:`h_{t-1}`.
        """
1132
        return (self.hidden_size,)
F
Feiyu Chan 已提交
1133

1134 1135 1136
    def extra_repr(self):
        return '{input_size}, {hidden_size}'.format(**self.__dict__)

F
Feiyu Chan 已提交
1137 1138 1139

class RNN(Layer):
    r"""
1140 1141
    Wrapper for RNN, which creates a recurrent neural network with an RNN cell.
    It performs :code:`cell.forward()` repeatedly until reaches to the maximum
F
Feiyu Chan 已提交
1142 1143
    length of `inputs`.

1144
    Parameters:
F
Feiyu Chan 已提交
1145 1146 1147 1148 1149 1150 1151
        cell(RNNCellBase): An instance of `RNNCellBase`.
        is_reverse (bool, optional): Indicate whether to calculate in the reverse
            order of input sequences. Defaults to False.
        time_major (bool): Whether the first dimension of the input means the
            time steps. Defaults to False.

    Inputs:
1152 1153 1154
        - **inputs** (Tensor): A (possibly nested structure of) tensor[s]. The input sequences. If time major is False, the shape is `[batch_size, time_steps, input_size]`. If time major is True, the shape is `[time_steps, batch_size, input_size]` where `input_size` is the input size of the cell.
        - **initial_states** (Tensor|list|tuple, optional): Tensor of a possibly nested structure of tensors, representing the initial state for the rnn cell. If not provided, `cell.get_initial_states` would be called to produce the initial states. Defaults to None.
        - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None.If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.
1155
        - **kwargs**: Additional keyword arguments to pass to `forward` of the cell.
F
Feiyu Chan 已提交
1156 1157

    Returns:
1158 1159
        - **outputs** (Tensor|list|tuple): the output sequences. If `time_major` is True, the shape is `[time_steps, batch_size, hidden_size]`, else `[batch_size, time_steps, hidden_size]`.
        - **final_states** (Tensor|list|tuple): final states of the cell. Tensor or a possibly nested structure of tensors which has the same structure with intial state. Each tensor in final states has the same shape and dtype as the corresponding tensor in initial states.
1160

F
Feiyu Chan 已提交
1161
    Notes:
V
Vegetable dog 已提交
1162
        This class is a low-level API for wrapping rnn cell into a RNN network.
1163 1164
        Users should take care of the state of the cell. If `initial_states` is
        passed to the `forward` method, make sure that it satisfies the
F
Feiyu Chan 已提交
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        requirements of the cell.

    Examples:

        .. code-block:: python

            import paddle

            inputs = paddle.rand((4, 23, 16))
            prev_h = paddle.randn((4, 32))

            cell = paddle.nn.SimpleRNNCell(16, 32)
            rnn = paddle.nn.RNN(cell)
            outputs, final_states = rnn(inputs, prev_h)

1180 1181 1182 1183 1184 1185
            print(outputs.shape)
            print(final_states.shape)

            #[4,23,32]
            #[4,32]

F
Feiyu Chan 已提交
1186 1187 1188
    """

    def __init__(self, cell, is_reverse=False, time_major=False):
1189
        super().__init__()
F
Feiyu Chan 已提交
1190 1191 1192 1193 1194 1195 1196
        self.cell = cell
        if not hasattr(self.cell, "call"):
            # for non-dygraph mode, `rnn` api uses cell.call
            self.cell.call = self.cell.forward
        self.is_reverse = is_reverse
        self.time_major = time_major

1197 1198 1199
    def forward(
        self, inputs, initial_states=None, sequence_length=None, **kwargs
    ):
1200
        final_outputs, final_states = rnn(
1201 1202 1203 1204 1205 1206
            self.cell,
            inputs,
            initial_states=initial_states,
            sequence_length=sequence_length,
            time_major=self.time_major,
            is_reverse=self.is_reverse,
1207
            **kwargs,
1208
        )
F
Feiyu Chan 已提交
1209 1210 1211 1212 1213
        return final_outputs, final_states


class BiRNN(Layer):
    r"""
1214 1215 1216
    Wrapper for bidirectional RNN, which builds a bidiretional RNN given the
    forward rnn cell and backward rnn cell. A BiRNN applies forward RNN and
    backward RNN with coresponding cells separately and concats the outputs
F
Feiyu Chan 已提交
1217 1218
    along the last axis.

1219
    Parameters:
F
Feiyu Chan 已提交
1220 1221
        cell_fw (RNNCellBase): A RNNCellBase instance used for forward RNN.
        cell_bw (RNNCellBase): A RNNCellBase instance used for backward RNN.
1222
        time_major (bool, optional): Whether the first dimension of the input means the
F
Feiyu Chan 已提交
1223 1224 1225
            time steps. Defaults to False.

    Inputs:
1226 1227 1228 1229
        - **inputs** (Tensor): the input sequences of both RNN. If time_major is True, the shape of is `[time_steps, batch_size, input_size]`, else the shape is `[batch_size, time_steps, input_size]`, where input_size is the input size of both cells.
        - **initial_states** (list|tuple, optional): A tuple/list of the initial states of the forward cell and backward cell. Defaults to None. If not provided, `cell.get_initial_states` would be called to produce the initial states for each cell. Defaults to None.
        - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.
        - **kwargs**: Additional keyword arguments. Arguments passed to `forward` for each cell.
F
Feiyu Chan 已提交
1230 1231

    Outputs:
1232
        - **outputs** (Tensor): the outputs of the bidirectional RNN. It is the concatenation of the outputs from the forward RNN and backward RNN along the last axis. If time major is True, the shape is `[time_steps, batch_size, size]`, else the shape is `[batch_size, time_steps, size]`, where size is `cell_fw.hidden_size + cell_bw.hidden_size`.
1233
        - **final_states** (tuple): A tuple of the final states of the forward cell and backward cell.
F
Feiyu Chan 已提交
1234 1235

    Notes:
1236 1237 1238
        This class is a low level API for wrapping rnn cells into a BiRNN
        network. Users should take care of the states of the cells.
        If `initial_states` is passed to the `forward` method, make sure that
F
Feiyu Chan 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        it satisfies the requirements of the cells.

    Examples:

        .. code-block:: python

            import paddle

            cell_fw = paddle.nn.LSTMCell(16, 32)
            cell_bw = paddle.nn.LSTMCell(16, 32)
            rnn = paddle.nn.BiRNN(cell_fw, cell_bw)

            inputs = paddle.rand((2, 23, 16))
            outputs, final_states = rnn(inputs)

1254 1255 1256 1257 1258 1259
            print(outputs.shape)
            print(final_states[0][0].shape,len(final_states),len(final_states[0]))

            #[4,23,64]
            #[2,32] 2 2

F
Feiyu Chan 已提交
1260 1261 1262
    """

    def __init__(self, cell_fw, cell_bw, time_major=False):
1263
        super().__init__()
F
Feiyu Chan 已提交
1264 1265 1266
        self.cell_fw = cell_fw
        self.cell_bw = cell_bw
        if cell_fw.input_size != cell_bw.input_size:
1267 1268 1269 1270 1271 1272
            raise ValueError(
                "input size of forward cell({}) does not equals"
                "that of backward cell({})".format(
                    cell_fw.input_size, cell_bw.input_size
                )
            )
F
Feiyu Chan 已提交
1273 1274 1275 1276 1277 1278
        for cell in [self.cell_fw, self.cell_bw]:
            if not hasattr(cell, "call"):
                # for non-dygraph mode, `rnn` api uses cell.call
                cell.call = cell.forward
        self.time_major = time_major

1279 1280 1281
    def forward(
        self, inputs, initial_states=None, sequence_length=None, **kwargs
    ):
F
Feiyu Chan 已提交
1282
        if isinstance(initial_states, (list, tuple)):
1283 1284 1285
            assert (
                len(initial_states) == 2
            ), "length of initial_states should be 2 when it is a list/tuple"
F
Feiyu Chan 已提交
1286

1287
        outputs, final_states = birnn(
1288 1289 1290 1291 1292 1293
            self.cell_fw,
            self.cell_bw,
            inputs,
            initial_states,
            sequence_length,
            self.time_major,
1294
            **kwargs,
1295
        )
F
Feiyu Chan 已提交
1296 1297 1298
        return outputs, final_states


1299
class RNNBase(LayerList):
F
Feiyu Chan 已提交
1300
    r"""
1301 1302
    RNNBase class for RNN networks. It provides `forward`, `flatten_parameters`
    and other common methods for SimpleRNN, LSTM and GRU.
F
Feiyu Chan 已提交
1303 1304
    """

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    def __init__(
        self,
        mode,
        input_size,
        hidden_size,
        num_layers=1,
        direction="forward",
        time_major=False,
        dropout=0.0,
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
    ):
1319
        super().__init__()
1320
        bidirectional_list = ["bidirectional", "bidirect"]
1321 1322 1323 1324
        self.mode = mode
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.dropout = dropout
1325
        self.num_directions = 2 if direction in bidirectional_list else 1
1326 1327 1328 1329 1330 1331 1332 1333
        self.time_major = time_major
        self.num_layers = num_layers
        self.state_components = 2 if mode == "LSTM" else 1

        kwargs = {
            "weight_ih_attr": weight_ih_attr,
            "weight_hh_attr": weight_hh_attr,
            "bias_ih_attr": bias_ih_attr,
1334
            "bias_hh_attr": bias_hh_attr,
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        }

        if mode == "LSTM":
            rnn_cls = LSTMCell
        elif mode == "GRU":
            rnn_cls = GRUCell
        else:
            rnn_cls = SimpleRNNCell
            kwargs["activation"] = self.activation

1345 1346
        if direction in ["forward"]:
            is_reverse = False
1347 1348 1349 1350 1351
            cell = rnn_cls(input_size, hidden_size, **kwargs)
            self.append(RNN(cell, is_reverse, time_major))
            for i in range(1, num_layers):
                cell = rnn_cls(hidden_size, hidden_size, **kwargs)
                self.append(RNN(cell, is_reverse, time_major))
1352
        elif direction in bidirectional_list:
1353 1354 1355 1356 1357 1358 1359 1360 1361
            cell_fw = rnn_cls(input_size, hidden_size, **kwargs)
            cell_bw = rnn_cls(input_size, hidden_size, **kwargs)
            self.append(BiRNN(cell_fw, cell_bw, time_major))
            for i in range(1, num_layers):
                cell_fw = rnn_cls(2 * hidden_size, hidden_size, **kwargs)
                cell_bw = rnn_cls(2 * hidden_size, hidden_size, **kwargs)
                self.append(BiRNN(cell_fw, cell_bw, time_major))
        else:
            raise ValueError(
1362
                "direction should be forward or bidirect (or bidirectional), "
1363 1364
                "received direction = {}".format(direction)
            )
1365

1366
        self.could_use_cudnn = True
1367
        self.could_use_cudnn &= len(self.parameters()) == num_layers * 4 * (
1368 1369
            2 if direction in bidirectional_list else 1
        )
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

        # Expose params as RNN's attribute, which can make it compatible when
        # replacing small ops composed rnn with cpp rnn kernel.
        # Moreover, `jit.to_static` assumes params are added by current layer
        # and wouldn't include sublayer's params in current layer, which also
        # requires these params are added to current layer for `jit.save`.
        param_names = []
        for layer in range(self.num_layers):
            for direction in range(self.num_directions):
                suffix = '_reverse' if direction == 1 else ''
                param_names.extend(['weight_ih_l{}{}', 'weight_hh_l{}{}'])
1381
                if bias_ih_attr is not False:
1382
                    param_names.append('bias_ih_l{}{}')
1383
                if bias_hh_attr is not False:
1384
                    param_names.append('bias_hh_l{}{}')
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
                param_names = [x.format(layer, suffix) for x in param_names]
        for name, param in zip(param_names, self.parameters()):
            setattr(self, name, param)

        self.flatten_parameters()

    def flatten_parameters(self):
        """
        Resets parameter data pointer to address in continuous memory block for
        cudnn usage.
        """
        if self.could_use_cudnn:
            # layer.parameters() is depth first and ordered
            # for i in layer: for j in direct: w_ih, w_hh, b_ih, b_hh
            # need to reorganize to cudnn param layout:
            # all bias following all weights
            params = self.parameters(include_sublayers=False)
            shape = [np.prod(param.shape) for param in params]
            self._all_weights = [None] * len(params)
            for i, param in enumerate(params):
1405 1406 1407 1408 1409
                offset = (
                    0
                    if i % 4 < 2
                    else (2 * self.num_layers * self.num_directions)
                )
1410 1411 1412 1413 1414 1415 1416
                layer_idx = i // 4
                self._all_weights[offset + layer_idx * 2 + i % 2] = param
            # Wrap using a list to avoid registed into params and saving, maybe
            # need a better way to handle this later. Use `create_parameter` to
            # add both to main_program and startup_program for static-graph.
            # Use Constant initializer to avoid make effect on random generator.
            self._flat_weight = [
1417 1418 1419 1420 1421
                self.create_parameter(
                    shape=[np.sum(shape)],
                    dtype=params[0].dtype,
                    default_initializer=I.Constant(0.0),
                )
1422 1423 1424 1425
            ]
            # dropout state may also can be hided and avoid saving
            # should dropout state be persistable for static-graph
            self._dropout_state = self.create_variable(
1426 1427
                dtype=core.VarDesc.VarType.UINT8,
                name=f"dropout_state{NON_PERSISTABLE_VAR_NAME_SUFFIX}",
1428
            )
Z
zhiboniu 已提交
1429
            if in_dynamic_mode():
1430
                with paddle.no_grad():
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
                    _legacy_C_ops.coalesce_tensor(
                        self._all_weights,
                        self._all_weights,
                        self._flat_weight[0],
                        "copy_data",
                        True,
                        "use_align",
                        False,
                        "dtype",
                        params[0].dtype,
                    )
1442
                    return
1443
            # for static-graph, append coalesce_tensor into startup program
1444 1445 1446
            with program_guard(
                default_startup_program(), default_startup_program()
            ):
Z
zhiboniu 已提交
1447
                with paddle.no_grad():
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
                    self._helper.append_op(
                        type="coalesce_tensor",
                        inputs={"Input": self._all_weights},
                        outputs={
                            "Output": self._all_weights,
                            "FusedOutput": self._flat_weight,
                        },
                        attrs={
                            "copy_data": True,
                            "use_align": False,
                            "dtype": params[0].dtype,
                        },
                    )
1461 1462 1463 1464 1465

    def _cudnn_impl(self, inputs, initial_states, sequence_length):
        if not self.time_major:
            inputs = paddle.tensor.transpose(inputs, [1, 0, 2])

Y
YuanRisheng 已提交
1466 1467
        if in_dygraph_mode():
            out, _, state = _C_ops.rnn(
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
                inputs,
                initial_states,
                self._all_weights,
                sequence_length,
                self._dropout_state,
                self.dropout,
                self.num_directions == 2,
                self.input_size,
                self.hidden_size,
                self.num_layers,
                self.mode,
                0,
                not self.training,
            )
Y
YuanRisheng 已提交
1482
        elif in_dynamic_mode():
1483
            _, _, out, state = _legacy_C_ops.rnn(
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
                inputs,
                initial_states,
                self._all_weights,
                sequence_length,
                self._dropout_state,
                self.state_components,
                'dropout_prob',
                self.dropout,
                'is_bidirec',
                self.num_directions == 2,
                'input_size',
                self.input_size,
                'hidden_size',
                self.hidden_size,
                'num_layers',
                self.num_layers,
                'mode',
                self.mode,
                'is_test',
                not self.training,
            )
1505 1506 1507 1508 1509 1510 1511
        else:
            out = self._helper.create_variable_for_type_inference(inputs.dtype)
            state = [
                self._helper.create_variable_for_type_inference(inputs.dtype)
                for i in range(self.state_components)
            ]
            reserve = self._helper.create_variable_for_type_inference(
1512 1513
                dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
            )
1514 1515 1516 1517 1518

            inputs = {
                'Input': inputs,
                'WeightList': self._all_weights,
                'PreState': initial_states,
1519
                'SequenceLength': sequence_length,
1520 1521 1522 1523 1524 1525 1526 1527
            }
            attrs = {
                'dropout_prob': self.dropout,
                'is_bidirec': self.num_directions == 2,
                'input_size': self.input_size,
                'hidden_size': self.hidden_size,
                'num_layers': self.num_layers,
                'mode': self.mode,
1528
                'is_test': not self.training,
1529 1530 1531 1532 1533 1534 1535 1536 1537
            }

            outputs = {
                'Out': out,
                'State': state,
                'Reserve': reserve,
                'DropoutState': self._dropout_state,
            }

1538 1539 1540
            self._helper.append_op(
                type="rnn", inputs=inputs, outputs=outputs, attrs=attrs
            )
1541

1542 1543 1544 1545 1546
        out = (
            paddle.tensor.transpose(out, [1, 0, 2])
            if not self.time_major
            else out
        )
G
Guo Sheng 已提交
1547
        return out, tuple(state) if len(state) > 1 else state[0]
1548

F
Feiyu Chan 已提交
1549 1550 1551 1552
    def forward(self, inputs, initial_states=None, sequence_length=None):
        batch_index = 1 if self.time_major else 0
        dtype = inputs.dtype
        if initial_states is None:
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
            state_shape = (
                self.num_layers * self.num_directions,
                -1,
                self.hidden_size,
            )
            initial_states = tuple(
                [
                    paddle.fluid.layers.fill_constant_batch_size_like(
                        inputs, state_shape, dtype, 0, batch_index, 1
                    )
                    for _ in range(self.state_components)
                ]
            )
1566
        else:
1567 1568 1569 1570 1571 1572 1573 1574 1575
            initial_states = (
                [initial_states]
                if isinstance(initial_states, paddle.static.Variable)
                else initial_states
            )

        if self.could_use_cudnn and (
            not paddle.device.is_compiled_with_rocm() or sequence_length is None
        ):
1576 1577 1578
            # Add CPU kernel and dispatch in backend later
            return self._cudnn_impl(inputs, initial_states, sequence_length)

1579 1580 1581
        states = split_states(
            initial_states, self.num_directions == 2, self.state_components
        )
F
Feiyu Chan 已提交
1582 1583 1584 1585
        final_states = []

        for i, rnn_layer in enumerate(self):
            if i > 0:
1586 1587 1588 1589 1590 1591
                inputs = F.dropout(
                    inputs,
                    self.dropout,
                    training=self.training,
                    mode="upscale_in_train",
                )
F
Feiyu Chan 已提交
1592 1593 1594 1595
            outputs, final_state = rnn_layer(inputs, states[i], sequence_length)
            final_states.append(final_state)
            inputs = outputs

1596 1597 1598
        final_states = concat_states(
            final_states, self.num_directions == 2, self.state_components
        )
F
Feiyu Chan 已提交
1599 1600
        return outputs, final_states

1601 1602 1603 1604
    def extra_repr(self):
        main_str = '{input_size}, {hidden_size}'
        if self.num_layers != 1:
            main_str += ', num_layers={num_layers}'
1605
        if self.time_major is not False:
1606 1607 1608 1609 1610
            main_str += ', time_major={time_major}'
        if self.dropout != 0:
            main_str += ', dropout={dropout}'
        return main_str.format(**self.__dict__)

F
Feiyu Chan 已提交
1611

1612
class SimpleRNN(RNNBase):
F
Feiyu Chan 已提交
1613
    r"""
1614
    Multilayer Elman network(SimpleRNN). It takes input sequences and initial
F
Feiyu Chan 已提交
1615 1616
    states as inputs, and returns the output sequences and the final states.

1617 1618 1619
    Each layer inside the SimpleRNN maps the input sequences and initial states
    to the output sequences and final states in the following manner: at each
    step, it takes step inputs(:math:`x_{t}`) and previous
F
Feiyu Chan 已提交
1620 1621 1622 1623 1624
    states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`)
    and new states(:math:`h_{t}`).

    .. math::

1625
        h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh})
1626

F
Feiyu Chan 已提交
1627
        y_{t} & = h_{t}
1628

1629
    where :math:`act` is for :attr:`activation`.
1630 1631

    Using key word arguments to construct is recommended.
F
Feiyu Chan 已提交
1632

1633
    Parameters:
1634 1635 1636
        input_size (int): The input size of :math:`x` for the first layer's cell.
        hidden_size (int): The hidden size of :math:`h` for each layer's cell.
        num_layers (int, optional): Number of recurrent layers. Defaults to 1.
1637 1638
        direction (str, optional): The direction of the network. It can be "forward"
            or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
1639
            outputs of forward and backward is concatenating. Defaults to "forward".
1640 1641
        time_major (bool, optional): Whether the first dimension of the input
            means the time steps. If time_major is True, the shape of Tensor is
1642 1643
            [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
            Defaults to False. `time_steps` means the length of input sequence.
1644 1645
        dropout (float, optional): The droput probability. Dropout is applied
            to the input of each layer except for the first layer. The range of
1646
            dropout from 0 to 1. Defaults to 0.
1647
        activation (str, optional): The activation in each SimpleRNN cell. It can be
1648
            `tanh` or `relu`. Defaults to `tanh`.
1649
        weight_ih_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1650
            `weight_ih` of each cell. Defaults to None.
1651
        weight_hh_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1652
            `weight_hh` of each cell. Defaults to None.
1653
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1654
            `bias_ih` of each cells. Defaults to None.
1655
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1656
            `bias_hh` of each cells. Defaults to None.
1657
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
1658 1659
            None). For more information, please refer to :ref:`api_guide_Name`.

1660
    Inputs:
1661
        - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
1662 1663
        - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used.
        - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings.
F
Feiyu Chan 已提交
1664 1665

    Returns:
1666

1667
        - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.
1668

1669
        - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.
1670 1671 1672 1673 1674 1675

    Variables:
        - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
        - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
        - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
        - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`.
1676

F
Feiyu Chan 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
    Examples:

        .. code-block:: python

            import paddle

            rnn = paddle.nn.SimpleRNN(16, 32, 2)

            x = paddle.randn((4, 23, 16))
            prev_h = paddle.randn((2, 4, 32))
            y, h = rnn(x, prev_h)

1689 1690 1691 1692 1693 1694
            print(y.shape)
            print(h.shape)

            #[4,23,32]
            #[2,4,32]

F
Feiyu Chan 已提交
1695 1696
    """

1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    def __init__(
        self,
        input_size,
        hidden_size,
        num_layers=1,
        direction="forward",
        time_major=False,
        dropout=0.0,
        activation="tanh",
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
1712 1713 1714 1715
        if activation == "tanh":
            mode = "RNN_TANH"
        elif activation == "relu":
            mode = "RNN_RELU"
F
Feiyu Chan 已提交
1716
        else:
1717
            raise ValueError(f"Unknown activation '{activation}'")
1718
        self.activation = activation
1719
        super().__init__(
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
            mode,
            input_size,
            hidden_size,
            num_layers,
            direction,
            time_major,
            dropout,
            weight_ih_attr,
            weight_hh_attr,
            bias_ih_attr,
            bias_hh_attr,
        )
F
Feiyu Chan 已提交
1732 1733


1734
class LSTM(RNNBase):
F
Feiyu Chan 已提交
1735
    r"""
1736
    Multilayer LSTM. It takes a sequence and an initial state as inputs, and
F
Feiyu Chan 已提交
1737 1738
    returns the output sequences and the final states.

1739 1740 1741 1742
    Each layer inside the LSTM maps the input sequences and initial states
    to the output sequences and final states in the following manner: at each
    step, it takes step inputs(:math:`x_{t}`) and previous
    states(:math:`h_{t-1}, c_{t-1}`) as inputs, and returns step
F
Feiyu Chan 已提交
1743 1744 1745 1746 1747
    outputs(:math:`y_{t}`) and new states(:math:`h_{t}, c_{t}`).

    .. math::

        i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi})
1748

F
Feiyu Chan 已提交
1749
        f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf})
1750

F
Feiyu Chan 已提交
1751
        o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho})
1752 1753 1754 1755 1756 1757 1758

        \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg})

        c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t}

        h_{t} & = o_{t} * \tanh(c_{t})

F
Feiyu Chan 已提交
1759 1760
        y_{t} & = h_{t}

1761
    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise
F
Feiyu Chan 已提交
1762 1763
    multiplication operator.

1764 1765
    Using key word arguments to construct is recommended.

1766
    Parameters:
1767 1768 1769
        input_size (int): The input size of :math:`x` for the first layer's cell.
        hidden_size (int): The hidden size of :math:`h` for each layer's cell.
        num_layers (int, optional): Number of recurrent layers. Defaults to 1.
1770 1771
        direction (str, optional): The direction of the network. It can be "forward"
            or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
1772
            outputs of forward and backward is concatenating. Defaults to "forward".
1773 1774
        time_major (bool, optional): Whether the first dimension of the input
            means the time steps. If time_major is True, the shape of Tensor is
1775 1776
            [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
            Defaults to False. `time_steps` means the length of input sequence.
1777 1778
        dropout (float, optional): The droput probability. Dropout is applied
            to the input of each layer except for the first layer. The range of
1779
            dropout from 0 to 1. Defaults to 0.
1780
        weight_ih_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1781
            `weight_ih` of each cell. Default: None.
1782
        weight_hh_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1783
            `weight_hh` of each cell. Default: None.
1784
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1785
            `bias_ih` of each cells. Default: None.
1786
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1787
            `bias_hh` of each cells. Default: None.
1788
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
1789 1790 1791
            None). For more information, please refer to :ref:`api_guide_Name`.

    Inputs:
1792
        - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
1793
        - **initial_states** (list|tuple, optional): the initial state, a list/tuple of (h, c), the shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used.
1794
        - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whos time step index are not less than the valid length are treated as paddings.
F
Feiyu Chan 已提交
1795 1796

    Returns:
1797

1798
        - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, If `time_major` is False, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.
1799

1800
        - **final_states** (tuple): the final state, a tuple of two tensors, h and c. The shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.
1801 1802 1803 1804 1805 1806

    Variables:
        - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
        - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
        - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
        - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, swith shape `[hidden_size]`.
1807

F
Feiyu Chan 已提交
1808
    Examples:
1809

F
Feiyu Chan 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
        .. code-block:: python

            import paddle

            rnn = paddle.nn.LSTM(16, 32, 2)

            x = paddle.randn((4, 23, 16))
            prev_h = paddle.randn((2, 4, 32))
            prev_c = paddle.randn((2, 4, 32))
            y, (h, c) = rnn(x, (prev_h, prev_c))

1821 1822 1823 1824 1825 1826 1827 1828
            print(y.shape)
            print(h.shape)
            print(c.shape)

            #[4,23,32]
            #[2,4,32]
            #[2,4,32]

F
Feiyu Chan 已提交
1829 1830
    """

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    def __init__(
        self,
        input_size,
        hidden_size,
        num_layers=1,
        direction="forward",
        time_major=False,
        dropout=0.0,
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
1845
        super().__init__(
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
            "LSTM",
            input_size,
            hidden_size,
            num_layers,
            direction,
            time_major,
            dropout,
            weight_ih_attr,
            weight_hh_attr,
            bias_ih_attr,
            bias_hh_attr,
        )
F
Feiyu Chan 已提交
1858 1859


1860
class GRU(RNNBase):
F
Feiyu Chan 已提交
1861
    r"""
1862
    Multilayer GRU. It takes input sequencse and initial states as inputs, and
F
Feiyu Chan 已提交
1863 1864
    returns the output sequences and the final states.

1865 1866 1867 1868
    Each layer inside the GRU maps the input sequences and initial states
    to the output sequences and final states in the following manner: at each
    step, it takes step inputs(:math:`x_{t}`) and previous
    states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`)
F
Feiyu Chan 已提交
1869 1870 1871 1872
    and new states(:math:`h_{t}`).

    .. math::

1873
        r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr})
1874

1875
        z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz})
1876

1877
        \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc}))
1878 1879 1880

        h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t}

F
Feiyu Chan 已提交
1881 1882
        y_{t} & = h_{t}

1883
    where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise
F
Feiyu Chan 已提交
1884 1885
    multiplication operator.

1886 1887
    Using key word arguments to construct is recommended.

1888
    Parameters:
1889 1890 1891
        input_size (int): The input size of :math:`x` for the first layer's cell.
        hidden_size (int): The hidden size of :math:`h` for each layer's cell.
        num_layers (int, optional): Number of recurrent layers. Defaults to 1.
1892 1893
        direction (str, optional): The direction of the network. It can be "forward"
            or "bidirect"(or "bidirectional"). When "bidirect", the way to merge
1894
            outputs of forward and backward is concatenating. Defaults to "forward".
1895 1896
        time_major (bool, optional): Whether the first dimension of the input
            means the time steps. If time_major is True, the shape of Tensor is
1897 1898
            [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size].
            Defaults to False. `time_steps` means the length of input sequence.
1899 1900
        dropout (float, optional): The droput probability. Dropout is applied
            to the input of each layer except for the first layer. The range of
1901
            dropout from 0 to 1. Defaults to 0.
1902
        weight_ih_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1903
            `weight_ih` of each cell. Default: None.
1904
        weight_hh_attr (ParamAttr, optional): The parameter attribute for
F
Feiyu Chan 已提交
1905
            `weight_hh` of each cell. Default: None.
1906
        bias_ih_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1907
            `bias_ih` of each cells. Default: None.
1908
        bias_hh_attr (ParamAttr, optional): The parameter attribute for the
F
Feiyu Chan 已提交
1909
            `bias_hh` of each cells. Default: None.
1910
        name (str, optional): Name for the operation (optional, default is
F
Feiyu Chan 已提交
1911 1912 1913
            None). For more information, please refer to :ref:`api_guide_Name`.

    Inputs:
1914
        - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence.
1915 1916
        - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used. Defaults to None.
        - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whos time step index are not less than the valid length are treated as paddings.
F
Feiyu Chan 已提交
1917 1918

    Returns:
1919

1920
        - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence.
1921

1922
        - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1.
1923 1924 1925 1926 1927 1928

    Variables:
        - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`.
        - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`.
        - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`.
        - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`.
1929

F
Feiyu Chan 已提交
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    Examples:

        .. code-block:: python

            import paddle

            rnn = paddle.nn.GRU(16, 32, 2)

            x = paddle.randn((4, 23, 16))
            prev_h = paddle.randn((2, 4, 32))
            y, h = rnn(x, prev_h)

1942 1943 1944 1945 1946 1947
            print(y.shape)
            print(h.shape)

            #[4,23,32]
            #[2,4,32]

F
Feiyu Chan 已提交
1948 1949
    """

1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    def __init__(
        self,
        input_size,
        hidden_size,
        num_layers=1,
        direction="forward",
        time_major=False,
        dropout=0.0,
        weight_ih_attr=None,
        weight_hh_attr=None,
        bias_ih_attr=None,
        bias_hh_attr=None,
        name=None,
    ):
1964
        super().__init__(
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
            "GRU",
            input_size,
            hidden_size,
            num_layers,
            direction,
            time_major,
            dropout,
            weight_ih_attr,
            weight_hh_attr,
            bias_ih_attr,
            bias_hh_attr,
        )