rnn.py 158.0 KB
Newer Older
G
Guo Sheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import sys
G
Guo Sheng 已提交
16
from functools import partial, reduce
J
Jiaqi Liu 已提交
17
import warnings
G
Guo Sheng 已提交
18

19
import paddle
20
from paddle.utils import deprecated
G
Guo Sheng 已提交
21 22 23 24
from . import nn
from . import tensor
from . import control_flow
from . import utils
25
from . import sequence_lod
G
Guo Sheng 已提交
26
from .utils import *
weixin_46829950's avatar
weixin_46829950 已提交
27
from .. import core
28 29
from ..framework import default_main_program
from ..data_feeder import convert_dtype
30
from ..layer_helper import LayerHelper
J
Jiabin Yang 已提交
31
from ..framework import _non_static_mode
32
from ..param_attr import ParamAttr
X
Xing Wu 已提交
33
from ..data_feeder import check_variable_and_dtype, check_type, check_dtype
34

35 36 37 38
try:
    from collections.abc import Sequence
except:
    from collections import Sequence
G
Guo Sheng 已提交
39 40 41 42 43 44 45 46

__all__ = [
    'RNNCell',
    'GRUCell',
    'LSTMCell',
    'Decoder',
    'BeamSearchDecoder',
    'rnn',
F
Feiyu Chan 已提交
47
    'birnn',
G
Guo Sheng 已提交
48
    'dynamic_decode',
49 50 51 52 53
    'DecodeHelper',
    'TrainingHelper',
    'GreedyEmbeddingHelper',
    'SampleEmbeddingHelper',
    'BasicDecoder',
54 55 56 57 58 59 60 61
    'dynamic_lstm',
    'dynamic_lstmp',
    'dynamic_gru',
    'gru_unit',
    'lstm_unit',
    'lstm',
    'beam_search',
    'beam_search_decode',
G
Guo Sheng 已提交
62 63 64
]


65
class RNNCell:
G
Guo Sheng 已提交
66
    """
67
        :api_attr: Static Graph
S
swtkiwi 已提交
68

G
Guo Sheng 已提交
69 70 71 72 73 74
    RNNCell 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.
    """

    def call(self, inputs, states, **kwargs):
75
        r"""
G
Guo Sheng 已提交
76 77 78 79 80 81 82 83 84 85
        Every cell must implement this method to do the calculations mapping the
        inputs and states to the output and new states.

        To be more flexible, both inputs and states can be a tensor variable or
        a nested structure (list|tuple|namedtuple|dict) of tensor variable, that
        is, a (possibly nested structure of) tensor variable[s].

        Parameters:
            inputs: A (possibly nested structure of) tensor variable[s].
            states: A (possibly nested structure of) tensor variable[s].
86 87
            **kwargs: Additional keyword arguments, provided by the caller.

G
Guo Sheng 已提交
88 89 90 91 92 93 94 95 96 97 98
        Returns:
            tuple: outputs and new_states pair. outputs and new_states both \
                can be nested structure of tensor variables. new_states must \
                have the same structure with states.

        """
        raise NotImplementedError("RNNCell must implent the call function.")

    def __call__(self, inputs, states, **kwargs):
        return self.call(inputs, states, **kwargs)

99 100 101 102 103 104 105 106
    def get_initial_states(
        self,
        batch_ref,
        shape=None,
        dtype='float32',
        init_value=0,
        batch_dim_idx=0,
    ):
107
        r"""
G
Guo Sheng 已提交
108 109 110 111 112 113 114
        Generate initialized states according to provided shape, data type and
        value.

        Parameters:
            batch_ref: A (possibly nested structure of) tensor variable[s].
                The first dimension of the tensor will be used as batch size to
                initialize states.
T
tianshuo78520a 已提交
115
            shape: A (possibly nested structure of) shape[s], where a shape is
G
Guo Sheng 已提交
116 117 118
                represented as a list/tuple of integer). -1(for batch size) will
                beautomatically inserted if shape is not started with it. If None,
                property `state_shape` will be used. The default value is None.
T
tianshuo78520a 已提交
119
            dtype: A (possibly nested structure of) data type[s]. The structure
G
Guo Sheng 已提交
120
                must be same as that of `shape`, except when all tensors' in states
X
Xing Wu 已提交
121
                has the same data type, a single data type can be used. If
G
Guo Sheng 已提交
122
                property `cell.state_shape` is not available, float32 will be used
X
Xing Wu 已提交
123
                as the data type. The default value is float32.
G
Guo Sheng 已提交
124
            init_value: A float value used to initialize states.
125 126
            batch_dim_idx: An integer indicating which dimension of the tensor in
                inputs represents batch size.  The default value is 0.
127

G
Guo Sheng 已提交
128 129 130 131
        Returns:
            Variable: tensor variable[s] packed in the same structure provided \
                by shape, representing the initialized states.
        """
132 133 134 135 136 137
        check_variable_and_dtype(
            batch_ref,
            'batch_ref',
            ['float32', 'float64', 'int32', 'int64'],
            'RNNCell',
        )
138
        check_type(shape, 'shape', (list, tuple, type(None), int), 'RNNCell')
X
Xing Wu 已提交
139 140 141 142
        if isinstance(shape, (list, tuple)):
            shapes = map_structure(lambda x: x, shape)
            if isinstance(shape, list):
                for i, _shape in enumerate(shapes):
143
                    check_type(_shape, 'shapes[' + str(i) + ']', int, 'RNNCell')
X
Xing Wu 已提交
144
            else:
145
                check_type(shapes, 'shapes', int, 'RNNCell')
X
Xing Wu 已提交
146 147
        check_dtype(dtype, 'dtype', ['float32', 'float64'], 'RNNCell')

G
Guo Sheng 已提交
148 149 150 151 152
        # TODO: use inputs and batch_size
        batch_ref = flatten(batch_ref)[0]

        def _is_shape_sequence(seq):
            """For shape, list/tuple of integer is the finest-grained objection"""
153 154 155 156
            if isinstance(seq, list) or isinstance(seq, tuple):
                if reduce(
                    lambda flag, x: isinstance(x, int) and flag, seq, True
                ):
G
Guo Sheng 已提交
157 158 159 160
                    return False
            # TODO: Add check for the illegal
            if isinstance(seq, dict):
                return True
161
            return isinstance(seq, Sequence) and not isinstance(seq, str)
G
Guo Sheng 已提交
162

163
        class Shape:
G
Guo Sheng 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
            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
        is_sequence_ori = utils.is_sequence
        utils.is_sequence = _is_shape_sequence
        states_shapes = map_structure(lambda shape: Shape(shape), states_shapes)
        utils.is_sequence = is_sequence_ori

        # nested structure of dtypes
        try:
            states_dtypes = self.state_dtype if dtype is None else dtype
        except NotImplementedError:  # use fp32 as default
            states_dtypes = "float32"
        if len(flatten(states_dtypes)) == 1:
            dtype = flatten(states_dtypes)[0]
            states_dtypes = map_structure(lambda shape: dtype, states_shapes)

        init_states = map_structure(
            lambda shape, dtype: tensor.fill_constant_batch_size_like(
                input=batch_ref,
                shape=shape.shape,
                dtype=dtype,
188
                value=init_value,
189 190 191 192 193
                input_dim_idx=batch_dim_idx,
            ),
            states_shapes,
            states_dtypes,
        )
G
Guo Sheng 已提交
194 195 196 197 198
        return init_states

    @property
    def state_shape(self):
        """
199
        Abstract method (property).
G
Guo Sheng 已提交
200
        Used to initialize states.
T
tianshuo78520a 已提交
201
        A (possibly nested structure of) shape[s], where a shape is represented
G
Guo Sheng 已提交
202
        as a list/tuple of integers (-1 for batch size would be automatically
203
        inserted into a shape if shape is not started with it).
G
Guo Sheng 已提交
204 205 206 207
        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`.
        """
208
        raise NotImplementedError(
209 210
            "Please add implementaion for `state_shape` in the used cell."
        )
G
Guo Sheng 已提交
211 212 213 214

    @property
    def state_dtype(self):
        """
215
        Abstract method (property).
G
Guo Sheng 已提交
216
        Used to initialize states.
T
tianshuo78520a 已提交
217
        A (possibly nested structure of) data types[s]. The structure must be
G
Guo Sheng 已提交
218
        same as that of `shape`, except when all tensors' in states has the same
T
tianshuo78520a 已提交
219
        data type, a single data type can be used.
G
Guo Sheng 已提交
220 221 222 223
        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`.
        """
224
        raise NotImplementedError(
225 226
            "Please add implementaion for `state_dtype` in the used cell."
        )
G
Guo Sheng 已提交
227 228 229


class GRUCell(RNNCell):
230
    r"""
231
        :api_attr: Static Graph
S
swtkiwi 已提交
232

233
    Gated Recurrent Unit cell. It is a wrapper for
G
Guo Sheng 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    `fluid.contrib.layers.rnn_impl.BasicGRUUnit` to make it adapt to RNNCell.

    The formula used is as follow:

    .. math::

        u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u)

        r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r)

        \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c)

        h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t}

    For more details, please refer to  `Learning Phrase Representations using
    RNN Encoder Decoder for Statistical Machine Translation <https://arxiv.org/pdf/1406.1078.pdf>`_

    Examples:

        .. code-block:: python

            import paddle.fluid.layers as layers
            cell = layers.GRUCell(hidden_size=256)
    """

259 260 261 262 263 264 265 266 267 268
    def __init__(
        self,
        hidden_size,
        param_attr=None,
        bias_attr=None,
        gate_activation=None,
        activation=None,
        dtype="float32",
        name="GRUCell",
    ):
G
Guo Sheng 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        """
        Constructor of GRUCell.

        Parameters:
            hidden_size (int): The hidden size in the GRU cell.
            param_attr(ParamAttr, optional): The parameter attribute for the learnable
                weight matrix. Default: None.
            bias_attr (ParamAttr, optional): The parameter attribute for the bias
                of GRU. Default: None.
            gate_activation (function, optional): The activation function for :math:`act_g`.
                Default: `fluid.layers.sigmoid`.
            activation (function, optional): The activation function for :math:`act_c`.
                Default: `fluid.layers.tanh`.
            dtype(string, optional): The data type used in this cell. Default float32.
            name(string, optional) : The name scope used to identify parameters and biases.
        """
X
Xing Wu 已提交
285 286
        check_type(hidden_size, 'hidden_size', (int), 'GRUCell')
        check_dtype(dtype, 'dtype', ['float32', 'float64'], 'GRUCell')
G
Guo Sheng 已提交
287 288
        self.hidden_size = hidden_size
        from .. import contrib  # TODO: resolve recurrent import
289

G
Guo Sheng 已提交
290
        self.gru_unit = contrib.layers.rnn_impl.BasicGRUUnit(
291 292 293 294 295 296 297 298
            name,
            hidden_size,
            param_attr,
            bias_attr,
            gate_activation,
            activation,
            dtype,
        )
G
Guo Sheng 已提交
299 300

    def call(self, inputs, states):
301
        r"""
G
Guo Sheng 已提交
302 303 304 305 306
        Perform calculations of GRU.

        Parameters:
            inputs(Variable): A tensor with shape `[batch_size, input_size]`,
                corresponding to :math:`x_t` in the formula. The data type
X
Xing Wu 已提交
307
                should be float32 or float64.
G
Guo Sheng 已提交
308 309
            states(Variable): A tensor with shape `[batch_size, hidden_size]`.
                corresponding to :math:`h_{t-1}` in the formula. The data type
X
Xing Wu 已提交
310
                should be float32 or float64.
G
Guo Sheng 已提交
311 312 313 314 315

        Returns:
            tuple: A tuple( :code:`(outputs, new_states)` ), where `outputs` and \
                `new_states` is the same tensor shaped `[batch_size, hidden_size]`, \
                corresponding to :math:`h_t` in the formula. The data type of the \
316
                tensor is same as that of `states`.
G
Guo Sheng 已提交
317
        """
X
Xing Wu 已提交
318

319 320 321 322 323 324
        check_variable_and_dtype(
            inputs, 'inputs', ['float32', 'float64'], 'GRUCell'
        )
        check_variable_and_dtype(
            states, 'states', ['float32', 'float64'], 'GRUCell'
        )
G
Guo Sheng 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338
        new_hidden = self.gru_unit(inputs, states)
        return new_hidden, new_hidden

    @property
    def state_shape(self):
        """
        The `state_shape` of GRUCell is a shape `[hidden_size]` (-1 for batch
        size would be automatically inserted into shape). The shape corresponds
        to :math:`h_{t-1}`.
        """
        return [self.hidden_size]


class LSTMCell(RNNCell):
339
    r"""
340
        :api_attr: Static Graph
S
swtkiwi 已提交
341

342
    Long-Short Term Memory cell. It is a wrapper for
G
Guo Sheng 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    `fluid.contrib.layers.rnn_impl.BasicLSTMUnit` to make it adapt to RNNCell.

    The formula used is as follow:

    .. math::

        i_{t} & = act_g(W_{x_{i}}x_{t} + W_{h_{i}}h_{t-1} + b_{i})

        f_{t} & = act_g(W_{x_{f}}x_{t} + W_{h_{f}}h_{t-1} + b_{f} + forget\\_bias)

        c_{t} & = f_{t}c_{t-1} + i_{t} act_c (W_{x_{c}}x_{t} + W_{h_{c}}h_{t-1} + b_{c})

        o_{t} & = act_g(W_{x_{o}}x_{t} + W_{h_{o}}h_{t-1} + b_{o})

        h_{t} & = o_{t} act_c (c_{t})
358

G
Guo Sheng 已提交
359 360 361 362 363 364 365 366 367 368
    For more details, please refer to `RECURRENT NEURAL NETWORK REGULARIZATION <http://arxiv.org/abs/1409.2329>`_

    Examples:

        .. code-block:: python

            import paddle.fluid.layers as layers
            cell = layers.LSTMCell(hidden_size=256)
    """

369 370 371 372 373 374 375 376 377 378 379
    def __init__(
        self,
        hidden_size,
        param_attr=None,
        bias_attr=None,
        gate_activation=None,
        activation=None,
        forget_bias=1.0,
        dtype="float32",
        name="LSTMCell",
    ):
G
Guo Sheng 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        """
        Constructor of LSTMCell.

        Parameters:
            hidden_size (int): The hidden size in the LSTM cell.
            param_attr(ParamAttr, optional): The parameter attribute for the learnable
                weight matrix. Default: None.
            bias_attr (ParamAttr, optional): The parameter attribute for the bias
                of LSTM. Default: None.
            gate_activation (function, optional): The activation function for :math:`act_g`.
                Default: 'fluid.layers.sigmoid'.
            activation (function, optional): The activation function for :math:`act_h`.
                Default: 'fluid.layers.tanh'.
            forget_bias(float, optional): forget bias used when computing forget gate.
                Default 1.0
            dtype(string, optional): The data type used in this cell. Default float32.
            name(string, optional) : The name scope used to identify parameters and biases.
        """
X
Xing Wu 已提交
398 399 400

        check_type(hidden_size, 'hidden_size', (int), 'LSTMCell')
        check_dtype(dtype, 'dtype', ['float32', 'float64'], 'LSTMCell')
G
Guo Sheng 已提交
401 402
        self.hidden_size = hidden_size
        from .. import contrib  # TODO: resolve recurrent import
403

G
Guo Sheng 已提交
404
        self.lstm_unit = contrib.layers.rnn_impl.BasicLSTMUnit(
405 406 407 408 409 410 411 412 413
            name,
            hidden_size,
            param_attr,
            bias_attr,
            gate_activation,
            activation,
            forget_bias,
            dtype,
        )
G
Guo Sheng 已提交
414 415

    def call(self, inputs, states):
416
        r"""
G
Guo Sheng 已提交
417 418 419 420 421
        Perform calculations of LSTM.

        Parameters:
            inputs(Variable): A tensor with shape `[batch_size, input_size]`,
                corresponding to :math:`x_t` in the formula. The data type
X
Xing Wu 已提交
422
                should be float32 or float64.
T
tianshuo78520a 已提交
423
            states(Variable): A list of containing two tensors, each shaped
G
Guo Sheng 已提交
424
                `[batch_size, hidden_size]`, corresponding to :math:`h_{t-1}, c_{t-1}`
X
Xing Wu 已提交
425
                in the formula. The data type should be float32 or float64.
G
Guo Sheng 已提交
426 427 428 429 430 431 432 433 434

        Returns:
            tuple: A tuple( :code:`(outputs, new_states)` ), where `outputs` is \
                a tensor with shape `[batch_size, hidden_size]`, corresponding \
                to :math:`h_{t}` in the formula; `new_states` is a list containing \
                two tenser variables shaped `[batch_size, hidden_size]`, corresponding \
                to :math:`h_{t}, c_{t}` in the formula. The data type of these \
                tensors all is same as that of `states`.
        """
X
Xing Wu 已提交
435

436 437 438
        check_variable_and_dtype(
            inputs, 'inputs', ['float32', 'float64'], 'LSTMCell'
        )
X
Xing Wu 已提交
439 440 441
        check_type(states, 'states', list, 'LSTMCell')
        if isinstance(states, list):
            for i, state in enumerate(states):
442 443 444 445 446 447
                check_variable_and_dtype(
                    state,
                    'state[' + str(i) + ']',
                    ['float32', 'float64'],
                    'LSTMCell',
                )
X
Xing Wu 已提交
448

G
Guo Sheng 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462
        pre_hidden, pre_cell = states
        new_hidden, new_cell = self.lstm_unit(inputs, pre_hidden, pre_cell)
        return new_hidden, [new_hidden, new_cell]

    @property
    def state_shape(self):
        """
        The `state_shape` of LSTMCell is a list with two shapes: `[[hidden_size], [hidden_size]]`
        (-1 for batch size would be automatically inserted into shape). These two
        shapes correspond to :math:`h_{t-1}` and :math:`c_{t-1}` separately.
        """
        return [[self.hidden_size], [self.hidden_size]]


463 464 465 466 467 468 469 470 471
def rnn(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
    **kwargs
):
G
Guo Sheng 已提交
472 473
    """
    rnn creates a recurrent neural network specified by RNNCell `cell`,
474
    which performs :code:`cell.call()` (for dygraph mode :code:`cell.forward`)
F
Feiyu Chan 已提交
475 476 477 478
    repeatedly until reaches to the maximum length of `inputs`.

    Arguments:
        cell(RNNCellBase): An instance of `RNNCellBase`.
479 480
        inputs(Tensor): the input sequences.
            If time_major is True, the shape is
F
Feiyu Chan 已提交
481 482
            `[time_steps, batch_size, input_size]`
            else the shape is `[batch_size, time_steps, input_size]`.
483 484
        initial_states(Tensor|tuple|list, optional): the initial state of the
            rnn cell. Tensor or a possibly nested structure of tensors. If not
F
Feiyu Chan 已提交
485 486
            provided, `cell.get_initial_states` would be called to produce
            the initial state. Defaults to None.
487
        sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
F
Feiyu Chan 已提交
488
            or int32. The valid lengths of input sequences. Defaults to None.
489 490
            If `sequence_length` is not None, the inputs are treated as
            padded sequences. In each input sequence, elements whose time step
F
Feiyu Chan 已提交
491 492 493 494 495
            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.
        is_reverse (bool, optional): Indicate whether to calculate in the reverse
            order of input sequences. Defaults to False.
496
        **kwargs: Additional keyword arguments to pass to `forward` of the cell.
G
Guo Sheng 已提交
497 498

    Returns:
F
Feiyu Chan 已提交
499
        (outputs, final_states)
500
        outputs (Tensor|list|tuple): the output sequence. Tensor or nested
F
Feiyu Chan 已提交
501
            structure of Tensors.
502 503
            If `time_major` is True, the shape of each tensor in outpus is
            `[time_steps, batch_size, hidden_size]`, else
F
Feiyu Chan 已提交
504 505
            `[batch_size, time_steps, hidden_size]`.
        final_states (Tensor|list|tuple): final states. A (possibly nested structure of)
506
            tensor[s], representing the final state for RNN. It has the same
F
Feiyu Chan 已提交
507 508
            structure of intial state. Each tensor in final states has the same
            shape and dtype as the corresponding tensor in initial states.
509

G
Guo Sheng 已提交
510 511 512 513 514

    Examples:

        .. code-block:: python

F
Feiyu Chan 已提交
515 516 517 518 519 520 521
            import paddle
            paddle.disable_static()

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

            inputs = paddle.rand((4, 23, 16))
            prev_h = paddle.randn((4, 32))
522
            outputs, final_states = paddle.fluid.layers.rnn(cell, inputs, prev_h)
F
Feiyu Chan 已提交
523

G
Guo Sheng 已提交
524
    """
J
Jiabin Yang 已提交
525
    if _non_static_mode():
526 527 528 529 530 531 532 533 534
        return _rnn_dynamic_graph(
            cell,
            inputs,
            initial_states,
            sequence_length,
            time_major,
            is_reverse,
            **kwargs
        )
F
Feiyu Chan 已提交
535
    else:
536 537 538 539 540 541 542 543 544
        return _rnn_static_graph(
            cell,
            inputs,
            initial_states,
            sequence_length,
            time_major,
            is_reverse,
            **kwargs
        )
F
Feiyu Chan 已提交
545 546


547
class ArrayWrapper:
F
Feiyu Chan 已提交
548 549 550 551 552 553 554
    def __init__(self, x):
        self.array = [x]

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

555 556 557
    def __getitem__(self, item):
        return self.array.__getitem__(item)

F
Feiyu Chan 已提交
558 559 560

def _maybe_copy(state, new_state, step_mask):
    """update rnn state or just pass the old state through"""
561 562 563
    new_state = nn.elementwise_mul(
        new_state, step_mask, axis=0
    ) + nn.elementwise_mul(state, (1 - step_mask), axis=0)
F
Feiyu Chan 已提交
564 565 566 567 568 569 570 571
    return new_state


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


572 573 574 575 576 577 578 579 580
def _rnn_dynamic_graph(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
    **kwargs
):
F
Feiyu Chan 已提交
581 582 583 584
    time_step_index = 0 if time_major else 1
    flat_inputs = flatten(inputs)
    time_steps = flat_inputs[0].shape[time_step_index]

585 586
    if initial_states is None:
        initial_states = cell.get_initial_states(
587 588
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
589

F
Feiyu Chan 已提交
590 591 592 593
    if not time_major:
        inputs = map_structure(_transpose_batch_time, inputs)

    if sequence_length is not None:
594 595 596
        mask = sequence_lod.sequence_mask(
            sequence_length, maxlen=time_steps, dtype=inputs.dtype
        )
F
Feiyu Chan 已提交
597 598 599 600
        mask = nn.transpose(mask, [1, 0])

    if is_reverse:
        inputs = map_structure(lambda x: tensor.reverse(x, axis=[0]), inputs)
601 602 603 604 605
        mask = (
            tensor.reverse(mask, axis=[0])
            if sequence_length is not None
            else None
        )
F
Feiyu Chan 已提交
606 607 608 609 610 611 612

    states = initial_states
    outputs = []
    for i in range(time_steps):
        step_inputs = map_structure(lambda x: x[i], inputs)
        step_outputs, new_states = cell(step_inputs, states, **kwargs)
        if sequence_length is not None:
613 614 615
            new_states = map_structure(
                partial(_maybe_copy, step_mask=mask[i]), states, new_states
            )
F
Feiyu Chan 已提交
616
        states = new_states
617 618 619 620 621 622 623
        outputs = (
            map_structure(lambda x: ArrayWrapper(x), step_outputs)
            if i == 0
            else map_structure(
                lambda x, x_array: x_array.append(x), step_outputs, outputs
            )
        )
F
Feiyu Chan 已提交
624 625

    final_outputs = map_structure(
626 627
        lambda x: nn.stack(x.array, axis=time_step_index), outputs
    )
F
Feiyu Chan 已提交
628 629 630

    if is_reverse:
        final_outputs = map_structure(
631 632
            lambda x: tensor.reverse(x, axis=time_step_index), final_outputs
        )
F
Feiyu Chan 已提交
633 634 635 636 637

    final_states = new_states
    return final_outputs, final_states


638 639 640 641 642 643 644 645 646
def _rnn_static_graph(
    cell,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    is_reverse=False,
    **kwargs
):
X
Xing Wu 已提交
647 648 649
    check_type(inputs, 'inputs', (Variable, list, tuple), 'rnn')
    if isinstance(inputs, (list, tuple)):
        for i, input_x in enumerate(inputs):
650 651 652 653 654 655 656 657 658
            check_variable_and_dtype(
                input_x, 'inputs[' + str(i) + ']', ['float32', 'float64'], 'rnn'
            )
    check_type(
        initial_states,
        'initial_states',
        (Variable, list, tuple, type(None)),
        'rnn',
    )
X
Xing Wu 已提交
659

660 661 662
    check_type(
        sequence_length, 'sequence_length', (Variable, type(None)), 'rnn'
    )
G
Guo Sheng 已提交
663 664 665 666 667 668

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

    if initial_states is None:
669
        initial_states = cell.get_initial_states(
670 671
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
G
Guo Sheng 已提交
672 673 674 675 676 677 678
    initial_states = map_structure(_switch_grad, initial_states)

    if not time_major:
        inputs = map_structure(_transpose_batch_time, inputs)

    if sequence_length:
        max_seq_len = nn.shape(flatten(inputs)[0])[0]
679
        mask = sequence_lod.sequence_mask(
G
Guo Sheng 已提交
680 681
            sequence_length,
            maxlen=max_seq_len,
682 683
            dtype=flatten(initial_states)[0].dtype,
        )
G
Guo Sheng 已提交
684 685 686 687 688 689 690 691 692 693 694
        mask = nn.transpose(mask, [1, 0])
    if is_reverse:
        inputs = map_structure(lambda x: tensor.reverse(x, axis=[0]), inputs)
        mask = tensor.reverse(mask, axis=[0]) if sequence_length else None

    # StaticRNN
    rnn = control_flow.StaticRNN()
    with rnn.step():
        inputs = map_structure(rnn.step_input, inputs)
        states = map_structure(rnn.memory, initial_states)
        copy_states = map_structure(lambda x: x, states)
H
Huihuang Zheng 已提交
695
        outputs, new_states = cell(inputs, copy_states, **kwargs)
G
Guo Sheng 已提交
696 697 698 699
        assert_same_structure(states, new_states)
        if sequence_length:
            step_mask = rnn.step_input(mask)
            new_states = map_structure(
700 701
                partial(_maybe_copy, step_mask=step_mask), states, new_states
            )
G
Guo Sheng 已提交
702 703 704 705 706 707 708

        map_structure(rnn.update_memory, states, new_states)
        flat_outputs = flatten(outputs)
        map_structure(rnn.step_output, outputs)
        map_structure(rnn.step_output, new_states)

    rnn_out = rnn()
709
    final_outputs = rnn_out[: len(flat_outputs)]
G
Guo Sheng 已提交
710
    final_outputs = pack_sequence_as(outputs, final_outputs)
711
    final_states = map_structure(lambda x: x[-1], rnn_out[len(flat_outputs) :])
G
Guo Sheng 已提交
712 713 714
    final_states = pack_sequence_as(new_states, final_states)

    if is_reverse:
715 716 717
        final_outputs = map_structure(
            lambda x: tensor.reverse(x, axis=[0]), final_outputs
        )
G
Guo Sheng 已提交
718 719 720 721 722 723 724

    if not time_major:
        final_outputs = map_structure(_transpose_batch_time, final_outputs)

    return (final_outputs, final_states)


725 726 727 728 729 730 731 732 733
def birnn(
    cell_fw,
    cell_bw,
    inputs,
    initial_states=None,
    sequence_length=None,
    time_major=False,
    **kwargs
):
F
Feiyu Chan 已提交
734
    """
735 736 737
    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
738
    the maximum length of `inputs` and then concat the outputs for both RNNs
F
Feiyu Chan 已提交
739 740 741 742 743
    along the last axis.

    Arguments:
        cell_fw(RNNCellBase): An instance of `RNNCellBase`.
        cell_bw(RNNCellBase): An instance of `RNNCellBase`.
744 745
        inputs(Tensor): the input sequences.
            If time_major is True, the shape is
F
Feiyu Chan 已提交
746 747
            `[time_steps, batch_size, input_size]`
            else the shape is `[batch_size, time_steps, input_size]`.
748
        initial_states(tuple, optional): A tuple of initial states of
F
Feiyu Chan 已提交
749
            `cell_fw` and `cell_bw`.
750
            If not provided, `cell.get_initial_states` would be called to
F
Feiyu Chan 已提交
751
            produce initial state for each cell. Defaults to None.
752
        sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64
F
Feiyu Chan 已提交
753
            or int32. The valid lengths of input sequences. Defaults to None.
754 755
            If `sequence_length` is not None, the inputs are treated as
            padded sequences. In each input sequence, elements whose time step
F
Feiyu Chan 已提交
756 757 758
            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.
759
        **kwargs: Additional keyword arguments to pass to `forward` of each cell.
F
Feiyu Chan 已提交
760 761 762

    Returns:
        (outputs, final_states)
763 764 765
        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.
F
Feiyu Chan 已提交
766 767 768
            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`.
769 770
        final_states (tuple): A tuple of the final states of the forward
            cell and backward cell.
F
Feiyu Chan 已提交
771 772 773 774

    Examples:

        .. code-block:: python
775

F
Feiyu Chan 已提交
776 777 778 779 780 781 782 783 784 785
            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))
786
            outputs, final_states = paddle.fluid.layers.birnn(
F
Feiyu Chan 已提交
787
                cell_fw, cell_bw, inputs, initial_states)
788

F
Feiyu Chan 已提交
789 790 791
    """
    if initial_states is None:
        states_fw = cell_fw.get_initial_states(
792 793
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
F
Feiyu Chan 已提交
794
        states_bw = cell_fw.get_initial_states(
795 796
            batch_ref=inputs, batch_dim_idx=1 if time_major else 0
        )
F
Feiyu Chan 已提交
797 798
    else:
        states_fw, states_bw = initial_states
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    outputs_fw, states_fw = rnn(
        cell_fw,
        inputs,
        states_fw,
        sequence_length,
        time_major=time_major,
        **kwargs
    )

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

    outputs = map_structure(
        lambda x, y: tensor.concat([x, y], -1), outputs_fw, outputs_bw
    )
F
Feiyu Chan 已提交
821 822 823 824 825

    final_states = (states_fw, states_bw)
    return outputs, final_states


826
class Decoder:
G
Guo Sheng 已提交
827
    """
828
        :api_attr: Static Graph
S
swtkiwi 已提交
829

G
Guo Sheng 已提交
830 831
    Decoder is the base class for any decoder instance used in `dynamic_decode`.
    It provides interface for output generation for one time step, which can be
832
    used to generate sequences.
G
Guo Sheng 已提交
833 834 835 836 837

    The key abstraction provided by Decoder is:

    1. :code:`(initial_input, initial_state, finished) = initialize(inits)` ,
    which generates the input and state for the first decoding step, and gives the
838
    initial status telling whether each sequence in the batch is finished.
G
Guo Sheng 已提交
839 840 841
    It would be called once before the decoding iterations.

    2. :code:`(output, next_state, next_input, finished) = step(time, input, state)` ,
842
    which transforms the input and state to the output and new state, generates
G
Guo Sheng 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    input for the next decoding step, and emits the flag indicating finished status.
    It is the main part for each decoding iteration.

    3. :code:`(final_outputs, final_state) = finalize(outputs, final_state, sequence_lengths)` ,
    which revises the outputs(stack of all time steps' output) and final state(state from the
    last decoding step) to get the counterpart for special usage.
    Not necessary to be implemented if no need to revise the stacked outputs and
    state from the last decoding step. If implemented, it would be called after
    the decoding iterations.

    Decoder is more general compared to RNNCell, since the returned `next_input`
    and `finished` make it can determine the input and when to finish by itself
    when used in dynamic decoding. Decoder always wraps a RNNCell instance though
    not necessary.
    """

    def initialize(self, inits):
860
        r"""
G
Guo Sheng 已提交
861 862 863 864 865 866
        Called once before the decoding iterations.

        Parameters:
            inits: Argument provided by the caller.

        Returns:
867
            tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
G
Guo Sheng 已提交
868 869 870 871 872 873
                `initial_inputs` and `initial_states` both are a (possibly nested \
                structure of) tensor variable[s], and `finished` is a tensor with \
                bool data type.
        """
        raise NotImplementedError

874
    def step(self, time, inputs, states, **kwargs):
875
        r"""
876
        Called per step of decoding.
G
Guo Sheng 已提交
877 878 879 880 881 882

        Parameters:
            time(Variable): A Tensor with shape :math:`[1]` provided by the caller.
                The data type is int64.
            inputs(Variable): A (possibly nested structure of) tensor variable[s].
            states(Variable): A (possibly nested structure of) tensor variable[s].
883
            **kwargs: Additional keyword arguments, provided by the caller.
884

G
Guo Sheng 已提交
885 886 887 888 889 890 891 892 893 894 895
        Returns:
            tuple: A tuple( :code:(outputs, next_states, next_inputs, finished)` ). \
                `next_inputs` and `next_states` both are a (possibly nested \
                structure of) tensor variable[s], and the structure, shape and \
                data type must be same as the counterpart from input arguments. \
                `outputs` is a (possibly nested structure of) tensor variable[s]. \
                `finished` is a Tensor with bool data type.
        """
        raise NotImplementedError

    def finalize(self, outputs, final_states, sequence_lengths):
896
        r"""
G
Guo Sheng 已提交
897 898 899 900 901
        Called once after the decoding iterations if implemented.

        Parameters:
            outputs(Variable): A (possibly nested structure of) tensor variable[s].
                The structure and data type is same as `output_dtype`.
902 903
                The tensor stacks all time steps' output thus has shape
                :math:`[time\_step, batch\_size, ...]` , which is done by the caller.
G
Guo Sheng 已提交
904 905
            final_states(Variable): A (possibly nested structure of) tensor variable[s].
                It is the `next_states` returned by `decoder.step` at last decoding step,
T
tianshuo78520a 已提交
906
                thus has the same structure, shape and data type with states at any time
G
Guo Sheng 已提交
907 908 909 910 911 912 913 914 915
                step.

        Returns:
            tuple: A tuple( :code:`(final_outputs, final_states)` ). \
                `final_outputs` and `final_states` both are a (possibly nested \
                structure of) tensor variable[s].
        """
        raise NotImplementedError

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
    @property
    def tracks_own_finished(self):
        """
        Describes whether the Decoder keeps track of finished states by itself.

        `decoder.step()` would emit a bool `finished` value at each decoding
        step. The emited `finished` can be used to determine whether every
        batch entries is finished directly, or it can be combined with the
        finished tracker keeped in `dynamic_decode` by performing a logical OR
        to take the already finished into account.

        If `False`, the latter would be took when performing `dynamic_decode`,
        which is the default. Otherwise, the former would be took, which uses
        the finished value emited by the decoder as all batch entry finished
        status directly, and it is the case when batch entries might be
        reordered such as beams in BeamSearchDecoder.

        Returns:
            bool: A python bool `False`.
        """
        return False

G
Guo Sheng 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955

class BeamSearchDecoder(Decoder):
    """
    Decoder with beam search decoding strategy. It wraps a cell to get probabilities,
    and follows a beam search step to calculate scores and select candidate
    token ids for each decoding step.

    Please refer to `Beam search <https://en.wikipedia.org/wiki/Beam_search>`_
    for more details.

    **NOTE** When decoding with beam search, the `inputs` and `states` of cell
    would be tiled to `beam_size` (unsqueeze and tile), resulting to shapes like
    `[batch_size * beam_size, ...]` , which is built into `BeamSearchDecoder` and
    done automatically. Thus any other tensor with shape `[batch_size, ...]` used
    in `cell.call` needs to be tiled manually first, which can be completed by using
    :code:`BeamSearchDecoder.tile_beam_merge_with_batch` . The most common case
    for this is the encoder output in attention mechanism.

956 957
    Returns:
        BeamSearchDecoder: An instance of decoder which can be used in \
958
            `paddle.nn.dynamic_decode` to implement decoding.
G
Guo Sheng 已提交
959 960 961 962

    Examples:

        .. code-block:: python
963

964 965 966 967 968 969 970
            import numpy as np
            import paddle
            from paddle.nn import BeamSearchDecoder, dynamic_decode
            from paddle.nn import GRUCell, Linear, Embedding
            trg_embeder = Embedding(100, 32)
            output_layer = Linear(32, 32)
            decoder_cell = GRUCell(input_size=32, hidden_size=32)
G
Guo Sheng 已提交
971 972 973 974 975 976
            decoder = BeamSearchDecoder(decoder_cell,
                                        start_token=0,
                                        end_token=1,
                                        beam_size=4,
                                        embedding_fn=trg_embeder,
                                        output_fn=output_layer)
977

G
Guo Sheng 已提交
978 979
    """

980 981 982 983 984 985 986 987 988
    def __init__(
        self,
        cell,
        start_token,
        end_token,
        beam_size,
        embedding_fn=None,
        output_fn=None,
    ):
G
Guo Sheng 已提交
989 990 991 992
        """
        Constructor of BeamSearchDecoder.

        Parameters:
993
            cell(RNNCellBase): An instance of `RNNCellBase` or object with the same interface.
G
Guo Sheng 已提交
994 995 996
            start_token(int): The start token id.
            end_token(int): The end token id.
            beam_size(int): The beam width used in beam search.
997
            embedding_fn(optional): A callable to apply to selected candidate ids.
G
Guo Sheng 已提交
998 999
                Mostly it is an embedding layer to transform ids to embeddings,
                and the returned value acts as the `input` argument for `cell.call`.
T
tianshuo78520a 已提交
1000
                If not provided, the id to embedding transformation must be built into
G
Guo Sheng 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                `cell.call`. Default None.
            output_fn(optional): A callable to apply to the cell's output prior to
                calculate scores and select candidate token ids. Default None.
        """
        self.cell = cell
        self.embedding_fn = embedding_fn
        self.output_fn = output_fn
        self.start_token = start_token
        self.end_token = end_token
        self.beam_size = beam_size

    @staticmethod
    def tile_beam_merge_with_batch(x, beam_size):
1014
        r"""
G
Guo Sheng 已提交
1015
        Tile the batch dimension of a tensor. Specifically, this function takes
1016
        a tensor t shaped `[batch_size, s0, s1, ...]` composed of minibatch
G
Guo Sheng 已提交
1017 1018 1019 1020 1021 1022
        entries `t[0], ..., t[batch_size - 1]` and tiles it to have a shape
        `[batch_size * beam_size, s0, s1, ...]` composed of minibatch entries
        `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated
        `beam_size` times.

        Parameters:
T
tianshuo78520a 已提交
1023
            x(Variable): A tensor with shape `[batch_size, ...]`. The data type
G
Guo Sheng 已提交
1024 1025 1026 1027 1028 1029 1030
                should be float32, float64, int32, int64 or bool.
            beam_size(int): The beam width used in beam search.

        Returns:
            Variable: A tensor with shape `[batch_size * beam_size, ...]`, whose \
                data type is same as `x`.
        """
1031 1032 1033
        check_type(
            x, 'x', (Variable), 'BeamSearchDecoder.tile_beam_merge_with_batch'
        )
G
Guo Sheng 已提交
1034 1035 1036
        x = nn.unsqueeze(x, [1])  # [batch_size, 1, ...]
        expand_times = [1] * len(x.shape)
        expand_times[1] = beam_size
1037
        x = paddle.tile(x, expand_times)  # [batch_size, beam_size, ...]
1038 1039 1040
        x = nn.transpose(
            x, list(range(2, len(x.shape))) + [0, 1]
        )  # [..., batch_size, beam_size]
G
Guo Sheng 已提交
1041
        # use 0 to copy to avoid wrong shape
1042 1043 1044
        x = nn.reshape(
            x, shape=[0] * (len(x.shape) - 2) + [-1]
        )  # [..., batch_size * beam_size]
G
Guo Sheng 已提交
1045
        x = nn.transpose(
1046 1047
            x, [len(x.shape) - 1] + list(range(0, len(x.shape) - 1))
        )  # [batch_size * beam_size, ...]
G
Guo Sheng 已提交
1048 1049 1050
        return x

    def _split_batch_beams(self, x):
1051
        r"""
G
Guo Sheng 已提交
1052
        Reshape a tensor with shape `[batch_size * beam_size, ...]` to a new
1053
        tensor with shape `[batch_size, beam_size, ...]`.
G
Guo Sheng 已提交
1054 1055

        Parameters:
T
tianshuo78520a 已提交
1056
            x(Variable): A tensor with shape `[batch_size * beam_size, ...]`. The
G
Guo Sheng 已提交
1057 1058 1059 1060
                data type should be float32, float64, int32, int64 or bool.

        Returns:
            Variable: A tensor with shape `[batch_size, beam_size, ...]`, whose \
1061
                data type is same as `x`.
G
Guo Sheng 已提交
1062
        """
1063
        check_type(x, 'x', (Variable), 'BeamSearchDecoder._split_batch_beams')
G
Guo Sheng 已提交
1064
        # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch
1065
        return nn.reshape(x, shape=[-1, self.beam_size] + list(x.shape[1:]))
G
Guo Sheng 已提交
1066 1067

    def _merge_batch_beams(self, x):
1068
        r"""
G
Guo Sheng 已提交
1069
        Reshape a tensor with shape `[batch_size, beam_size, ...]` to a new
1070
        tensor with shape `[batch_size * beam_size, ...]`.
G
Guo Sheng 已提交
1071 1072

        Parameters:
T
tianshuo78520a 已提交
1073
            x(Variable): A tensor with shape `[batch_size, beam_size, ...]`. The
G
Guo Sheng 已提交
1074 1075 1076 1077
                data type should be float32, float64, int32, int64 or bool.

        Returns:
            Variable: A tensor with shape `[batch_size * beam_size, ...]`, whose \
1078
                data type is same as `x`.
G
Guo Sheng 已提交
1079
        """
1080
        check_type(x, 'x', (Variable), 'BeamSearchDecoder._merge_batch_beams')
G
Guo Sheng 已提交
1081
        # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch
1082
        return nn.reshape(x, shape=[-1] + list(x.shape[2:]))
G
Guo Sheng 已提交
1083 1084

    def _expand_to_beam_size(self, x):
1085
        r"""
G
Guo Sheng 已提交
1086 1087 1088 1089 1090 1091 1092
        This function takes a tensor t shaped `[batch_size, s0, s1, ...]` composed
        of minibatch entries `t[0], ..., t[batch_size - 1]` and tiles it to have a
        shape `[batch_size, beam_size, s0, s1, ...]` composed of minibatch entries
        `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated
        `beam_size` times.

        Parameters:
1093 1094
            x(Variable): A tensor with shape `[batch_size, ...]`, The data type
                should be float32, float64, int32, int64 or bool.
G
Guo Sheng 已提交
1095 1096 1097 1098 1099

        Returns:
            Variable: A tensor with shape `[batch_size, beam_size, ...]`, whose \
                data type is same as `x`.
        """
1100
        check_type(x, 'x', (Variable), 'BeamSearchDecoder._expand_to_beam_size')
G
Guo Sheng 已提交
1101 1102 1103
        x = nn.unsqueeze(x, [1])
        expand_times = [1] * len(x.shape)
        expand_times[1] = self.beam_size
1104
        x = paddle.tile(x, expand_times)
G
Guo Sheng 已提交
1105 1106 1107
        return x

    def _mask_probs(self, probs, finished):
1108
        r"""
G
Guo Sheng 已提交
1109 1110 1111 1112 1113
        Mask log probabilities. It forces finished beams to allocate all probability
        mass to eos and unfinished beams to remain unchanged.

        Parameters:
            probs(Variable): A tensor with shape `[batch_size, beam_size, vocab_size]`,
X
Xing Wu 已提交
1114
                representing the log probabilities. Its data type should be float32 or float64.
G
Guo Sheng 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123
            finished(Variable): A tensor with shape `[batch_size, beam_size]`,
                representing the finished status for all beams. Its data type
                should be bool.

        Returns:
            Variable: A tensor with the same shape and data type as `x`, \
                where unfinished beams stay unchanged and finished beams are \
                replaced with a tensor with all probability on the EOS token.
        """
1124
        check_type(probs, 'probs', (Variable), 'BeamSearchDecoder._mask_probs')
1125 1126 1127
        check_type(
            finished, 'finished', (Variable), 'BeamSearchDecoder._mask_probs'
        )
G
Guo Sheng 已提交
1128 1129 1130
        # TODO: use where_op
        finished = tensor.cast(finished, dtype=probs.dtype)
        probs = nn.elementwise_mul(
1131
            paddle.tile(nn.unsqueeze(finished, [2]), [1, 1, self.vocab_size]),
G
Guo Sheng 已提交
1132
            self.noend_mask_tensor,
1133 1134
            axis=-1,
        ) - nn.elementwise_mul(probs, (finished - 1), axis=0)
G
Guo Sheng 已提交
1135 1136 1137
        return probs

    def _gather(self, x, indices, batch_size):
1138
        r"""
G
Guo Sheng 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        Gather from the tensor `x` using `indices`.

        Parameters:
            x(Variable): A tensor with shape `[batch_size, beam_size, ...]`.
            indices(Variable): A `int64` tensor with shape `[batch_size, beam_size]`,
                representing the indices that we use to gather.
            batch_size(Variable): A tensor with shape `[1]`. Its data type should
                be int32 or int64.

        Returns:
            Variable: A tensor with the same shape and data type as `x`, \
                representing the gathered tensor.
        """
1152 1153
        check_type(x, 'x', (Variable), 'BeamSearchDecoder._gather')
        check_type(indices, 'indices', (Variable), 'BeamSearchDecoder._gather')
1154 1155 1156
        check_type(
            batch_size, 'batch_size', (Variable), 'BeamSearchDecoder._gather'
        )
G
Guo Sheng 已提交
1157
        # TODO: compatibility of int32 and int64
1158 1159 1160 1161 1162
        batch_size = (
            tensor.cast(batch_size, indices.dtype)
            if batch_size.dtype != indices.dtype
            else batch_size
        )
1163
        batch_size.stop_gradient = True  # TODO: remove this
1164
        batch_pos = paddle.tile(
1165 1166 1167 1168 1169
            nn.unsqueeze(
                tensor.range(0, batch_size, 1, dtype=indices.dtype), [1]
            ),
            [1, self.beam_size],
        )
G
Guo Sheng 已提交
1170
        topk_coordinates = nn.stack([batch_pos, indices], axis=2)
1171
        topk_coordinates.stop_gradient = True
G
Guo Sheng 已提交
1172 1173 1174
        return nn.gather_nd(x, topk_coordinates)

    class OutputWrapper(
1175 1176 1177 1178
        collections.namedtuple(
            "OutputWrapper", ("scores", "predicted_ids", "parent_ids")
        )
    ):
G
Guo Sheng 已提交
1179 1180 1181 1182
        """
        The structure for the returned value `outputs` of `decoder.step`.
        A namedtuple includes scores, predicted_ids, parent_ids as fields.
        """
1183

G
Guo Sheng 已提交
1184 1185 1186
        pass

    class StateWrapper(
1187 1188 1189 1190
        collections.namedtuple(
            "StateWrapper", ("cell_states", "log_probs", "finished", "lengths")
        )
    ):
G
Guo Sheng 已提交
1191 1192 1193 1194
        """
        The structure for the argument `states` of `decoder.step`.
        A namedtuple includes cell_states, log_probs, finished, lengths as fields.
        """
1195

G
Guo Sheng 已提交
1196 1197 1198
        pass

    def initialize(self, initial_cell_states):
1199
        r"""
G
Guo Sheng 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208
        Initialize the BeamSearchDecoder.

        Parameters:
            initial_cell_states(Variable): A (possibly nested structure of)
                tensor variable[s]. An argument provided by the caller.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
                `initial_inputs` is a tensor t filled by `start_token` with shape \
1209
                `[batch_size, beam_size]` when `embedding_fn` is None, or the \
G
Guo Sheng 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
                returned value of `embedding_fn(t)` when `embedding_fn` is provided. \
                `initial_states` is a nested structure(namedtuple including cell_states, \
                log_probs, finished, lengths as fields) of tensor variables, where \
                `log_probs, finished, lengths` all has a tensor value shaped \
                `[batch_size, beam_size]` with data type `float32, bool, int64`. \
                cell_states has a value with the same structure as the input \
                argument `initial_cell_states` but with tiled shape `[batch_size, beam_size, ...]`. \
                `finished` is a `bool` tensor filled by False with shape `[batch_size, beam_size]`.
        """
        self.kinf = 1e9
        state = flatten(initial_cell_states)[0]
        self.batch_size = nn.shape(state)[0]

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
        self.start_token_tensor = tensor.fill_constant(
            shape=[1], dtype="int64", value=self.start_token
        )
        self.end_token_tensor = tensor.fill_constant(
            shape=[1], dtype="int64", value=self.end_token
        )

        init_cell_states = map_structure(
            self._expand_to_beam_size, initial_cell_states
        )
        init_inputs = paddle.full(
            shape=[self.batch_size, self.beam_size],
            fill_value=self.start_token_tensor,
            dtype=self.start_token_tensor.dtype,
        )
1238
        log_probs = paddle.tile(
G
Guo Sheng 已提交
1239
            tensor.assign(
1240 1241 1242 1243 1244 1245 1246
                np.array(
                    [[0.0] + [-self.kinf] * (self.beam_size - 1)],
                    dtype="float32",
                )
            ),
            [self.batch_size, 1],
        )
1247 1248
        if paddle.get_default_dtype() == "float64":
            log_probs = tensor.cast(log_probs, "float64")
G
Guo Sheng 已提交
1249 1250 1251 1252 1253 1254
        # TODO: remove the restriction of force_cpu
        init_finished = tensor.fill_constant_batch_size_like(
            input=state,
            shape=[-1, self.beam_size],
            dtype="bool",
            value=False,
1255 1256
            force_cpu=True,
        )
G
Guo Sheng 已提交
1257
        init_lengths = tensor.zeros_like(init_inputs)
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        init_inputs = (
            self.embedding_fn(init_inputs) if self.embedding_fn else init_inputs
        )
        return (
            init_inputs,
            self.StateWrapper(
                init_cell_states, log_probs, init_finished, init_lengths
            ),
            init_finished,
        )
G
Guo Sheng 已提交
1268 1269

    def _beam_search_step(self, time, logits, next_cell_states, beam_state):
1270
        r"""
G
Guo Sheng 已提交
1271 1272 1273 1274 1275 1276 1277 1278
        Calculate scores and select candidate token ids.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the caller,
                representing the current time step number of decoding.
            logits(Variable): A tensor with shape `[batch_size, beam_size, vocab_size]`,
                representing the logits at the current time step. Its data type is float32.
            next_cell_states(Variable): A (possibly nested structure of) tensor variable[s].
1279 1280
                It has the same structure, shape and data type as the `cell_states` of
                `initial_states` returned by `initialize()`. It represents the next state
G
Guo Sheng 已提交
1281 1282 1283 1284
                from the cell.
            beam_state(Variable): A structure of tensor variables.
                It is same as the `initial_states` returned by `initialize()` for
                the first decoding step and `beam_search_state` returned by
1285
                `step()` for the others.
1286

G
Guo Sheng 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
        Returns:
            tuple: A tuple( :code:`(beam_search_output, beam_search_state)` ). \
                `beam_search_output` is a namedtuple(including scores, predicted_ids, \
                parent_ids as fields) of tensor variables, where \
                `scores, predicted_ids, parent_ids` all has a tensor value shaped \
                `[batch_size, beam_size]` with data type `float32, int64, int64`.
                `beam_search_state` has the same structure, shape and data type \
                as the input argument `beam_state`.

        """
        self.vocab_size = logits.shape[-1]
1298 1299 1300
        self.vocab_size_tensor = tensor.fill_constant(
            shape=[1], dtype="int64", value=self.vocab_size
        )
G
Guo Sheng 已提交
1301 1302
        noend_array = [-self.kinf] * self.vocab_size
        noend_array[self.end_token] = 0
1303

G
Guo Sheng 已提交
1304
        self.noend_mask_tensor = tensor.assign(np.array(noend_array, "float32"))
1305
        if paddle.get_default_dtype() == "float64":
1306 1307 1308
            self.noend_mask_tensor = tensor.cast(
                self.noend_mask_tensor, "float64"
            )
G
Guo Sheng 已提交
1309 1310 1311

        step_log_probs = nn.log(nn.softmax(logits))
        step_log_probs = self._mask_probs(step_log_probs, beam_state.finished)
1312 1313 1314
        log_probs = nn.elementwise_add(
            x=step_log_probs, y=beam_state.log_probs, axis=0
        )
G
Guo Sheng 已提交
1315 1316 1317
        # TODO: length penalty
        scores = log_probs
        scores = nn.reshape(scores, [-1, self.beam_size * self.vocab_size])
1318
        # TODO: add grad for topk then this beam search can be used to train
1319
        topk_scores, topk_indices = paddle.topk(x=scores, k=self.beam_size)
1320 1321 1322
        beam_indices = nn.elementwise_floordiv(
            topk_indices, self.vocab_size_tensor
        )
G
Guo Sheng 已提交
1323 1324 1325
        token_indices = nn.elementwise_mod(topk_indices, self.vocab_size_tensor)
        next_log_probs = self._gather(
            nn.reshape(log_probs, [-1, self.beam_size * self.vocab_size]),
1326 1327 1328
            topk_indices,
            self.batch_size,
        )
G
Guo Sheng 已提交
1329 1330
        next_cell_states = map_structure(
            lambda x: self._gather(x, beam_indices, self.batch_size),
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
            next_cell_states,
        )
        next_finished = self._gather(
            beam_state.finished, beam_indices, self.batch_size
        )
        next_lengths = self._gather(
            beam_state.lengths, beam_indices, self.batch_size
        )
        next_lengths = next_lengths + tensor.cast(
            nn.logical_not(next_finished), beam_state.lengths.dtype
        )
G
Guo Sheng 已提交
1342 1343
        next_finished = control_flow.logical_or(
            next_finished,
1344 1345 1346 1347 1348 1349 1350 1351 1352
            control_flow.equal(token_indices, self.end_token_tensor),
        )

        beam_search_output = self.OutputWrapper(
            topk_scores, token_indices, beam_indices
        )
        beam_search_state = self.StateWrapper(
            next_cell_states, next_log_probs, next_finished, next_lengths
        )
G
Guo Sheng 已提交
1353 1354 1355
        return beam_search_output, beam_search_state

    def step(self, time, inputs, states, **kwargs):
1356
        r"""
G
Guo Sheng 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        Perform a beam search decoding step, which uses `cell` to get probabilities,
        and follows a beam search step to calculate scores and select candidate
        token ids.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the caller,
                representing the current time step number of decoding.
            inputs(Variable): A tensor variable. It is same as `initial_inputs`
                returned by `initialize()` for the first decoding step and
                `next_inputs` returned by `step()` for the others.
            states(Variable): A structure of tensor variables.
                It is same as the `initial_states` returned by `initialize()` for
                the first decoding step and `beam_search_state` returned by
                `step()` for the others.
1371 1372
            **kwargs: Additional keyword arguments, provided by the caller.

G
Guo Sheng 已提交
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
        Returns:
            tuple: A tuple( :code:`(beam_search_output, beam_search_state, next_inputs, finished)` ). \
                `beam_search_state` and `next_inputs` have the same structure, \
                shape and data type as the input arguments `states` and `inputs` separately. \
                `beam_search_output` is a namedtuple(including scores, predicted_ids, \
                parent_ids as fields) of tensor variables, where \
                `scores, predicted_ids, parent_ids` all has a tensor value shaped \
                `[batch_size, beam_size]` with data type `float32, int64, int64`. \
                `finished` is a `bool` tensor with shape `[batch_size, beam_size]`.
        """
        inputs = map_structure(self._merge_batch_beams, inputs)
        cell_states = map_structure(self._merge_batch_beams, states.cell_states)
1385 1386 1387
        cell_outputs, next_cell_states = self.cell(
            inputs, cell_states, **kwargs
        )
G
Guo Sheng 已提交
1388
        cell_outputs = map_structure(self._split_batch_beams, cell_outputs)
1389 1390 1391
        next_cell_states = map_structure(
            self._split_batch_beams, next_cell_states
        )
G
Guo Sheng 已提交
1392 1393 1394 1395 1396 1397 1398 1399

        if self.output_fn is not None:
            cell_outputs = self.output_fn(cell_outputs)

        beam_search_output, beam_search_state = self._beam_search_step(
            time=time,
            logits=cell_outputs,
            next_cell_states=next_cell_states,
1400 1401
            beam_state=states,
        )
G
Guo Sheng 已提交
1402 1403
        finished = beam_search_state.finished
        sample_ids = beam_search_output.predicted_ids
1404
        sample_ids.stop_gradient = True
1405 1406 1407
        next_inputs = (
            self.embedding_fn(sample_ids) if self.embedding_fn else sample_ids
        )
G
Guo Sheng 已提交
1408 1409 1410 1411

        return (beam_search_output, beam_search_state, next_inputs, finished)

    def finalize(self, outputs, final_states, sequence_lengths):
1412
        r"""
G
Guo Sheng 已提交
1413 1414 1415 1416 1417 1418
        Use `gather_tree` to backtrace along the beam search tree and construct
        the full predicted sequences.

        Parameters:
            outputs(Variable): A structure(namedtuple) of tensor variables,
                The structure and data type is same as `output_dtype`.
1419 1420
                The tensor stacks all time steps' output thus has shape
                `[time_step, batch_size, ...]`, which is done by the caller.
G
Guo Sheng 已提交
1421 1422
            final_states(Variable): A structure(namedtuple) of tensor variables.
                It is the `next_states` returned by `decoder.step` at last
T
tianshuo78520a 已提交
1423
                decoding step, thus has the same structure, shape and data type
G
Guo Sheng 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
                with states at any time step.
            sequence_lengths(Variable): An `int64` tensor shaped `[batch_size, beam_size]`.
                It contains sequence lengths for each beam determined during
                decoding.

        Returns:
            tuple: A tuple( :code:`(predicted_ids, final_states)` ). \
                `predicted_ids` is an `int64` tensor shaped \
                `[time_step, batch_size, beam_size]`. `final_states` is the same \
                as the input argument `final_states`.
        """
1435 1436 1437
        predicted_ids = nn.gather_tree(
            outputs.predicted_ids, outputs.parent_ids
        )
G
Guo Sheng 已提交
1438 1439 1440
        # TODO: use FinalBeamSearchDecoderOutput as output
        return predicted_ids, final_states

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
    @property
    def tracks_own_finished(self):
        """
        BeamSearchDecoder reorders its beams and their finished state. Thus it
        conflicts with `dynamic_decode` function's tracking of finished states.
        Setting this property to true to avoid early stopping of decoding due
        to mismanagement of the finished state.

        Returns:
            bool: A python bool `True`.
        """
        return True

G
Guo Sheng 已提交
1454

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
def _dynamic_decode_imperative(
    decoder,
    inits=None,
    max_step_num=None,
    output_time_major=False,
    impute_finished=False,
    is_test=False,
    return_length=False,
    **kwargs
):
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    def _maybe_copy(state, new_state, step_mask):
        # TODO: use where_op
        state_dtype = state.dtype
        if convert_dtype(state_dtype) in ["bool"]:
            state = tensor.cast(state, dtype="float32")
            new_state = tensor.cast(new_state, dtype="float32")
        if step_mask.dtype != state.dtype:
            step_mask = tensor.cast(step_mask, dtype=state.dtype)
            # otherwise, renamed bool gradients of would be summed up leading
            # to sum(bool) error.
            step_mask.stop_gradient = True
        new_state = nn.elementwise_mul(
1477 1478
            state, step_mask, axis=0
        ) - nn.elementwise_mul(new_state, (step_mask - 1), axis=0)
1479 1480 1481
        if convert_dtype(state_dtype) in ["bool"]:
            new_state = tensor.cast(new_state, dtype=state_dtype)
        return new_state
S
swtkiwi 已提交
1482

1483
    initial_inputs, initial_states, initial_finished = decoder.initialize(inits)
1484 1485 1486 1487 1488
    inputs, states, finished = (
        initial_inputs,
        initial_states,
        initial_finished,
    )
1489 1490 1491 1492 1493
    cond = control_flow.logical_not((nn.reduce_all(initial_finished)))
    sequence_lengths = tensor.cast(tensor.zeros_like(initial_finished), "int64")
    outputs = None

    step_idx = 0
1494 1495 1496
    step_idx_tensor = tensor.fill_constant(
        shape=[1], dtype="int64", value=step_idx
    )
1497
    while cond.numpy():
1498 1499 1500
        (step_outputs, next_states, next_inputs, next_finished) = decoder.step(
            step_idx_tensor, inputs, states, **kwargs
        )
1501 1502 1503 1504 1505 1506 1507 1508 1509
        if not decoder.tracks_own_finished:
            # BeamSearchDecoder would track it own finished, since
            # beams would be reordered and the finished status of each
            # entry might change. Otherwise, perform logical OR which
            # would not change the already finished.
            next_finished = control_flow.logical_or(next_finished, finished)
            # To confirm states.finished/finished be consistent with
            # next_finished.
            tensor.assign(next_finished, finished)
J
Jiaqi Liu 已提交
1510 1511
            next_sequence_lengths = nn.elementwise_add(
                sequence_lengths,
1512 1513 1514 1515
                tensor.cast(
                    control_flow.logical_not(finished), sequence_lengths.dtype
                ),
            )
J
Jiaqi Liu 已提交
1516 1517
            if impute_finished:  # rectify the states for the finished.
                next_states = map_structure(
1518 1519 1520 1521
                    lambda x, y: _maybe_copy(x, y, finished),
                    states,
                    next_states,
                )
J
Jiaqi Liu 已提交
1522 1523 1524 1525
        else:
            warnings.warn(
                "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros."
            ) if not hasattr(next_states, "lengths") else None
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
            next_sequence_lengths = getattr(
                next_states, "lengths", sequence_lengths
            )

        outputs = (
            map_structure(lambda x: ArrayWrapper(x), step_outputs)
            if step_idx == 0
            else map_structure(
                lambda x, x_array: x_array.append(x), step_outputs, outputs
            )
        )
        inputs, states, finished, sequence_lengths = (
            next_inputs,
            next_states,
            next_finished,
            next_sequence_lengths,
        )
G
Guo Sheng 已提交
1543

1544 1545
        control_flow.increment(x=step_idx_tensor, value=1.0, in_place=True)
        step_idx += 1
G
Guo Sheng 已提交
1546

1547
        cond = control_flow.logical_not(nn.reduce_all(finished))
1548 1549
        if max_step_num is not None and step_idx > max_step_num:
            break
G
Guo Sheng 已提交
1550

1551 1552
    final_outputs = map_structure(lambda x: nn.stack(x.array, axis=0), outputs)
    final_states = states
G
Guo Sheng 已提交
1553

1554
    try:
1555 1556 1557
        final_outputs, final_states = decoder.finalize(
            final_outputs, final_states, sequence_lengths
        )
1558 1559
    except NotImplementedError:
        pass
G
Guo Sheng 已提交
1560

1561 1562 1563
    if not output_time_major:
        final_outputs = map_structure(
            lambda x: nn.transpose(x, [1, 0] + list(range(2, len(x.shape)))),
1564 1565
            final_outputs,
        )
1566

1567 1568 1569 1570 1571
    return (
        (final_outputs, final_states, sequence_lengths)
        if return_length
        else (final_outputs, final_states)
    )
1572 1573


1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
def _dynamic_decode_declarative(
    decoder,
    inits=None,
    max_step_num=None,
    output_time_major=False,
    impute_finished=False,
    is_test=False,
    return_length=False,
    **kwargs
):
G
Guo Sheng 已提交
1584
    initial_inputs, initial_states, initial_finished = decoder.initialize(inits)
1585 1586 1587 1588 1589
    global_inputs, global_states, global_finished = (
        initial_inputs,
        initial_states,
        initial_finished,
    )
1590
    global_finished.stop_gradient = True
G
Guo Sheng 已提交
1591
    step_idx = tensor.fill_constant(shape=[1], dtype="int64", value=0)
1592

G
Guo Sheng 已提交
1593 1594
    cond = control_flow.logical_not((nn.reduce_all(initial_finished)))
    if max_step_num is not None:
1595 1596 1597
        max_step_num = tensor.fill_constant(
            shape=[1], dtype="int64", value=max_step_num
        )
1598
    while_op = control_flow.While(cond, is_test=is_test)
G
Guo Sheng 已提交
1599 1600

    sequence_lengths = tensor.cast(tensor.zeros_like(initial_finished), "int64")
1601 1602 1603 1604 1605 1606 1607 1608 1609
    sequence_lengths.stop_gradient = True

    if is_test:
        # for test, reuse inputs and states variables to save memory
        inputs = map_structure(lambda x: x, initial_inputs)
        states = map_structure(lambda x: x, initial_states)
    else:
        # inputs and states of all steps must be saved for backward and training
        inputs_arrays = map_structure(
1610 1611
            lambda x: control_flow.array_write(x, step_idx), initial_inputs
        )
1612
        states_arrays = map_structure(
1613 1614
            lambda x: control_flow.array_write(x, step_idx), initial_states
        )
G
Guo Sheng 已提交
1615 1616 1617

    def _maybe_copy(state, new_state, step_mask):
        # TODO: use where_op
1618 1619 1620 1621 1622 1623 1624 1625 1626
        state_dtype = state.dtype
        if convert_dtype(state_dtype) in ["bool"]:
            state = tensor.cast(state, dtype="float32")
            new_state = tensor.cast(new_state, dtype="float32")
        if step_mask.dtype != state.dtype:
            step_mask = tensor.cast(step_mask, dtype=state.dtype)
            # otherwise, renamed bool gradients of would be summed up leading
            # to sum(bool) error.
            step_mask.stop_gradient = True
G
Guo Sheng 已提交
1627
        new_state = nn.elementwise_mul(
1628 1629
            state, step_mask, axis=0
        ) - nn.elementwise_mul(new_state, (step_mask - 1), axis=0)
1630 1631
        if convert_dtype(state_dtype) in ["bool"]:
            new_state = tensor.cast(new_state, dtype=state_dtype)
G
Guo Sheng 已提交
1632 1633 1634 1635 1636
        return new_state

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

1637 1638
    def _create_array_out_of_while(dtype):
        current_block_idx = default_main_program().current_block_idx
1639 1640 1641
        default_main_program().current_block_idx = (
            default_main_program().current_block().parent_idx
        )
1642 1643 1644 1645
        tensor_array = control_flow.create_array(dtype)
        default_main_program().current_block_idx = current_block_idx
        return tensor_array

G
Guo Sheng 已提交
1646 1647
    # While
    with while_op.block():
1648 1649 1650
        if not is_test:
            inputs = map_structure(
                lambda array: control_flow.array_read(array, step_idx),
1651 1652
                inputs_arrays,
            )
1653 1654
            states = map_structure(
                lambda array: control_flow.array_read(array, step_idx),
1655 1656 1657 1658 1659
                states_arrays,
            )
        (outputs, next_states, next_inputs, next_finished) = decoder.step(
            step_idx, inputs, states, **kwargs
        )
1660 1661 1662 1663 1664
        if not decoder.tracks_own_finished:
            # BeamSearchDecoder would track it own finished, since beams would
            # be reordered and the finished status of each entry might change.
            # Otherwise, perform logical OR which would not change the already
            # finished.
1665 1666 1667
            next_finished = control_flow.logical_or(
                next_finished, global_finished
            )
J
Jiaqi Liu 已提交
1668 1669
            next_sequence_lengths = nn.elementwise_add(
                sequence_lengths,
1670 1671 1672 1673 1674
                tensor.cast(
                    control_flow.logical_not(global_finished),
                    sequence_lengths.dtype,
                ),
            )
J
Jiaqi Liu 已提交
1675 1676 1677 1678
            if impute_finished:  # rectify the states for the finished.
                next_states = map_structure(
                    lambda x, y: _maybe_copy(x, y, global_finished),
                    states,
1679 1680
                    next_states,
                )
J
Jiaqi Liu 已提交
1681 1682 1683 1684
        else:
            warnings.warn(
                "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros."
            ) if not hasattr(next_states, "lengths") else None
1685 1686 1687
            next_sequence_lengths = getattr(
                next_states, "lengths", sequence_lengths
            )
1688 1689 1690

        # create tensor array in global block after dtype[s] of outputs can be got
        outputs_arrays = map_structure(
1691 1692
            lambda x: _create_array_out_of_while(x.dtype), outputs
        )
1693

G
Guo Sheng 已提交
1694 1695
        map_structure(
            lambda x, x_array: control_flow.array_write(
1696 1697 1698 1699 1700
                x, i=step_idx, array=x_array
            ),
            outputs,
            outputs_arrays,
        )
G
Guo Sheng 已提交
1701
        control_flow.increment(x=step_idx, value=1.0, in_place=True)
1702 1703 1704 1705
        # update the global_finished first, since it might be also in states of
        # decoder, which otherwise would write a stale finished status to array
        tensor.assign(next_finished, global_finished)
        tensor.assign(next_sequence_lengths, sequence_lengths)
1706 1707 1708 1709 1710 1711
        if is_test:
            map_structure(tensor.assign, next_inputs, global_inputs)
            map_structure(tensor.assign, next_states, global_states)
        else:
            map_structure(
                lambda x, x_array: control_flow.array_write(
1712 1713 1714 1715 1716
                    x, i=step_idx, array=x_array
                ),
                next_inputs,
                inputs_arrays,
            )
1717 1718
            map_structure(
                lambda x, x_array: control_flow.array_write(
1719 1720 1721 1722 1723
                    x, i=step_idx, array=x_array
                ),
                next_states,
                states_arrays,
            )
G
Guo Sheng 已提交
1724 1725
        if max_step_num is not None:
            control_flow.logical_and(
1726
                control_flow.logical_not(nn.reduce_all(global_finished)),
1727 1728 1729
                control_flow.less_equal(step_idx, max_step_num),
                cond,
            )
G
Guo Sheng 已提交
1730
        else:
1731
            control_flow.logical_not(nn.reduce_all(global_finished), cond)
G
Guo Sheng 已提交
1732 1733 1734

    final_outputs = map_structure(
        lambda array: tensor.tensor_array_to_tensor(
1735 1736 1737 1738
            array, axis=0, use_stack=True
        )[0],
        outputs_arrays,
    )
1739 1740 1741 1742 1743
    if is_test:
        final_states = global_states
    else:
        final_states = map_structure(
            lambda array: control_flow.array_read(array, step_idx),
1744 1745
            states_arrays,
        )
G
Guo Sheng 已提交
1746 1747

    try:
1748 1749 1750
        final_outputs, final_states = decoder.finalize(
            final_outputs, final_states, sequence_lengths
        )
G
Guo Sheng 已提交
1751 1752 1753 1754 1755 1756
    except NotImplementedError:
        pass

    if not output_time_major:
        final_outputs = map_structure(_transpose_batch_time, final_outputs)

1757 1758 1759 1760 1761
    return (
        (final_outputs, final_states, sequence_lengths)
        if return_length
        else (final_outputs, final_states)
    )
1762 1763


1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
def dynamic_decode(
    decoder,
    inits=None,
    max_step_num=None,
    output_time_major=False,
    impute_finished=False,
    is_test=False,
    return_length=False,
    **kwargs
):
1774
    r"""
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
    Dynamic decoding performs :code:`decoder.step()` repeatedly until the returned
    Tensor indicating finished status contains all True values or the number of
    decoding step reaches to :attr:`max_step_num`.

    :code:`decoder.initialize()` would be called once before the decoding loop.
    If the `decoder` has implemented `finalize` method, :code:`decoder.finalize()`
    would be called once after the decoding loop.

    Parameters:
        decoder(Decoder): An instance of `Decoder`.
1785
        inits(object, optional): Argument passed to `decoder.initialize`.
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
            Default `None`.
        max_step_num(int, optional): The maximum number of steps. If not provided,
            decode until the decoder is fully done, or in other words, the returned
            Tensor by :code:`decoder.step()` indicating finished status contains
            all True. Default `None`.
        output_time_major(bool, optional): Indicate the data layout of Tensor included
            in the final outputs(the first returned value of this method). If
            attr:`False`, the data layout would be batch major with shape
            `[batch_size, seq_len, ...]`.  If attr:`True`, the data layout would
            be time major with shape `[seq_len, batch_size, ...]`. Default: `False`.
J
Jiaqi Liu 已提交
1796 1797 1798 1799 1800 1801 1802
        impute_finished(bool, optional): If `True` and `decoder.tracks_own_finished`
            is False, then states get copied through for batch entries which are
            marked as finished, which differs with the unfinished using the new states
            returned by :code:`decoder.step()` and ensures that the final states have
            the correct values. Otherwise, states wouldn't be copied through when
            finished. If the returned `final_states` is needed, it should be set as
            True, which causes some slowdown. Default `False`.
1803 1804 1805 1806 1807
        is_test(bool, optional): A flag indicating whether to use test mode. In
            test mode, it is more memory saving. Default `False`.
        return_length(bool, optional):  A flag indicating whether to return an
            extra Tensor variable in the output tuple, which stores the actual
            lengths of all decoded sequences. Default `False`.
1808
        **kwargs: Additional keyword arguments. Arguments passed to `decoder.step`.
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823

    Returns:
        tuple: A tuple( :code:`(final_outputs, final_states, sequence_lengths)` ) \
            when `return_length` is True, otherwise a tuple( :code:`(final_outputs, final_states)` ). \
            The final outputs and states, both are Tensor or nested structure of Tensor. \
            `final_outputs` has the same structure and data types as the :code:`outputs` \
            returned by :code:`decoder.step()` , and each Tenser in `final_outputs` \
            is the stacked of all decoding steps' outputs, which might be revised \
            by :code:`decoder.finalize()` if the decoder has implemented `finalize`. \
            `final_states` is the counterpart at last time step of initial states \
            returned by :code:`decoder.initialize()` , thus has the same structure \
            with it and has tensors with same shapes and data types. `sequence_lengths` \
            is an `int64` tensor with the same shape as `finished` returned \
            by :code:`decoder.initialize()` , and it stores the actual lengths of \
            all decoded sequences.
1824

1825 1826 1827 1828

    Examples:

        .. code-block:: python
1829

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
            import numpy as np
            import paddle
            from paddle.nn import BeamSearchDecoder, dynamic_decode
            from paddle.nn import GRUCell, Linear, Embedding
            trg_embeder = Embedding(100, 32)
            output_layer = Linear(32, 32)
            decoder_cell = GRUCell(input_size=32, hidden_size=32)
            decoder = BeamSearchDecoder(decoder_cell,
                                        start_token=0,
                                        end_token=1,
                                        beam_size=4,
                                        embedding_fn=trg_embeder,
                                        output_fn=output_layer)
            encoder_output = paddle.ones((4, 8, 32), dtype=paddle.get_default_dtype())
            outputs = dynamic_decode(decoder=decoder,
                                    inits=decoder_cell.get_initial_states(encoder_output),
                                    max_step_num=10)
    """
J
Jiabin Yang 已提交
1848
    if _non_static_mode():
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
        return _dynamic_decode_imperative(
            decoder,
            inits,
            max_step_num,
            output_time_major,
            impute_finished,
            is_test,
            return_length,
            **kwargs
        )
1859
    else:
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
        return _dynamic_decode_declarative(
            decoder,
            inits,
            max_step_num,
            output_time_major,
            impute_finished,
            is_test,
            return_length,
            **kwargs
        )
1870 1871


1872
class DecodeHelper:
1873 1874 1875 1876 1877 1878 1879
    """
    DecodeHelper is the base class for any helper instance used in `BasicDecoder`.
    It provides interface to implement sampling and produce inputs for the next
    time step in dynamic decoding.
    """

    def initialize(self):
1880
        r"""
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
        DecodeHelper initialization to produce inputs for the first decoding step
        and give the initial status telling whether each sequence in the batch
        is finished. It is the partial of the initialization of `BasicDecoder`.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \
                `initial_inputs` is a (possibly nested structure of) tensor \
                variable[s], and the tensor's shape is `[batch_size, ...]`. \
                `initial_finished` is a bool tensor with shape `[batch_size]`.
        """
        pass

    def sample(self, time, outputs, states):
        """
        Perform sampling with some strategies according to `outputs`. It is the
        partial of `BasicDecoder.step`.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the caller,
                representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.

        Returns:
            Variable: An `int64` tensor representing the sampled ids.
        """
        pass

    def next_inputs(self, time, outputs, states, sample_ids):
1914
        r"""
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
        Produce the inputs and states for next time step and give status telling
        whether each minibatch entry is finished. It is called after `sample` in
        `BasicDecoder.step`. It is the partial of `BasicDecoder.step`.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the caller,
                representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.
            sample_ids(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `sample_ids` returned by `sample()`.

        Returns:
            tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \
                `next_inputs` and `next_states` both are a (possibly nested \
                structure of) tensor variable[s], and the structure, shape and \
                data type of `next_states` must be same as the input argument \
                `states`. `finished` is a bool tensor with shape `[batch_size]`.
        """
        pass


class TrainingHelper(DecodeHelper):
    """
    TrainingHelper is a subclass of DecodeHelper. It is a decoding helper
    slicing from the full sequence inputs as the inputs for corresponding
    step. And it uses `argmax` to sample from the outputs of `cell.call()`.

    Since the needs of sequence inputs, it is used mostly for teach-forcing MLE
    (maximum likelihood) training, and the sampled would not be used.

    Examples:
        .. code-block:: python
1952

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
            import paddle.fluid as fluid
            import paddle.fluid.layers as layers
            trg_emb = fluid.data(name="trg_emb",
                                 shape=[None, None, 128],
                                 dtype="float32")
            trg_seq_length = fluid.data(name="trg_seq_length",
                                        shape=[None],
                                        dtype="int64")
            helper = layers.TrainingHelper(trg_emb, trg_seq_length)
            decoder_cell = layers.GRUCell(hidden_size=128)
            decoder = layers.BasicDecoder(decoder_cell, helper)
            outputs = layers.dynamic_decode(
                decoder,
                inits=decoder_cell.get_initial_states(trg_emb),
                is_test=False)
    """

    def __init__(self, inputs, sequence_length, time_major=False):
        """
        Constructor of TrainingHelper.

        Parameters:
1975
            inputs(Variable): A (possibly nested structure of) tensor variable[s].
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
                The shape of tensor should be `[batch_size, sequence_length, ...]`
                for `time_major == False` or `[sequence_length, batch_size, ...]`
                for `time_major == True`. It represents the inputs to be sliced
                from at every decoding step.
            sequence_length(Variable): A tensor with shape `[batch_size]`.
                It stores real length of each instance in `inputs`, by which we
                can label the finished status of each instance at every decoding
                step.
            time_major(bool, optional): Indicate the data layout of Tensor included
                in `inputs`. If `False`, the data layout would be batch major with
                shape `[batch_size, sequence_length, ...]`.  If `True`, the data
                layout would be time major with shape `[sequence_length, batch_size, ...]`.
                Default: `False`.
        """
        self.inputs = inputs
        self.sequence_length = sequence_length
        self.time_major = time_major
        # extend inputs to avoid to slice out of range in `next_inputs`
        # may be easier and have better performance than condition_op
        self.inputs_ = map_structure(
1996 1997 1998 1999 2000 2001 2002 2003
            lambda x: nn.pad(
                x,
                paddings=([0, 1] + [0, 0] * (len(x.shape) - 1))
                if time_major
                else ([0, 0, 0, 1] + [0, 0] * (len(x.shape) - 2)),
            ),
            self.inputs,
        )
2004 2005

    def initialize(self):
2006
        r"""
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
        TrainingHelper initialization produces inputs for the first decoding
        step by slicing at the first time step of full sequence inputs, and it
        gives initial status telling whether each sequence in the batch is
        finished. It is the partial of the initialization of `BasicDecoder`.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \
                `initial_inputs` is a (possibly nested structure of) tensor \
                variable[s], and the tensor's shape is `[batch_size, ...]`. \
                `initial_finished` is a bool tensor with shape `[batch_size]`.
        """
        init_finished = control_flow.equal(
            self.sequence_length,
2020 2021 2022 2023
            tensor.fill_constant(
                shape=[1], dtype=self.sequence_length.dtype, value=0
            ),
        )
2024 2025
        # TODO: support zero length
        init_inputs = map_structure(
2026 2027
            lambda x: x[0] if self.time_major else x[:, 0], self.inputs
        )
2028 2029 2030
        return init_inputs, init_finished

    def sample(self, time, outputs, states):
2031
        r"""
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
        Perform sampling by using `argmax` according to the `outputs`. Mostly
        the sampled ids would not be used since the inputs for next decoding
        step would be got by slicing.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the
                caller, representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
2042
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.

        Returns:
            Variable: An `int64` tensor with shape `[batch_size]`, representing \
                the sampled ids.
        """
        sample_ids = tensor.argmax(outputs, axis=-1)
        return sample_ids

    def next_inputs(self, time, outputs, states, sample_ids):
2054
        r"""
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
        Generate inputs for the next decoding step by slicing at corresponding
        step of the full sequence inputs. Simultaneously, produce the states
        for next time step by directly using the input `states` and emit status
        telling whether each minibatch entry reaches to the corresponding length.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the
                caller, representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.
            sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`.
                It is same as `sample_ids` returned by `sample()`.

        Returns:
            tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \
                `next_inputs` and `next_states` both are a (possibly nested \
                structure of) tensor variable[s],  and the tensor's shape is \
                `[batch_size, ...]`. `next_states` is identical to the input \
                argument `states`. `finished` is a `bool` Tensor with \
                shape `[batch_size]`.
        """
        # TODO: compatibility of int32 and int64
2081 2082 2083 2084 2085
        time = (
            tensor.cast(time, "int32")
            if convert_dtype(time.dtype) not in ["int32"]
            else time
        )
2086 2087 2088 2089 2090 2091 2092
        if self.sequence_length.dtype != time.dtype:
            self.sequence_length = tensor.cast(self.sequence_length, time.dtype)
        next_time = time + 1
        finished = control_flow.less_equal(self.sequence_length, next_time)

        def _slice(x):  # TODO: use Variable.__getitem__
            axes = [0 if self.time_major else 1]
2093 2094 2095 2096 2097 2098
            return nn.squeeze(
                nn.slice(
                    x, axes=axes, starts=[next_time], ends=[next_time + 1]
                ),
                axes=axes,
            )
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

        next_inputs = map_structure(_slice, self.inputs_)
        return finished, next_inputs, states


class GreedyEmbeddingHelper(DecodeHelper):
    """
    GreedyEmbeddingHelper is a subclass of DecodeHelper. It is a decoding helper
    uses the argmax of the output (treated as logits) and passes the results
    through an embedding layer to get inputs for the next decoding step.

    Examples:
        .. code-block:: python
2112

2113 2114 2115 2116 2117
            import paddle.fluid as fluid
            import paddle.fluid.layers as layers
            trg_emb = fluid.data(name="trg_emb",
                                 shape=[None, None, 128],
                                 dtype="float32")
2118

2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
            trg_embeder = lambda x: fluid.embedding(
                x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding"))
            output_layer = lambda x: layers.fc(x,
                                            size=10000,
                                            num_flatten_dims=len(x.shape) - 1,
                                            param_attr=fluid.ParamAttr(name=
                                                                    "output_w"),
                                            bias_attr=False)
            helper = layers.GreedyEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1)
            decoder_cell = layers.GRUCell(hidden_size=128)
            decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer)
            outputs = layers.dynamic_decode(
                decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output))
    """

    def __init__(self, embedding_fn, start_tokens, end_token):
2135
        r"""
2136 2137 2138
        Constructor of GreedyEmbeddingHelper.

        Parameters:
2139
            embedding_fn(callable): A functor to apply on the argmax results.
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
                Mostly it is an embedding layer to transform ids to embeddings.
                **Note that fluid.embedding should be used here rather than
                fluid.layers.embedding, since shape of ids is [batch_size].
                when using fluid.layers.embedding, must unsqueeze in embedding_fn.**
            start_tokens(Variable):  A `int64` tensor shaped `[batch_size]`,
                representing the start tokens.
            end_token(int): The end token id.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
                `initial_inputs` and `initial_states` both are a (possibly nested \
                structure of) tensor variable[s], and `finished` is a tensor with \
                bool data type.
        """
        self.embedding_fn = embedding_fn
        self.start_tokens = start_tokens
2156 2157 2158
        self.end_token = tensor.fill_constant(
            shape=[1], dtype="int64", value=end_token
        )
2159 2160

    def initialize(self):
2161
        r"""
2162 2163
        GreedyEmbeddingHelper initialization produces inputs for the first decoding
        step by using `start_tokens` of the constructor, and gives initial
2164
        status telling whether each sequence in the batch is finished.
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
        It is the partial of the initialization of `BasicDecoder`.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \
                `initial_inputs` is same as `start_tokens` of the constructor. \
                `initial_finished` is a `bool` tensor filled by False and has \
                the same shape as `start_tokens`.
        """
        # TODO: remove the restriction of force_cpu
        init_finished = tensor.fill_constant_batch_size_like(
            input=self.start_tokens,
            shape=[-1],
            dtype="bool",
            value=False,
2179 2180
            force_cpu=True,
        )
2181 2182 2183 2184
        init_inputs = self.embedding_fn(self.start_tokens)
        return init_inputs, init_finished

    def sample(self, time, outputs, states):
2185
        r"""
2186 2187 2188 2189 2190 2191 2192 2193
        Perform sampling by using `argmax` according to the `outputs`.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the
                caller, representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
2194
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.

        Returns:
            Variable: An `int64` tensor with shape `[batch_size]`, representing \
                the sampled ids.
        """
        sample_ids = tensor.argmax(outputs, axis=-1)
        return sample_ids

    def next_inputs(self, time, outputs, states, sample_ids):
2206
        r"""
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
        Generate inputs for the next decoding step by applying `embedding_fn`
        to `sample_ids`. Simultaneously, produce the states for next time step
        by directly using the input `states` and emit status telling whether
        each minibatch entry gets an `end_token` sample.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the
                caller, representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.
            sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`.
                It is same as `sample_ids` returned by `sample()`.

        Returns:
            tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \
                `next_inputs` and `next_states` both are a (possibly nested \
                structure of) tensor variable[s],  and the tensor's shape is \
                `[batch_size, ...]`. `next_states` is identical to the input \
                argument `states`. `finished` is a `bool` Tensor with \
                shape `[batch_size]`.
        """
        finished = control_flow.equal(sample_ids, self.end_token)
        next_inputs = self.embedding_fn(sample_ids)
        return finished, next_inputs, states


class SampleEmbeddingHelper(GreedyEmbeddingHelper):
    """
    SampleEmbeddingHelper is a subclass of GreedyEmbeddingHelper. It is a decoding
    helper uses sampling (from a distribution) instead of argmax of the output
    (treated as logits) and passes the results through an embedding layer to get
    inputs for the next decoding step.

    Examples:
        .. code-block:: python
2246

2247 2248 2249 2250 2251
            import paddle.fluid as fluid
            import paddle.fluid.layers as layers
            trg_emb = fluid.data(name="trg_emb",
                                 shape=[None, None, 128],
                                 dtype="float32")
2252

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
            trg_embeder = lambda x: fluid.embedding(
                x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding"))
            output_layer = lambda x: layers.fc(x,
                                            size=10000,
                                            num_flatten_dims=len(x.shape) - 1,
                                            param_attr=fluid.ParamAttr(name=
                                                                    "output_w"),
                                            bias_attr=False)
            helper = layers.SampleEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1)
            decoder_cell = layers.GRUCell(hidden_size=128)
            decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer)
            outputs = layers.dynamic_decode(
                decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output))
    """

2268 2269 2270 2271 2272 2273 2274 2275
    def __init__(
        self,
        embedding_fn,
        start_tokens,
        end_token,
        softmax_temperature=None,
        seed=None,
    ):
2276
        r"""
2277 2278 2279
        Constructor of SampleEmbeddingHelper.

        Parameters:
2280
            embedding_fn(callable): A functor to apply on the argmax results.
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
                Mostly it is an embedding layer to transform ids to embeddings.
                **Note that fluid.embedding should be used here rather than
                fluid.layers.embedding, since shape of ids is [batch_size].
                when using fluid.layers.embedding, must unsqueeze in embedding_fn.**
            start_tokens(Variable):  A `int64` tensor shaped `[batch_size]`,
                representing the start tokens.
            end_token(int): The end token id.
            softmax_temperature(float, optional): the value to divide the logits
                by before computing the softmax. Higher temperatures (above 1.0)
                lead to more random, while lower temperatures push the sampling
                distribution towards the argmax. It must be strictly greater than
                0. Defaults to None, meaning using a temperature valued 1.0.
            seed: (int, optional) The sampling seed. Defaults to None, meaning not
                to use fixed seed.

        Returns:
            tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
                `initial_inputs` and `initial_states` both are a (possibly nested \
                structure of) tensor variable[s], and `finished` is a tensor with \
                bool data type.
        """
2302
        super().__init__(embedding_fn, start_tokens, end_token)
2303 2304 2305 2306 2307 2308 2309
        self.softmax_temperature = (
            tensor.fill_constant(
                shape=[1], dtype="float32", value=softmax_temperature
            )
            if softmax_temperature is not None
            else None
        )
2310 2311 2312
        self.seed = seed

    def sample(self, time, outputs, states):
2313
        r"""
2314 2315 2316 2317 2318 2319 2320 2321 2322
        Perform sampling from a categorical distribution, and the distribution
        is computed by `softmax(outputs/softmax_temperature)`.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the
                caller, representing the current time step number of decoding.
            outputs(Variable): A tensor variable. Usually it's data type is float32
                or float64, and it's shape is `[batch_size, vocabulary_size]`,
                representing the predicted logits of current step. It is same as
2323
                `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`.
2324 2325 2326 2327 2328 2329 2330
            states(Variable): A (possibly nested structure of) tensor variable[s].
                It is same as `new_states` returned by `BasicDecoder.cell.call()`.

        Returns:
            Variable: An `int64` tensor with shape `[batch_size]`, representing \
                the sampled ids.
        """
2331 2332 2333 2334 2335
        logits = (
            (outputs / self.softmax_temperature)
            if self.softmax_temperature is not None
            else outputs
        )
2336 2337 2338 2339 2340
        probs = nn.softmax(logits)
        # TODO: remove this stop_gradient. The stop_gradient of sample_ids can
        # not pass to probs, since sampling_id op does not have corresponding
        # grad op and thus can not pass.
        probs.stop_gradient = True
2341 2342 2343
        sample_ids = nn.sampling_id(
            probs, seed=self.seed, dtype=self.start_tokens.dtype
        )
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
        return sample_ids


class BasicDecoder(Decoder):
    """
    BasicDecoder is a subclass of Decoder and assembles a RNNCell and DecodeHelper
    instance as members, where the DecodeHelper helps to implement customed
    decoding strategies.. It performs one decoding step as following steps:

    1. Perform `cell_outputs, cell_states = cell.call(inputs, states)`
    to get outputs and new states from cell.

    2. Perform `sample_ids = helper.sample(time, cell_outputs, cell_states)`
    to sample ids as decoded results of the current time step.

    3. Perform `finished, next_inputs, next_states = helper.next_inputs(time,
    cell_outputs, cell_states, sample_ids)` to generate inputs, states and
    finished status for the next decoding step.

    Examples:
        .. code-block:: python
2365

2366 2367 2368 2369 2370
            import paddle.fluid as fluid
            import paddle.fluid.layers as layers
            trg_emb = fluid.data(name="trg_emb",
                                 shape=[None, None, 128],
                                 dtype="float32")
2371

2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
            trg_embeder = lambda x: fluid.embedding(
                x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding"))
            output_layer = lambda x: layers.fc(x,
                                            size=10000,
                                            num_flatten_dims=len(x.shape) - 1,
                                            param_attr=fluid.ParamAttr(name=
                                                                    "output_w"),
                                            bias_attr=False)
            helper = layers.SampleEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1)
            decoder_cell = layers.GRUCell(hidden_size=128)
            decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer)
            outputs = layers.dynamic_decode(
                decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output))
    """

    def __init__(self, cell, helper, output_fn=None):
        """
        Constructor of BasicDecoder.

        Parameters:
            cell(RNNCell): An instance of `RNNCell` or object with the same interface.
            helper(DecodeHelper): An instance of `DecodeHelper`.
            output_fn(optional): A callable to apply to the cell's output prior to
                sampling. Default None.
        """
        self.cell = cell
        self.helper = helper
        self.output_fn = output_fn

    def initialize(self, initial_cell_states):
2402
        r"""
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
        BasicDecoder initialization includes helper initialization and cell
        initialization, and cell initialization uses `initial_cell_states` as
        the result directly.

        Parameters:
            initial_cell_states(Variable): A (possibly nested structure of)
                tensor variable[s]. An argument provided by the caller `dynamic_decode`.

        Returns:
            tuple: A tuple( :code:(initial_inputs, initial_cell_states, finished)` ). \
                `initial_inputs` and `initial_states` both are a (possibly nested \
                structure of) tensor variable[s], and `finished` is a tensor with \
                bool data type. `initial_inputs` and `finished` are the results \
                of `helper.initialize()`, and `initial_cell_states` is same as \
                the input argument counterpart.
        """
        (initial_inputs, initial_finished) = self.helper.initialize()
        return initial_inputs, initial_cell_states, initial_finished

    class OutputWrapper(
2423 2424
        collections.namedtuple("OutputWrapper", ("cell_outputs", "sample_ids"))
    ):
2425 2426 2427 2428
        """
        The structure for the returned value `outputs` of `decoder.step`.
        A namedtuple includes cell_outputs, sample_ids as fields.
        """
2429

2430 2431 2432
        pass

    def step(self, time, inputs, states, **kwargs):
2433
        r"""
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
        Perform one decoding step as following steps:

        1. Perform `cell_outputs, cell_states = cell.call(inputs, states)`
        to get outputs and new states from cell.

        2. Perform `sample_ids = helper.sample(time, cell_outputs, cell_states)`
        to sample ids as decoded results of the current time step.

        3. Perform `finished, next_inputs, next_states = helper.next_inputs(time,
        cell_outputs, cell_states, sample_ids)` to generate inputs, states and
        finished status for the next decoding step.

        Parameters:
            time(Variable): An `int64` tensor with shape `[1]` provided by the caller,
                representing the current time step number of decoding.
            inputs(Variable): A tensor variable. It is same as `initial_inputs`
                returned by `initialize()` for the first decoding step and
                `next_inputs` returned by `step()` for the others.
            states(Variable): A structure of tensor variables.
                It is same as the `initial_cell_states` returned by `initialize()`
                for the first decoding step and `next_states` returned by
                `step()` for the others.
            **kwargs: Additional keyword arguments, provided by the caller
2457 2458
                `dynamic_decode`.

2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
        Returns:
            tuple: A tuple( :code:`(outputs, next_states, next_inputs, finished)` ). \
                `outputs` is a namedtuple(including cell_outputs, sample_ids, \
                as fields) of tensor variables, where `cell_outputs` is the result \
                fof `cell.call()` and `sample_ids` is the result of `helper.sample()`. \
                `next_states` and `next_inputs` have the same structure, shape \
                and data type as the input arguments `states` and `inputs` separately. \
                `finished` is a `bool` tensor with shape `[batch_size]`.
        """
        cell_outputs, cell_states = self.cell(inputs, states, **kwargs)
        if self.output_fn is not None:
            cell_outputs = self.output_fn(cell_outputs)
2471 2472 2473
        sample_ids = self.helper.sample(
            time=time, outputs=cell_outputs, states=cell_states
        )
2474
        sample_ids.stop_gradient = True
2475 2476 2477 2478 2479 2480
        (finished, next_inputs, next_states) = self.helper.next_inputs(
            time=time,
            outputs=cell_outputs,
            states=cell_states,
            sample_ids=sample_ids,
        )
2481 2482
        outputs = self.OutputWrapper(cell_outputs, sample_ids)
        return (outputs, next_states, next_inputs, finished)
2483 2484


2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
def dynamic_lstm(
    input,
    size,
    h_0=None,
    c_0=None,
    param_attr=None,
    bias_attr=None,
    use_peepholes=True,
    is_reverse=False,
    gate_activation='sigmoid',
    cell_activation='tanh',
    candidate_activation='tanh',
    dtype='float32',
    name=None,
):
2500
    r"""
2501
	:api_attr: Static Graph
S
swtkiwi 已提交
2502

2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
    **Note**:
        1. This OP only supports LoDTensor as inputs. If you need to deal with Tensor, please use :ref:`api_fluid_layers_lstm` .
        2. In order to improve efficiency, users must first map the input of dimension [T, hidden_size] to input of [T, 4 * hidden_size], and then pass it to this OP.

    The implementation of this OP include diagonal/peephole connections.
    Please refer to `Gers, F. A., & Schmidhuber, J. (2000) <ftp://ftp.idsia.ch/pub/juergen/TimeCount-IJCNN2000.pdf>`_ .
    If you do not need peephole connections, please set use_peepholes to False .

    This OP computes each timestep as follows:

    .. math::
      i_t = \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_{x_i} + b_{h_i})
    .. math::
      f_t = \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_{x_f} + b_{h_f})
    .. math::
      o_t = \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_{x_o} + b_{h_o})
    .. math::
      \widetilde{c_t} = tanh(W_{cx}x_t + W_{ch}h_{t-1} + b{x_c} + b_{h_c})
    .. math::
      c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t}
    .. math::
      h_t = o_t \odot tanh(c_t)

    The symbolic meanings in the formula are as follows:

    - :math:`x_{t}` represents the input at timestep :math:`t`
    - :math:`h_{t}` represents the hidden state at timestep :math:`t`
    - :math:`h_{t-1}, c_{t-1}` represent the hidden state and cell state at timestep :math:`t-1` , respectively
    - :math:`\widetilde{c_t}` represents the candidate cell state
    - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively
    - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` )
    - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate)
    - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid
    - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension

    Parameters:
        input ( :ref:`api_guide_Variable_en` ): LSTM input tensor, multi-dimensional LODTensor of shape :math:`[T, 4*hidden\_size]` . Data type is float32 or float64.
        size (int): must be 4 * hidden_size.
        h_0( :ref:`api_guide_Variable_en` , optional): The initial hidden state of the LSTM, multi-dimensional Tensor of shape :math:`[batch\_size, hidden\_size]` .
                       Data type is float32 or float64. If set to None, it will be a vector of all 0. Default: None.
        c_0( :ref:`api_guide_Variable_en` , optional): The initial hidden state of the LSTM, multi-dimensional Tensor of shape :math:`[batch\_size, hidden\_size]` .
                       Data type is float32 or float64. If set to None, it will be a vector of all 0. `h_0` and `c_0` can be None but only at the same time. Default: None.
        param_attr(ParamAttr, optional): Parameter attribute of weight. If it is None, the default weight parameter attribute is used. Please refer to ref:`api_fluid_ParamAttr' .
                              If the user needs to set this parameter, the dimension must be :math:`[hidden\_size, 4*hidden\_size]` . Default: None.

                              - Weights = :math:`\{ W_{cr},W_{ir},W_{fr},W_{or} \}` , the shape is [hidden_size, 4*hidden_size].

        bias_attr (ParamAttr, optional): The bias attribute for the learnable bias
                              weights, which contains two parts, input-hidden
                              bias weights and peephole connections weights if
                              setting `use_peepholes` to `True`.
                              Please refer to ref:`api_fluid_ParamAttr' . Default: None.

                              1. `use_peepholes = False`
                                 - Biases = {:math:`b_c, b_i, b_f, b_o`}.
                                 - The shape is [1, 4*hidden_size].
                              2. `use_peepholes = True`
                                 - Biases = { :math:`b_c, b_i, b_f, b_o, W_{ic}, \
                                                 W_{fc}, W_{oc}`}.
                                 - The shape is [1, 7*hidden_size].
2563

2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
        use_peepholes (bool, optional): Whether to use peephole connection or not. Default: True.
        is_reverse (bool, optional): Whether to calculate reverse LSTM. Default: False.
        gate_activation (str, optional): The activation for input gate, forget gate and output gate. Default: "sigmoid".
        cell_activation (str, optional): The activation for cell output. Default: "tanh".
        candidate_activation (str, optional): The activation for candidate hidden state. Default: "tanh".
        dtype (str, optional): Data type, can be "float32" or "float64". Default: "float32".
        name (str, optional): A name for this layer. Please refer to :ref:`api_guide_Name` . Default: None.

    Returns:
        tuple ( :ref:`api_guide_Variable` , :ref:`api_guide_Variable` ) :

            The hidden state and cell state of LSTM

                - hidden: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input.
                - cell: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input.

    Examples:
        .. code-block:: python
2582

2583 2584 2585 2586
            import paddle.fluid as fluid
            emb_dim = 256
            vocab_size = 10000
            hidden_dim = 512
2587

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
            data = fluid.data(name='x', shape=[None], dtype='int64', lod_level=1)
            emb = fluid.embedding(input=data, size=[vocab_size, emb_dim], is_sparse=True)

            forward_proj = fluid.layers.fc(input=emb, size=hidden_dim * 4,
                                           bias_attr=False)

            forward, cell = fluid.layers.dynamic_lstm(
                input=forward_proj, size=hidden_dim * 4, use_peepholes=False)
            forward.shape  # (-1, 512)
            cell.shape  # (-1, 512)
    """
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
    assert (
        _non_static_mode() is not True
    ), "please use lstm instead of dynamic_lstm in dygraph mode!"
    assert (
        bias_attr is not False
    ), "bias_attr should not be False in dynamic_lstm."

    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'dynamic_lstm'
    )
2609 2610 2611

    check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_lstm')
    if isinstance(h_0, Variable):
2612 2613 2614
        check_variable_and_dtype(
            h_0, 'h_0', ['float32', 'float64'], 'dynamic_lstm'
        )
2615 2616 2617

    check_type(c_0, 'c_0', (Variable, type(None)), 'dynamic_lstm')
    if isinstance(c_0, Variable):
2618 2619 2620
        check_variable_and_dtype(
            c_0, 'c_0', ['float32', 'float64'], 'dynamic_lstm'
        )
2621

2622 2623
    helper = LayerHelper('lstm', **locals())
    size = size // 4
2624 2625 2626
    weight = helper.create_parameter(
        attr=helper.param_attr, shape=[size, 4 * size], dtype=dtype
    )
2627 2628 2629
    bias_size = [1, 7 * size]
    if not use_peepholes:
        bias_size[1] = 4 * size
2630 2631 2632
    bias = helper.create_parameter(
        attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True
    )
2633 2634 2635 2636 2637 2638 2639 2640

    hidden = helper.create_variable_for_type_inference(dtype)
    cell = helper.create_variable_for_type_inference(dtype)
    batch_gate = helper.create_variable_for_type_inference(dtype)
    batch_cell_pre_act = helper.create_variable_for_type_inference(dtype)
    inputs = {'Input': input, 'Weight': weight, 'Bias': bias}
    batch_size = input.shape[0]
    if h_0:
2641
        assert h_0.shape == (batch_size, size), (
2642
            'The shape of h0 should be (batch_size, %d)' % size
2643
        )
2644 2645
        inputs['H0'] = h_0
    if c_0:
2646
        assert c_0.shape == (batch_size, size), (
2647
            'The shape of c0 should be (batch_size, %d)' % size
2648
        )
2649 2650
        inputs['C0'] = c_0

2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
    helper.append_op(
        type='lstm',
        inputs=inputs,
        outputs={
            'Hidden': hidden,
            'Cell': cell,
            'BatchGate': batch_gate,
            'BatchCellPreAct': batch_cell_pre_act,
        },
        attrs={
            'use_peepholes': use_peepholes,
            'is_reverse': is_reverse,
            'gate_activation': gate_activation,
            'cell_activation': cell_activation,
            'candidate_activation': candidate_activation,
        },
    )
2668 2669 2670
    return hidden, cell


2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
@deprecated(
    since='2.0.0',
    update_to='paddle.nn.LSTM',
    reason="This API may occur CUDNN errors.",
)
def lstm(
    input,
    init_h,
    init_c,
    max_len,
    hidden_size,
    num_layers,
    dropout_prob=0.0,
    is_bidirec=False,
    is_test=False,
    name=None,
    default_initializer=None,
    seed=-1,
):
2690
    r"""
2691
	:api_attr: Static Graph
S
swtkiwi 已提交
2692

2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
    **Note**:
        This OP only supports running on GPU devices.

    This OP implements LSTM operation - `Hochreiter, S., & Schmidhuber, J. (1997) <http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf>`_ .

    The implementation of this OP does not include diagonal/peephole connections.
    Please refer to `Gers, F. A., & Schmidhuber, J. (2000) <ftp://ftp.idsia.ch/pub/juergen/TimeCount-IJCNN2000.pdf>`_ .
    If you need peephole connections, please use :ref:`api_fluid_layers_dynamic_lstm` .

    This OP computes each timestep as follows:

    .. math::
      i_t = \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_{x_i} + b_{h_i})
    .. math::
      f_t = \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_{x_f} + b_{h_f})
    .. math::
      o_t = \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_{x_o} + b_{h_o})
    .. math::
      \widetilde{c_t} = tanh(W_{cx}x_t + W_{ch}h_{t-1} + b{x_c} + b_{h_c})
    .. math::
      c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t}
    .. math::
      h_t = o_t \odot tanh(c_t)

    The symbolic meanings in the formula are as follows:

    - :math:`x_{t}` represents the input at timestep :math:`t`
    - :math:`h_{t}` represents the hidden state at timestep :math:`t`
    - :math:`h_{t-1}, c_{t-1}` represent the hidden state and cell state at timestep :math:`t-1` , respectively
    - :math:`\widetilde{c_t}` represents the candidate cell state
    - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively
    - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` )
    - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate)
    - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid
    - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension

    Parameters:
        input ( :ref:`api_guide_Variable_en` ): LSTM input tensor, 3-D Tensor of shape :math:`[batch\_size, seq\_len, input\_dim]` . Data type is float32 or float64
        init_h( :ref:`api_guide_Variable_en` ): The initial hidden state of the LSTM, 3-D Tensor of shape :math:`[num\_layers, batch\_size, hidden\_size]` .
                       If is_bidirec = True, shape should be :math:`[num\_layers*2, batch\_size, hidden\_size]` . Data type is float32 or float64.
G
GaoWei8 已提交
2733
        max_len (int): This parameter has no effect and will be discarded.
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
        init_c( :ref:`api_guide_Variable_en` ): The initial cell state of the LSTM, 3-D Tensor of shape :math:`[num\_layers, batch\_size, hidden\_size]` .
                       If is_bidirec = True, shape should be :math:`[num\_layers*2, batch\_size, hidden\_size]` . Data type is float32 or float64.
        hidden_size (int): hidden size of the LSTM.
        num_layers (int): total layers number of the LSTM.
        dropout_prob(float, optional): dropout prob, dropout ONLY work between rnn layers, NOT between time steps
                             There is NO dropout work on rnn output of the last RNN layers.
                             Default: 0.0.
        is_bidirec (bool, optional): If it is bidirectional. Default: False.
        is_test (bool, optional): If it is in test phrase. Default: False.
        name (str, optional): A name for this layer. If set None, the layer
                         will be named automatically. Default: None.
        default_initializer(Initializer, optional): Where use initializer to initialize the Weight
T
tianshuo78520a 已提交
2746
                         If set None, default initializer will be used. Default: None.
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
        seed(int, optional): Seed for dropout in LSTM, If it's -1, dropout will use random seed. Default: 1.


    Returns:
        tuple ( :ref:`api_guide_Variable_en` , :ref:`api_guide_Variable_en` , :ref:`api_guide_Variable_en` ) :

                        Three tensors, rnn_out, last_h, last_c:

                        - rnn_out is result of LSTM hidden, shape is :math:`[seq\_len, batch\_size, hidden\_size]` \
                          if is_bidirec set to True, shape will be :math:`[seq\_len, batch\_size, hidden\_size*2]`
                        - last_h is the hidden state of the last step of LSTM \
                          shape is :math:`[num\_layers, batch\_size, hidden\_size]` \
                          if is_bidirec set to True, shape will be :math:`[num\_layers*2, batch\_size, hidden\_size]`
                        - last_c(Tensor): the cell state of the last step of LSTM \
                          shape is :math:`[num\_layers, batch\_size, hidden\_size]` \
                          if is_bidirec set to True, shape will be :math:`[num\_layers*2, batch\_size, hidden\_size]`


    Examples:
        .. code-block:: python
2767

2768
            import paddle
2769 2770
            import paddle.fluid as fluid
            import paddle.fluid.layers as layers
2771
            paddle.enable_static()
2772 2773 2774 2775 2776

            emb_dim = 256
            vocab_size = 10000
            data = fluid.data(name='x', shape=[None, 100], dtype='int64')
            emb = fluid.embedding(input=data, size=[vocab_size, emb_dim], is_sparse=True)
2777
            batch_size = 100
2778 2779 2780 2781
            dropout_prob = 0.2
            input_size = 100
            hidden_size = 150
            num_layers = 1
2782
            max_len = 12
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
            init_h = layers.fill_constant( [num_layers, batch_size, hidden_size], 'float32', 0.0 )
            init_c = layers.fill_constant( [num_layers, batch_size, hidden_size], 'float32', 0.0 )
            rnn_out, last_h, last_c = layers.lstm( emb, init_h, init_c, \
                    max_len, hidden_size, num_layers, \
                    dropout_prob=dropout_prob)
            rnn_out.shape  # (-1, 100, 150)
            last_h.shape  # (1, 20, 150)
            last_c.shape  # (1, 20, 150)
    """

    helper = LayerHelper('cudnn_lstm', **locals())
X
Xing Wu 已提交
2794 2795 2796 2797 2798 2799
    check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'lstm')
    check_variable_and_dtype(init_h, 'init_h', ['float32', 'float64'], 'lstm')
    check_variable_and_dtype(init_c, 'init_c', ['float32', 'float64'], 'lstm')
    check_type(max_len, 'max_len', (int), 'lstm')
    check_type(hidden_size, 'hidden_size', (int), 'lstm')
    check_type(num_layers, 'num_layers', (int), 'lstm')
2800 2801 2802 2803
    dtype = input.dtype
    input_shape = list(input.shape)
    input_size = input_shape[-1]
    weight_size = 0
G
GaoWei8 已提交
2804 2805
    num_dirrection = 2 if is_bidirec == True else 1

2806 2807
    for i in range(num_layers):
        if i == 0:
G
GaoWei8 已提交
2808
            input_weight_size = (input_size * hidden_size) * 4 * num_dirrection
2809
        else:
G
GaoWei8 已提交
2810 2811
            input_weight_size = (hidden_size * hidden_size) * 4 * num_dirrection
        hidden_weight_size = (hidden_size * hidden_size) * 4 * num_dirrection
2812

G
GaoWei8 已提交
2813 2814
        weight_size += input_weight_size + hidden_weight_size
        weight_size += hidden_size * 8 * num_dirrection
2815

2816 2817 2818 2819 2820 2821
    weight = helper.create_parameter(
        attr=helper.param_attr,
        shape=[weight_size],
        dtype=dtype,
        default_initializer=default_initializer,
    )
2822 2823 2824 2825

    out = helper.create_variable_for_type_inference(dtype)
    last_h = helper.create_variable_for_type_inference(dtype)
    last_c = helper.create_variable_for_type_inference(dtype)
G
GaoWei8 已提交
2826
    reserve = helper.create_variable_for_type_inference(
2827 2828
        dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
    )
G
GaoWei8 已提交
2829
    state_out = helper.create_variable_for_type_inference(
2830 2831
        dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
    )
G
GaoWei8 已提交
2832
    state_out.persistable = True
2833

2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
    helper.append_op(
        type='cudnn_lstm',
        inputs={
            'Input': input,
            'InitH': init_h,
            'InitC': init_c,
            'W': weight,
        },
        outputs={
            'Out': out,
            'LastH': last_h,
            'LastC': last_c,
            'Reserve': reserve,
            'StateOut': state_out,
        },
        attrs={
            'is_bidirec': is_bidirec,
            'input_size': input_size,
            'hidden_size': hidden_size,
            'num_layers': num_layers,
            'is_test': is_test,
            'dropout_prob': dropout_prob,
            'seed': seed,
        },
    )
2859 2860 2861
    return out, last_h, last_c


2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
def dynamic_lstmp(
    input,
    size,
    proj_size,
    param_attr=None,
    bias_attr=None,
    use_peepholes=True,
    is_reverse=False,
    gate_activation='sigmoid',
    cell_activation='tanh',
    candidate_activation='tanh',
    proj_activation='tanh',
    dtype='float32',
    name=None,
    h_0=None,
    c_0=None,
    cell_clip=None,
    proj_clip=None,
):
2881
    r"""
2882
	:api_attr: Static Graph
S
swtkiwi 已提交
2883

2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
    **Note**:
        1. In order to improve efficiency, users must first map the input of dimension [T, hidden_size] to input of [T, 4 * hidden_size], and then pass it to this OP.

    This OP implements the LSTMP (LSTM Projected) layer.
    The LSTMP layer has a separate linear mapping layer behind the LSTM layer. -- `Sak, H., Senior, A., & Beaufays, F. (2014) <https://ai.google/research/pubs/pub43905.pdf>`_ .

    Compared with the standard LSTM layer, LSTMP has an additional linear mapping layer,
    which is used to map from the original hidden state :math:`h_t` to the lower dimensional state :math:`r_t` .
    This reduces the total number of parameters and computational complexity, especially when the output unit is relatively large.

    The default implementation of the OP contains diagonal/peephole connections,
    please refer to `Gers, F. A., & Schmidhuber, J. (2000) <ftp://ftp.idsia.ch/pub/juergen/TimeCount-IJCNN2000.pdf>`_ .
    If you need to disable the peephole connections, set use_peepholes to False.

    This OP computes each timestep as follows:

    .. math::
      i_t = \sigma(W_{ix}x_{t} + W_{ir}r_{t-1} + W_{ic}c_{t-1} + b_i)
    .. math::
          f_t = \sigma(W_{fx}x_{t} + W_{fr}r_{t-1} + W_{fc}c_{t-1} + b_f)
    .. math::
          o_t = \sigma(W_{ox}x_{t} + W_{or}r_{t-1} + W_{oc}c_{t-1} + b_o)
    .. math::
          \widetilde{c_t} = act_g(W_{cx}x_t + W_{cr}r_{t-1} + b_c)
    .. math::
          c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t}
    .. math::
          h_t = o_t \odot act_h(c_t)
    .. math::
          r_t = \overline{act_h}(W_{rh}h_t)

    The symbolic meanings in the formula are as follows:

    - :math:`x_{t}` represents the input at timestep :math:`t`
    - :math:`h_{t}` represents the hidden state at timestep :math:`t`
    - :math:`r_{t}` : represents the state of the projected output of the hidden state :math:`h_{t}`
    - :math:`h_{t-1}, c_{t-1}, r_{t-1}` represent the hidden state, cell state and projected output at timestep :math:`t-1` , respectively
    - :math:`\widetilde{c_t}` represents the candidate cell state
    - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively
    - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` )
    - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate)
    - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid
    - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension

    Parameters:
        input( :ref:`api_guide_Variable_en` ): The input of dynamic_lstmp layer, which supports
                         variable-time length input sequence.
                         It is a multi-dimensional LODTensor of shape :math:`[T, 4*hidden\_size]` . Data type is float32 or float64.
        size(int): must be 4 * hidden_size.
        proj_size(int): The size of projection output.
        param_attr(ParamAttr, optional): Parameter attribute of weight. If it is None, the default weight parameter attribute is used. Please refer to ref:`api_fluid_ParamAttr' .
                              If the user needs to set this parameter, the dimension must be :math:`[hidden\_size, 4*hidden\_size]` . Default: None.

                              - Weights = :math:`\{ W_{cr},W_{ir},W_{fr},W_{or} \}` , the shape is [P, 4*hidden_size] , where P is the projection size.
                              - Projection weight  = :math:`\{ W_{rh} \}` , the shape is [hidden_size, P].

        bias_attr (ParamAttr, optional): The bias attribute for the learnable bias
                              weights, which contains two parts, input-hidden
                              bias weights and peephole connections weights if
                              setting `use_peepholes` to `True`.
                              Please refer to ref:`api_fluid_ParamAttr' . Default: None.

                              1. `use_peepholes = False`
                                 - Biases = {:math:`b_c, b_i, b_f, b_o`}.
                                 - The shape is [1, 4*hidden_size].
                              2. `use_peepholes = True`
                                 - Biases = { :math:`b_c, b_i, b_f, b_o, W_{ic}, \
                                                 W_{fc}, W_{oc}`}.
                                 - The shape is [1, 7*hidden_size].

        use_peepholes (bool, optional): Whether to use peephole connection or not. Default True.
        is_reverse (bool, optional): Whether to calculate reverse LSTM. Default False.
        gate_activation (str, optional): The activation for input gate, forget gate and output gate. Default "sigmoid".
        cell_activation (str, optional): The activation for cell output. Default "tanh".
        candidate_activation (str, optional): The activation for candidate hidden state. Default "tanh".
        proj_activation(str, optional): The activation for projection output. Default "tanh".
        dtype (str, optional): Data type, can be "float32" or "float64". Default "float32".
        name (str, optional): A name for this layer. Please refer to :ref:`api_guide_Name` . Default: None.
        h_0( :ref:`api_guide_Variable` , optional): The initial hidden state is an optional input, default is zero.
                       This is a tensor with shape :math:`[batch\_size, P]` , where P is the projection size. Default: None.
        c_0( :ref:`api_guide_Variable` , optional): The initial cell state is an optional input, default is zero.
                       This is a tensor with shape :math:`[batch\_size, P]` , where P is the projection size.
                       `h_0` and `c_0` can be None but only at the same time. Default: None.
        cell_clip(float, optional): If not None, the cell state is clipped
                             by this value prior to the cell output activation. Default: None.
        proj_clip(float, optional): If `num_proj > 0` and `proj_clip` is
                            provided, then the projected values are clipped elementwise to within
                            `[-proj_clip, proj_clip]`. Default: None.

    Returns:
        tuple ( :ref:`api_guide_Variable` , :ref:`api_guide_Variable` ) :

                The hidden state and cell state of LSTMP

                - hidden: LoDTensor with shape of :math:`[T, P]` , and its lod and dtype is the same as the input.
                - cell: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid
            dict_dim, emb_dim = 128, 64
            data = fluid.data(name='sequence', shape=[None], dtype='int64', lod_level=1)
            emb = fluid.embedding(input=data, size=[dict_dim, emb_dim])
            hidden_dim, proj_dim = 512, 256
            fc_out = fluid.layers.fc(input=emb, size=hidden_dim * 4,
                                    act=None, bias_attr=None)
            proj_out, last_c = fluid.layers.dynamic_lstmp(input=fc_out,
                                                    size=hidden_dim * 4,
                                                    proj_size=proj_dim,
                                                    use_peepholes=False,
                                                    is_reverse=True,
                                                    cell_activation="tanh",
                                                    proj_activation="tanh")
            proj_out.shape  # (-1, 256)
            last_c.shape  # (-1, 512)
    """

3003 3004 3005
    assert (
        _non_static_mode() is not True
    ), "please use lstm instead of dynamic_lstmp in dygraph mode!"
3006

3007 3008 3009
    assert (
        bias_attr is not False
    ), "bias_attr should not be False in dynamic_lstmp."
3010

3011 3012 3013
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'dynamic_lstmp'
    )
3014 3015 3016

    check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_lstmp')
    if isinstance(h_0, Variable):
3017 3018 3019
        check_variable_and_dtype(
            h_0, 'h_0', ['float32', 'float64'], 'dynamic_lstmp'
        )
3020 3021 3022

    check_type(c_0, 'c_0', (Variable, type(None)), 'dynamic_lstmp')
    if isinstance(c_0, Variable):
3023 3024 3025
        check_variable_and_dtype(
            c_0, 'c_0', ['float32', 'float64'], 'dynamic_lstmp'
        )
3026

3027 3028
    helper = LayerHelper('lstmp', **locals())
    size = size // 4
3029 3030 3031 3032 3033 3034
    weight = helper.create_parameter(
        attr=helper.param_attr, shape=[proj_size, 4 * size], dtype=dtype
    )
    proj_weight = helper.create_parameter(
        attr=helper.param_attr, shape=[size, proj_size], dtype=dtype
    )
3035 3036 3037
    bias_size = [1, 7 * size]
    if not use_peepholes:
        bias_size[1] = 4 * size
3038 3039 3040
    bias = helper.create_parameter(
        attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True
    )
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051

    projection = helper.create_variable_for_type_inference(dtype)
    cell = helper.create_variable_for_type_inference(dtype)
    ordered_proj0 = helper.create_variable_for_type_inference(dtype)
    batch_hidden = helper.create_variable_for_type_inference(dtype)
    batch_gate = helper.create_variable_for_type_inference(dtype)
    batch_cell_pre_act = helper.create_variable_for_type_inference(dtype)
    inputs = {
        'Input': input,
        'Weight': weight,
        'ProjWeight': proj_weight,
3052
        'Bias': bias,
3053 3054 3055
    }
    batch_size = input.shape[0]
    if h_0:
3056
        assert h_0.shape == (batch_size, proj_size), (
3057
            'The shape of h0 should be (batch_size, %d)' % proj_size
3058
        )
3059 3060
        inputs['H0'] = h_0
    if c_0:
3061
        assert c_0.shape == (batch_size, size), (
3062
            'The shape of c0 should be (batch_size, %d)' % size
3063
        )
3064 3065 3066
        inputs['C0'] = c_0

    if cell_clip:
T
tianshuo78520a 已提交
3067
        assert cell_clip >= 0, "cell_clip should not be negative."
3068
    if proj_clip:
T
tianshuo78520a 已提交
3069
        assert proj_clip >= 0, "proj_clip should not be negative."
3070

3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
    helper.append_op(
        type='lstmp',
        inputs=inputs,
        outputs={
            'Projection': projection,
            'Cell': cell,
            'BatchHidden': batch_hidden,
            'BatchGate': batch_gate,
            'BatchCellPreAct': batch_cell_pre_act,
        },
        attrs={
            'use_peepholes': use_peepholes,
            'cell_clip': cell_clip,
            'proj_clip': proj_clip,
            'is_reverse': is_reverse,
            'gate_activation': gate_activation,
            'cell_activation': cell_activation,
            'candidate_activation': candidate_activation,
            'proj_activation': proj_activation,
        },
    )
3092 3093 3094
    return projection, cell


3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
def dynamic_gru(
    input,
    size,
    param_attr=None,
    bias_attr=None,
    is_reverse=False,
    gate_activation='sigmoid',
    candidate_activation='tanh',
    h_0=None,
    origin_mode=False,
):
3106
    r"""
3107
	:api_attr: Static Graph
S
swtkiwi 已提交
3108

3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
    **Note: The input type of this must be LoDTensor. If the input type to be
    processed is Tensor, use** :ref:`api_fluid_layers_StaticRNN` .

    This operator is used to perform the calculations for a single layer of
    Gated Recurrent Unit (GRU) on full sequences step by step. The calculations
    in one time step support these two modes:

    If ``origin_mode`` is True, then the formula used is from paper
    `Learning Phrase Representations using RNN Encoder Decoder for Statistical
    Machine Translation <https://arxiv.org/pdf/1406.1078.pdf>`_ .

    .. math::

        u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u)

        r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r)

        \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c)

        h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t}


    if ``origin_mode`` is False, then the formula used is from paper
    `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence
    Modeling  <https://arxiv.org/pdf/1412.3555.pdf>`_

    .. math::

        u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u)

        r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r)

        \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c)

        h_t & = (1-u_t) \odot h_{t-1} + u_t \odot \\tilde{h_t}

    :math:`x_t` is the input of current time step, but it is not from ``input`` .
    This operator does not include the calculations :math:`W_{ux}x_{t}, W_{rx}x_{t}, W_{cx}x_{t}` ,
    **Note** thus a fully-connect layer whose size is 3 times of ``size`` should
    be used before this operator, and the output should be used as ``input`` here.
3149
    :math:`h_{t-1}` is the hidden state from previous time step.
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
    :math:`u_t` , :math:`r_t` , :math:`\\tilde{h_t}` and :math:`h_t` stand for
    update gate, reset gate, candidate hidden and hidden output separately.
    :math:`W_{uh}, b_u` , :math:`W_{rh}, b_r` and :math:`W_{ch}, b_c` stand for
    the weight matrix and bias used in update gate, reset gate, candidate hidden
    calculations. For implementation, the three weight matrix are merged into a
    tensor shaped :math:`[D, D \\times 3]` , the three bias are concatenated as
    a tensor shaped :math:`[1, D \\times 3]` , where :math:`D` stands for the
    hidden size; The data layout of weight tensor is: :math:`W_{uh}` and :math:`W_{rh}`
    are concatenated with shape :math:`[D, D  \\times 2]` lying on the first part,
    and :math:`W_{ch}` lying on the latter part with shape :math:`[D, D]` .


    Args:
        input(Variable): A LoDTensor whose lod level is 1, representing the input
            after linear projection. Its shape should be :math:`[T, D \\times 3]` ,
            where :math:`T` stands for the total sequence lengths in this mini-batch,
            :math:`D` for the hidden size. The data type should be float32 or float64.
        size(int): Indicate the hidden size.
        param_attr(ParamAttr, optional):  To specify the weight parameter property.
            Default: None, which means the default weight parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
        bias_attr (ParamAttr, optional): To specify the bias parameter property.
            Default: None, which means the default bias parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
        is_reverse(bool, optional): Whether to compute in the reversed order of
            input sequences. Default False.
T
tianshuo78520a 已提交
3176
        gate_activation(str, optional): The activation function corresponding to
3177 3178
            :math:`act_g` in the formula. "sigmoid", "tanh", "relu" and "identity"
            are supported. Default "sigmoid".
T
tianshuo78520a 已提交
3179
        candidate_activation(str, optional): The activation function corresponding to
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
            :math:`act_c` in the formula. "sigmoid", "tanh", "relu" and "identity"
            are supported. Default "tanh".
        h_0 (Variable, optional): A Tensor representing the initial hidden state.
            It not provided, the default initial hidden state is 0. The shape is
            :math:`[N, D]` , where :math:`N` is the number of sequences in the
            mini-batch, :math:`D` for the hidden size. The data type should be
            same as ``input`` . Default None.

    Returns:
        Variable: A LoDTensor whose lod level is 1 and shape is :math:`[T, D]` , \
            where :math:`T` stands for the total sequence lengths in this mini-batch \
            :math:`D` for the hidden size. It represents GRU transformed sequence output, \
            and has the same lod and data type with ``input`` .

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid

            dict_dim, emb_dim = 128, 64
            data = fluid.data(name='sequence',
                      shape=[None],
                      dtype='int64',
                      lod_level=1)
            emb = fluid.embedding(input=data, size=[dict_dim, emb_dim])
            hidden_dim = 512
            x = fluid.layers.fc(input=emb, size=hidden_dim * 3)
            hidden = fluid.layers.dynamic_gru(input=x, size=hidden_dim)
    """

3211 3212 3213
    assert (
        _non_static_mode() is not True
    ), "please use gru instead of dynamic_gru in dygraph mode!"
3214

3215 3216 3217
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'dynamic_gru'
    )
3218 3219 3220

    check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_gru')
    if isinstance(h_0, Variable):
3221 3222 3223
        check_variable_and_dtype(
            h_0, 'h_0', ['float32', 'float64'], 'dynamic_gru'
        )
3224

3225 3226 3227
    helper = LayerHelper('gru', **locals())
    dtype = helper.input_dtype()

3228 3229 3230 3231 3232 3233
    weight = helper.create_parameter(
        attr=helper.param_attr, shape=[size, 3 * size], dtype=dtype
    )
    bias = helper.create_parameter(
        attr=helper.bias_attr, shape=[1, 3 * size], dtype=dtype, is_bias=True
    )
3234 3235 3236
    batch_size = input.shape[0]
    inputs = {'Input': input, 'Weight': weight, 'Bias': bias}
    if h_0:
3237 3238 3239
        assert h_0.shape == (batch_size, size), (
            'The shape of h0 should be(batch_size, %d)' % size
        )
3240 3241 3242 3243 3244 3245 3246
        inputs['H0'] = h_0

    hidden = helper.create_variable_for_type_inference(dtype)
    batch_gate = helper.create_variable_for_type_inference(dtype)
    batch_reset_hidden_prev = helper.create_variable_for_type_inference(dtype)
    batch_hidden = helper.create_variable_for_type_inference(dtype)

3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    helper.append_op(
        type='gru',
        inputs=inputs,
        outputs={
            'Hidden': hidden,
            'BatchGate': batch_gate,
            'BatchResetHiddenPrev': batch_reset_hidden_prev,
            'BatchHidden': batch_hidden,
        },
        attrs={
            'is_reverse': is_reverse,
            'gate_activation': gate_activation,
            'activation': candidate_activation,
            'origin_mode': origin_mode,
        },
    )
3263 3264 3265
    return hidden


3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
def gru_unit(
    input,
    hidden,
    size,
    param_attr=None,
    bias_attr=None,
    activation='tanh',
    gate_activation='sigmoid',
    origin_mode=False,
):
3276
    r"""
3277
	:api_attr: Static Graph
S
swtkiwi 已提交
3278

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
    Gated Recurrent Unit (GRU) RNN cell. This operator performs GRU calculations for
    one time step and it supports these two modes:

    If ``origin_mode`` is True, then the formula used is from paper
    `Learning Phrase Representations using RNN Encoder Decoder for Statistical
    Machine Translation <https://arxiv.org/pdf/1406.1078.pdf>`_ .

    .. math::

        u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u)

        r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r)

        \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c)

        h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t}


    if ``origin_mode`` is False, then the formula used is from paper
    `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence
    Modeling  <https://arxiv.org/pdf/1412.3555.pdf>`_

    .. math::

        u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u)

        r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r)

        \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c)

        h_t & = (1-u_t) \odot h_{t-1} + u_t \odot \\tilde{h_t}

    :math:`x_t` is the input of current time step, but it is not ``input`` .
    This operator does not include the calculations :math:`W_{ux}x_{t}, W_{rx}x_{t}, W_{cx}x_{t}` ,
    **Note** thus a fully-connect layer whose size is 3 times of GRU hidden size should
    be used before this operator, and the output should be used as ``input`` here.
3315
    :math:`h_{t-1}` is the hidden state from previous time step.
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
    :math:`u_t` , :math:`r_t` , :math:`\\tilde{h_t}` and :math:`h_t` stand for
    update gate, reset gate, candidate hidden and hidden output separately.
    :math:`W_{uh}, b_u` , :math:`W_{rh}, b_r` and :math:`W_{ch}, b_c` stand for
    the weight matrix and bias used in update gate, reset gate, candidate hidden
    calculations. For implementation, the three weight matrix are merged into a
    tensor shaped :math:`[D, D \\times 3]` , the three bias are concatenated as
    a tensor shaped :math:`[1, D \\times 3]` , where :math:`D` stands for the
    hidden size; The data layout of weight tensor is: :math:`W_{uh}` and :math:`W_{rh}`
    are concatenated with shape :math:`[D, D  \\times 2]` lying on the first part,
    and :math:`W_{ch}` lying on the latter part with shape :math:`[D, D]` .


    Args:
        input(Variable): A 2D Tensor representing the input after linear projection
            after linear projection. Its shape should be :math:`[N, D \\times 3]` ,
            where :math:`N` stands for batch size, :math:`D` for the hidden size.
            The data type should be float32 or float64.
        hidden(Variable): A 2D Tensor representing the hidden state from previous step.
            Its shape should be :math:`[N, D]` , where :math:`N` stands for batch size,
            :math:`D` for the hidden size. The data type should be same as ``input`` .
        size(int): Indicate the hidden size.
        param_attr(ParamAttr, optional):  To specify the weight parameter property.
            Default: None, which means the default weight parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
        bias_attr (ParamAttr, optional): To specify the bias parameter property.
            Default: None, which means the default bias parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
T
tianshuo78520a 已提交
3343
        activation(str, optional): The activation function corresponding to
3344 3345
            :math:`act_c` in the formula. "sigmoid", "tanh", "relu" and "identity"
            are supported. Default "tanh".
T
tianshuo78520a 已提交
3346
        gate_activation(str, optional): The activation function corresponding to
3347 3348 3349 3350 3351 3352
            :math:`act_g` in the formula. "sigmoid", "tanh", "relu" and "identity"
            are supported. Default "sigmoid".

    Returns:
        tuple: The tuple contains three Tensor variables with the same data type \
            as ``input`` . They represent the hidden state for next time step ( :math:`h_t` ), \
T
tianshuo78520a 已提交
3353
            reset previous hidden state ( :math:`r_t \odot h_{t-1}` ), and the \
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
            concatenation of :math:`h_t, r_t, \\tilde{h_t}` . And they have shape \
            :math:`[N, D]` , :math:`[N, D]` , :math:`[N, D \times 3]` separately. \
            Usually only the hidden state for next time step ( :math:`h_t` ) is used \
            as output and state, the other two are intermediate results of calculations.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid

            dict_dim, emb_dim = 128, 64
            data = fluid.data(name='step_data', shape=[None], dtype='int64')
            emb = fluid.embedding(input=data, size=[dict_dim, emb_dim])
            hidden_dim = 512
            x = fluid.layers.fc(input=emb, size=hidden_dim * 3)
            pre_hidden = fluid.data(
                name='pre_hidden', shape=[None, hidden_dim], dtype='float32')
            hidden = fluid.layers.gru_unit(
                input=x, hidden=pre_hidden, size=hidden_dim * 3)

    """
X
Xing Wu 已提交
3376
    check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'gru_unit')
3377 3378 3379
    check_variable_and_dtype(
        hidden, 'hidden', ['float32', 'float64'], 'gru_unit'
    )
X
Xing Wu 已提交
3380
    check_type(size, 'size', (int), 'gru_unit')
3381 3382 3383 3384
    activation_dict = dict(
        identity=0,
        sigmoid=1,
        tanh=2,
3385 3386
        relu=3,
    )
3387 3388 3389 3390 3391 3392 3393 3394
    activation = activation_dict[activation]
    gate_activation = activation_dict[gate_activation]

    helper = LayerHelper('gru_unit', **locals())
    dtype = helper.input_dtype()
    size = size // 3

    # create weight
3395 3396 3397
    weight = helper.create_parameter(
        attr=helper.param_attr, shape=[size, 3 * size], dtype=dtype
    )
3398 3399 3400 3401 3402 3403 3404 3405

    gate = helper.create_variable_for_type_inference(dtype)
    reset_hidden_pre = helper.create_variable_for_type_inference(dtype)
    updated_hidden = helper.create_variable_for_type_inference(dtype)
    inputs = {'Input': input, 'HiddenPrev': hidden, 'Weight': weight}
    # create bias
    if helper.bias_attr:
        bias_size = [1, 3 * size]
3406 3407 3408
        bias = helper.create_parameter(
            attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True
        )
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
        inputs['Bias'] = bias

    helper.append_op(
        type='gru_unit',
        inputs=inputs,
        outputs={
            'Gate': gate,
            'ResetHiddenPrev': reset_hidden_pre,
            'Hidden': updated_hidden,
        },
        attrs={
            'activation': 2,  # tanh
            'gate_activation': 1,  # sigmoid
3422 3423 3424
            'origin_mode': origin_mode,
        },
    )
3425 3426 3427 3428

    return updated_hidden, reset_hidden_pre, gate


3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
def beam_search(
    pre_ids,
    pre_scores,
    ids,
    scores,
    beam_size,
    end_id,
    level=0,
    is_accumulated=True,
    name=None,
    return_parent_idx=False,
):
3441
    r"""
S
swtkiwi 已提交
3442

3443 3444 3445 3446 3447 3448 3449 3450 3451 3452
    Beam search is a classical algorithm for selecting candidate words in a
    machine translation task.

    Refer to `Beam search <https://en.wikipedia.org/wiki/Beam_search>`_
    for more details.

    **This operator only supports LoDTensor.** It is used after finishing
    scores calculation to perform beam search for one time step. Specifically,
    after ``ids`` and ``scores`` have been produced, it selects the top-K
    ( `k` is ``beam_size`` ) candidate word ids of current step from ``ids``
T
tianshuo78520a 已提交
3453
    according to the corresponding ``scores``. Additionally, ``pre_id`` and
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
    ``pre_scores`` are the output of `beam_search` at previous step, they
    are needed for special use to handle ended candidate translations.

    Note that if ``is_accumulated`` is True, the ``scores`` passed in should
    be accumulated scores. Otherwise, the ``scores`` are
    considered as the probabilities of single step and would be transformed to
    the log field and added up with ``pre_scores`` for final scores in this
    operator. Length penalty should be done with extra operators before calculating
    the accumulated scores if needed.

    Please see the following demo for a fully beam search usage example:

        fluid/tests/book/test_machine_translation.py

    Args:
        pre_ids(Variable): A LodTensor variable (lod level is 2), representing
            the selected ids of previous step. It is the output of beam_search
            at previous step. Its shape is `[batch_size, 1]` and its lod is
            `[[0, 1, ... , batch_size], [0, 1, ..., batch_size]]` at the
            first step. The data type should be int64.
        pre_scores(Variable): A LodTensor variable has the same shape and lod
            with ``pre_ids`` , representing the accumulated scores corresponding
            to the selected ids of previous step. It is the output of
X
Xing Wu 已提交
3477
            beam_search at previous step. The data type should be float32 or float64.
3478 3479 3480 3481 3482
        ids(Variable|None): A LodTensor variable containing the candidates ids.
            It has the same lod with ``pre_ids`` and its shape should be
            `[batch_size * beam_size, K]`, where `K` supposed to be greater than
            ``beam_size`` and the first dimension size (decrease as samples reach
            to the end) should be same as that of ``pre_ids`` . The data type
T
tianshuo78520a 已提交
3483
            should be int64. It can be None, which use index in ``scores`` as
3484 3485 3486
            ids.
        scores(Variable): A LodTensor variable containing the accumulated
            scores corresponding to ``ids`` . Both its shape and lod are same as
X
Xing Wu 已提交
3487
            those of ``ids`` . The data type should be float32 or float64.
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
        beam_size(int): The beam width used in beam search.
        end_id(int): The id of end token.
        level(int): **It can be ignored and mustn't change currently.**
            The 2 level lod used in this operator has the following
            meaning: The first level describes how many beams each sample has,
            which would change to 0 when beams of the sample all end (batch reduce);
            The second level describes how many times each beam is selected.
            Default 0, which shouldn't be changed currently.
        is_accumulated(bool): Whether the input ``score`` is accumulated scores.
            Default True.
3498 3499
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
3500 3501
            None by default.
        return_parent_idx(bool, optional): Whether to return an extra Tensor variable
T
tianshuo78520a 已提交
3502
            in output, which stores the selected ids' parent index in
3503 3504 3505 3506 3507 3508 3509 3510
            ``pre_ids`` and can be used to update RNN's states by gather operator.
            Default False.

    Returns:
        tuple: The tuple contains two or three LodTensor variables. The two LodTensor, \
            representing the selected ids and the corresponding accumulated scores of \
            current step, have the same shape `[batch_size, beam_size]` and lod with 2 levels, \
            and have data types int64 and float32. If ``return_parent_idx`` is True, \
T
tianshuo78520a 已提交
3511
            an extra Tensor variable preserving the selected ids' parent index \
3512 3513 3514 3515 3516 3517 3518
            is included, whose shape is `[batch_size * beam_size]` and data type \
            is int64.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
3519 3520
            import paddle
            paddle.enable_static()
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545

            # Suppose `probs` contains predicted results from the computation
            # cell and `pre_ids` and `pre_scores` is the output of beam_search
            # at previous step.
            beam_size = 4
            end_id = 1
            pre_ids = fluid.data(
                name='pre_id', shape=[None, 1], lod_level=2, dtype='int64')
            pre_scores = fluid.data(
                name='pre_scores', shape=[None, 1], lod_level=2, dtype='float32')
            probs = fluid.data(
                name='probs', shape=[None, 10000], dtype='float32')
            topk_scores, topk_indices = fluid.layers.topk(probs, k=beam_size)
            accu_scores = fluid.layers.elementwise_add(
                x=fluid.layers.log(x=topk_scores),
                y=fluid.layers.reshape(pre_scores, shape=[-1]),
                axis=0)
            selected_ids, selected_scores = fluid.layers.beam_search(
                pre_ids=pre_ids,
                pre_scores=pre_scores,
                ids=topk_indices,
                scores=accu_scores,
                beam_size=beam_size,
                end_id=end_id)
    """
3546
    check_variable_and_dtype(pre_ids, 'pre_ids', ['int64'], 'beam_search')
3547 3548 3549
    check_variable_and_dtype(
        pre_scores, 'pre_scores', ['float32', 'float64'], 'beam_search'
    )
3550
    check_type(ids, 'ids', (Variable, type(None)), 'beam_search')
3551 3552 3553
    check_variable_and_dtype(
        scores, 'scores', ['float32', 'float64'], 'beam_search'
    )
3554 3555 3556 3557 3558 3559 3560 3561 3562
    helper = LayerHelper('beam_search', **locals())
    score_type = pre_scores.dtype
    id_type = pre_ids.dtype

    inputs = {"pre_ids": pre_ids, "pre_scores": pre_scores, "scores": scores}
    if ids is not None:
        inputs["ids"] = ids

    selected_scores = helper.create_variable_for_type_inference(
3563 3564
        dtype=score_type
    )
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
    selected_ids = helper.create_variable_for_type_inference(dtype=id_type)
    # parent_idx is a tensor used to gather cell states at the next time
    # step. Though lod in selected_ids can also be used to gather by
    # sequence_expand, it is not efficient.
    # gather_op's index input only supports int32 dtype currently
    parent_idx = helper.create_variable_for_type_inference(dtype="int32")

    helper.append_op(
        type='beam_search',
        inputs=inputs,
        outputs={
            'selected_ids': selected_ids,
            'selected_scores': selected_scores,
3578
            'parent_idx': parent_idx,
3579 3580 3581 3582 3583 3584 3585
        },
        attrs={
            # TODO(ChunweiYan) to assure other value support
            'level': level,
            'beam_size': beam_size,
            'end_id': end_id,
            'is_accumulated': is_accumulated,
3586 3587
        },
    )
3588 3589 3590 3591 3592 3593 3594
    if return_parent_idx:
        return selected_ids, selected_scores, parent_idx
    else:
        return selected_ids, selected_scores


def beam_search_decode(ids, scores, beam_size, end_id, name=None):
3595
    r"""
S
swtkiwi 已提交
3596

3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
    This operator is used after beam search has completed. It constructs the
    full predicted sequences for each sample by walking back along the search
    paths stored in lod of ``ids`` . The result sequences are stored in a
    LoDTensor, which uses the following way to parse:

    .. code-block:: text

        If lod = [[0, 3, 6], [0, 12, 24, 40, 54, 67, 82]]

        The first level of lod stands for: There are 2 samples each having 3
        (beam width) predicted sequence.

        The second level of lod stands for: The lengths of the first sample's
        3 predicted sequences are 12, 12, 16; The lengths of the second sample's
        3 predicted sequences are 14, 13, 15.


    Please see the following demo for a fully beam search usage example:
        fluid/tests/book/test_machine_translation.py

    Args:
        ids(Variable): The LoDTensorArray variable containing the selected ids
            of all steps. Each LoDTensor in it has int64 data type and 2 level
            lod which can be used to get the search paths.
        scores(Variable): The LodTensorArray variable containing the accumulated
            scores corresponding to selected ids of all steps. It has the same size
            as ``ids`` . Each LoDTensor in it has the same shape and lod as the
            counterpart in ``ids`` , and has a float32 data type.
        beam_size(int): The beam width used in beam search.
        end_id(int): The id of end token.
3627 3628
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
3629 3630 3631 3632
            None by default.

    Returns:
        tuple: The tuple contains two LodTensor variables. The two LodTensor, \
T
tianshuo78520a 已提交
3633
            containing the full sequences of ids and the corresponding accumulated \
3634 3635 3636 3637 3638 3639 3640 3641
            scores, have the same shape flattened to 1D and have the same 2 level \
            lod. The lod can be used to get how many predicted sequences each sample \
            has and how many ids each predicted sequence has.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
3642 3643
            import paddle
            paddle.enable_static()
3644 3645 3646 3647 3648 3649 3650
            # Suppose `ids` and `scores` are LodTensorArray variables reserving
            # the selected ids and scores of all steps
            ids = fluid.layers.create_array(dtype='int64')
            scores = fluid.layers.create_array(dtype='float32')
            finished_ids, finished_scores = fluid.layers.beam_search_decode(
                ids, scores, beam_size=5, end_id=0)
    """
3651
    check_variable_and_dtype(ids, 'ids', ['int64'], 'beam_search_encode')
3652 3653 3654
    check_variable_and_dtype(
        scores, 'scores', ['float32'], 'beam_search_encode'
    )
3655 3656
    helper = LayerHelper('beam_search_decode', **locals())
    sentence_ids = helper.create_variable_for_type_inference(dtype=ids.dtype)
3657
    sentence_scores = helper.create_variable_for_type_inference(
3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
        dtype=scores.dtype
    )

    helper.append_op(
        type="beam_search_decode",
        inputs={"Ids": ids, "Scores": scores},
        outputs={
            "SentenceIds": sentence_ids,
            "SentenceScores": sentence_scores,
        },
        attrs={"beam_size": beam_size, "end_id": end_id},
    )
3670 3671 3672 3673

    return sentence_ids, sentence_scores


3674 3675 3676 3677 3678 3679 3680 3681 3682
def lstm_unit(
    x_t,
    hidden_t_prev,
    cell_t_prev,
    forget_bias=0.0,
    param_attr=None,
    bias_attr=None,
    name=None,
):
3683
    r"""
3684
	:api_attr: Static Graph
S
swtkiwi 已提交
3685

3686 3687 3688 3689 3690 3691
    Long-Short Term Memory (LSTM) RNN cell. This operator performs LSTM calculations for
    one time step, whose implementation is based on calculations described in `RECURRENT
    NEURAL NETWORK REGULARIZATION <http://arxiv.org/abs/1409.2329>`_  .

    We add forget_bias to the biases of the forget gate in order to
    reduce the scale of forgetting. The formula is as follows:
3692

3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729
    .. math::

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

        f_{t} & = \sigma(W_{x_{f}}x_{t} + W_{h_{f}}h_{t-1} + b_{f} + forget\\_bias)

        c_{t} & = f_{t}c_{t-1} + i_{t} tanh (W_{x_{c}}x_{t} + W_{h_{c}}h_{t-1} + b_{c})

        o_{t} & = \sigma(W_{x_{o}}x_{t} + W_{h_{o}}h_{t-1} + b_{o})

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

    :math:`x_{t}` stands for ``x_t`` , corresponding to the input of current time step;
    :math:`h_{t-1}` and :math:`c_{t-1}` correspond to ``hidden_t_prev`` and ``cell_t_prev`` ,
    representing the output of from previous time step.
    :math:`i_{t}, f_{t}, c_{t}, o_{t}, h_{t}` are input gate, forget gate, cell, output gate
    and hidden calculation.

    Args:
        x_t(Variable): A 2D Tensor representing the input of current time step.
            Its shape should be :math:`[N, M]` , where :math:`N` stands for batch
            size, :math:`M` for the feature size of input. The data type should
            be float32 or float64.
        hidden_t_prev(Variable): A 2D Tensor representing the hidden value from
            previous step. Its shape should be :math:`[N, D]` , where :math:`N`
            stands for batch size, :math:`D` for the hidden size. The data type
            should be same as ``x_t`` .
        cell_t_prev(Variable): A 2D Tensor representing the cell value from
            previous step. It has the same shape and data type with ``hidden_t_prev`` .
        forget_bias (float, optional): :math:`forget\\_bias` added to the biases
            of the forget gate. Default 0.
        param_attr(ParamAttr, optional):  To specify the weight parameter property.
            Default: None, which means the default weight parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
        bias_attr (ParamAttr, optional): To specify the bias parameter property.
            Default: None, which means the default bias parameter property is used.
            See usage for details in :ref:`api_fluid_ParamAttr` .
3730 3731
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
            None by default.

    Returns:
        tuple: The tuple contains two Tensor variables with the same shape and \
            data type with ``hidden_t_prev`` , representing the hidden value and \
            cell value which correspond to :math:`h_{t}` and :math:`c_{t}` in \
            the formula.

    Raises:
        ValueError: Rank of x_t must be 2.
        ValueError: Rank of hidden_t_prev must be 2.
        ValueError: Rank of cell_t_prev must be 2.
        ValueError: The 1st dimensions of x_t, hidden_t_prev and cell_t_prev must be the same.
        ValueError: The 2nd dimensions of hidden_t_prev and cell_t_prev must be the same.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid

            dict_dim, emb_dim, hidden_dim = 128, 64, 512
            data = fluid.data(name='step_data', shape=[None], dtype='int64')
            x = fluid.embedding(input=data, size=[dict_dim, emb_dim])
            pre_hidden = fluid.data(
                name='pre_hidden', shape=[None, hidden_dim], dtype='float32')
            pre_cell = fluid.data(
                name='pre_cell', shape=[None, hidden_dim], dtype='float32')
            hidden = fluid.layers.lstm_unit(
                x_t=x,
                hidden_t_prev=pre_hidden,
                cell_t_prev=pre_cell)
    """
    helper = LayerHelper('lstm_unit', **locals())
X
Xing Wu 已提交
3766
    check_variable_and_dtype(x_t, 'x_t', ['float32', 'float64'], 'lstm_unit')
3767 3768 3769 3770 3771 3772
    check_variable_and_dtype(
        hidden_t_prev, 'hidden_t_prev', ['float32', 'float64'], 'lstm_unit'
    )
    check_variable_and_dtype(
        cell_t_prev, 'cell_t_prev', ['float32', 'float64'], 'lstm_unit'
    )
3773 3774 3775 3776 3777 3778 3779 3780 3781
    if len(x_t.shape) != 2:
        raise ValueError("Rank of x_t must be 2.")

    if len(hidden_t_prev.shape) != 2:
        raise ValueError("Rank of hidden_t_prev must be 2.")

    if len(cell_t_prev.shape) != 2:
        raise ValueError("Rank of cell_t_prev must be 2.")

3782 3783 3784 3785 3786 3787 3788 3789
    if (
        x_t.shape[0] != hidden_t_prev.shape[0]
        or x_t.shape[0] != cell_t_prev.shape[0]
    ):
        raise ValueError(
            "The 1st dimensions of x_t, hidden_t_prev and "
            "cell_t_prev must be the same."
        )
3790 3791

    if hidden_t_prev.shape[1] != cell_t_prev.shape[1]:
3792 3793 3794 3795
        raise ValueError(
            "The 2nd dimensions of hidden_t_prev and "
            "cell_t_prev must be the same."
        )
3796 3797 3798 3799 3800 3801

    if bias_attr is None:
        bias_attr = ParamAttr()

    size = cell_t_prev.shape[1]
    concat_out = nn.concat(input=[x_t, hidden_t_prev], axis=1)
3802 3803 3804 3805 3806 3807
    fc_out = nn.fc(
        input=concat_out,
        size=4 * size,
        param_attr=param_attr,
        bias_attr=bias_attr,
    )
3808 3809 3810 3811
    dtype = x_t.dtype
    c = helper.create_variable_for_type_inference(dtype)
    h = helper.create_variable_for_type_inference(dtype)

3812 3813 3814 3815 3816 3817
    helper.append_op(
        type='lstm_unit',
        inputs={"X": fc_out, "C_prev": cell_t_prev},
        outputs={"C": c, "H": h},
        attrs={"forget_bias": forget_bias},
    )
3818 3819

    return h, c