nn.py 62.0 KB
Newer Older
M
minqiyang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2018 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 paddle
M
minqiyang 已提交
16 17
from .. import core
from ..layers import utils
18
from ..layers import nn as F
19
from .. import dygraph_utils
M
minqiyang 已提交
20
from . import layers
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
from ..framework import (
    Variable,
    _non_static_mode,
    OpProtoHolder,
    Parameter,
    _dygraph_tracer,
    _varbase_creator,
    default_main_program,
    _global_flags,
    in_dygraph_mode,
    _in_legacy_dygraph,
)
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
M
minqiyang 已提交
39
from ..param_attr import ParamAttr
40
from ..initializer import Normal, Constant, NumpyArrayInitializer
H
hong 已提交
41 42
from .. import unique_name
from .layer_object_helper import LayerObjectHelper
43
from ..data_feeder import check_variable_and_dtype, check_type
L
lujun 已提交
44
import numpy as np
45
import numbers
46
import logging
47
import os
48
import paddle.utils.deprecated as deprecated
49
from paddle import _C_ops, _legacy_C_ops
50

51
__all__ = [
52 53 54 55 56 57 58 59 60
    'Conv3D',
    'Linear',
    'BatchNorm',
    'Embedding',
    'Conv3DTranspose',
    'GroupNorm',
    'SpectralNorm',
    'TreeConv',
    'Flatten',
61
]
M
minqiyang 已提交
62 63


L
lujun 已提交
64
class Conv3D(layers.Layer):
65
    r"""
66 67 68 69
    **Convlution3D Layer**

    The convolution3D layer calculates the output based on the input, filter
    and strides, paddings, dilations, groups parameters. Input(Input) and
70
    Output(Output) are multidimensional tensors with a shape of
D
DuYao 已提交
71
    :math:`[N, C, D, H, W]` . Where N is batch size, C is the number of
72 73 74 75 76 77 78 79 80 81 82 83 84 85
    channels, D is the depth of the feature, H is the height of the feature,
    and W is the width of the feature. Convlution3D is similar with Convlution2D
    but adds one dimension(depth). If bias attribution and activation type are
    provided, bias is added to the output of the convolution, and the
    corresponding activation function is applied to the final result.

    For each input :math:`X`, the equation is:

    .. math::

        Out = \sigma (W \\ast X + b)

    In the above equation:

D
DuYao 已提交
86
    * :math:`X`: Input value, a tensor with NCDHW or NDHWC format.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    * :math:`W`: Filter value, a tensor with MCDHW format.
    * :math:`\\ast`: Convolution operation.
    * :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
    * :math:`\\sigma`: Activation function.
    * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.

    Example:

        - Input:

          Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`

          Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)`

        - Output:
          Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`

        Where

        .. math::

            D_{out}&= \\frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\\\
            H_{out}&= \\frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\\\
            W_{out}&= \\frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1

112
    Parameters:
113
        num_channels(int): The number of channels in the input image.
L
lujun 已提交
114
        num_filters(int): The number of filter. It is as same as the output image channel.
D
DuYao 已提交
115
        filter_size (int|tuple, optional): The filter size. If filter_size is a tuple,
116
            it must contain three integers, (filter_size_D, filter_size_H, filter_size_W).
D
DuYao 已提交
117 118 119
            Otherwise, the filter will be a square, filter_size_depth = filter_size_height
            = filter_size_width = filter_size.
        stride (int|tuple, optional): The stride size. If stride is a tuple, it must
120
            contain three integers, (stride_D, stride_H, stride_W). Otherwise, the
D
DuYao 已提交
121 122
            stride_D = stride_H = stride_W = stride. The default value is 1.
        padding (int|tuple, optional): The padding size. If padding is a tuple, it must
123
            contain three integers, (padding_D, padding_H, padding_W). Otherwise, the
D
DuYao 已提交
124 125
            padding_D = padding_H = padding_W = padding. The default value is 0.
        dilation (int|tuple, optional): The dilation size. If dilation is a tuple, it must
126
            contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the
D
DuYao 已提交
127
            dilation_D = dilation_H = dilation_W = dilation. The default value is 1.
C
cnn 已提交
128
        groups (int, optional): The groups number of the Conv3D Layer. According to grouped
129 130 131
            convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
            the first half of the filters is only connected to the first half
            of the input channels, while the second half of the filters is only
D
DuYao 已提交
132 133
            connected to the second half of the input channels. The default value is 1.
        param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights
134 135 136
            of conv3d. If it is set to None or one attribute of ParamAttr, conv3d
            will create ParamAttr as param_attr. If it is set to None, the parameter
            is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is
D
DuYao 已提交
137 138
            :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None.
        bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d.
139 140 141
            If it is set to False, no bias will be added to the output units.
            If it is set to None or one attribute of ParamAttr, conv3d
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
D
DuYao 已提交
142 143 144 145 146
            is not set, the bias is initialized zero. The default value is None.
        use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. The default value is True.
        act (str, optional): Activation type, if it is set to None, activation is not appended.
            The default value is None.
147
        dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32".
148

D
DuYao 已提交
149 150 151 152
    Attribute:
        **weight** (Parameter): the learnable weights of filters of this layer.

        **bias** (Parameter): the learnable bias of this layer.
153

154
    Returns:
D
DuYao 已提交
155
        None.
156 157 158 159 160 161 162 163

    Raises:
        ValueError: If the shapes of input, filter_size, stride, padding and
                    groups mismatch.

    Examples:
        .. code-block:: python

164 165 166 167 168 169
          import paddle.fluid as fluid
          import numpy

          with fluid.dygraph.guard():
              data = numpy.random.random((5, 3, 12, 32, 32)).astype('float32')
              conv3d = fluid.dygraph.nn.Conv3D(
170
                    num_channels=3, num_filters=2, filter_size=3, act="relu")
171 172
              ret = conv3d(fluid.dygraph.base.to_variable(data))

173 174
    """

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    def __init__(
        self,
        num_channels,
        num_filters,
        filter_size,
        stride=1,
        padding=0,
        dilation=1,
        groups=None,
        param_attr=None,
        bias_attr=None,
        use_cudnn=True,
        act=None,
        dtype='float32',
    ):
L
lujun 已提交
190
        assert param_attr is not False, "param_attr should not be False here."
191
        super().__init__()
192
        self._num_channels = num_channels
L
lujun 已提交
193 194 195
        self._groups = groups
        self._stride = utils.convert_to_list(stride, 3, 'stride')
        self._padding = utils.convert_to_list(padding, 3, 'padding')
196
        self._dilation = utils.convert_to_list(dilation, 3, 'dilation')
L
lujun 已提交
197 198
        self._act = act
        self._use_cudnn = use_cudnn
199 200 201 202
        self._filter_size = filter_size
        self._num_filters = num_filters
        self._param_attr = param_attr
        self._bias_attr = bias_attr
203
        self._dtype = dtype
204 205

        if self._groups is None:
206
            num_filter_channels = self._num_channels
L
lujun 已提交
207
        else:
208
            if self._num_channels % self._groups != 0:
L
lujun 已提交
209
                raise ValueError("num_channels must be divisible by groups.")
210
            num_filter_channels = self._num_channels // self._groups
L
lujun 已提交
211

212 213
        filter_size = utils.convert_to_list(self._filter_size, 3, 'filter_size')
        filter_shape = [self._num_filters, num_filter_channels] + filter_size
L
lujun 已提交
214 215

        def _get_default_param_initializer():
216 217 218 219 220 221 222
            filter_elem_num = (
                filter_size[0]
                * filter_size[1]
                * filter_size[2]
                * self._num_channels
            )
            std = (2.0 / filter_elem_num) ** 0.5
L
lujun 已提交
223 224
            return Normal(0.0, std, 0)

225
        self.weight = self.create_parameter(
226
            attr=self._param_attr,
L
lujun 已提交
227 228
            shape=filter_shape,
            dtype=self._dtype,
229 230
            default_initializer=_get_default_param_initializer(),
        )
L
lujun 已提交
231

232 233 234 235 236 237
        self.bias = self.create_parameter(
            attr=self._bias_attr,
            shape=[self._num_filters],
            dtype=self._dtype,
            is_bias=True,
        )
L
lujun 已提交
238 239 240

    def forward(self, input):
        pre_bias = self._helper.create_variable_for_type_inference(
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
            dtype=self._dtype
        )

        self._helper.append_op(
            type='conv3d',
            inputs={
                'Input': input,
                'Filter': self.weight,
            },
            outputs={"Output": pre_bias},
            attrs={
                'strides': self._stride,
                'paddings': self._padding,
                'dilations': self._dilation,
                'groups': self._groups if self._groups else 1,
                'use_cudnn': self._use_cudnn,
                'use_mkldnn': False,
            },
        )
L
lujun 已提交
260

261
        if self.bias is not None:
262
            pre_act = self._helper.create_variable_for_type_inference(
263 264 265 266 267 268 269 270
                dtype=self._dtype
            )
            self._helper.append_op(
                type='elementwise_add',
                inputs={'X': [pre_bias], 'Y': [self.bias]},
                outputs={'Out': [pre_act]},
                attrs={'axis': 1},
            )
271 272
        else:
            pre_act = pre_bias
L
lujun 已提交
273 274 275 276 277

        return self._helper.append_activation(pre_act, act=self._act)


class Conv3DTranspose(layers.Layer):
278
    r"""
L
lujun 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    **Convlution3D transpose layer**

    The convolution3D transpose layer calculates the output based on the input,
    filter, and dilations, strides, paddings. Input(Input) and output(Output)
    are in NCDHW format. Where N is batch size, C is the number of channels,
    D is the depth of the feature, H is the height of the feature, and W
    is the width of the feature. Parameters(dilations, strides, paddings) are
    two elements. These two elements represent height and width, respectively.
    The details of convolution transpose layer, please refer to the following
    explanation and references `therein <http://www.matthewzeiler.com/wp-content/uploads/2017/07/cvpr2010.pdf>`_.
    If bias attribution and activation type are provided, bias is added to
    the output of the convolution, and the corresponding activation function
    is applied to the final result.

    For each input :math:`X`, the equation is:

    .. math::

        Out = \sigma (W \\ast X + b)

    In the above equation:

    * :math:`X`: Input value, a tensor with NCDHW format.
    * :math:`W`: Filter value, a tensor with MCDHW format.
    * :math:`\\ast`: Convolution operation.
    * :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
    * :math:`\\sigma`: Activation function.
    * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.

    Example:

        - Input:

          Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`

          Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)`

        - Output:

          Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`

        Where

        .. math::

D
DuYao 已提交
324 325 326 327 328 329 330 331
           D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\\\
           H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\\\
           W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\\\
           D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\\\
           H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\\\

    **Note**:

332 333
          The conv3d_transpose can be seen as the backward of the conv3d. For conv3d,
          when stride > 1, conv3d maps multiple input shape to the same output shape,
D
DuYao 已提交
334 335
          so for conv3d_transpose, when stride > 1, input shape maps multiple output shape.
          If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \
336 337 338 339 340
          H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output
          size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`,
          the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}`
          and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must
          between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`,
D
DuYao 已提交
341 342
          conv3d_transpose can compute the kernel size automatically.

L
lujun 已提交
343

344
    Parameters:
345
        num_channels(int): The number of channels in the input image.
L
lujun 已提交
346 347
        num_filters(int): The number of the filter. It is as same as the output
            image channel.
348
        filter_size(int|tuple): The filter size. If filter_size is a tuple,
L
lujun 已提交
349
            it must contain three integers, (filter_size_D, filter_size_H, filter_size_W).
350
            Otherwise, the filter will be a square.
D
DuYao 已提交
351 352 353 354 355 356 357 358 359 360
        padding(int|tuple, optional): The padding size. The padding argument effectively
             adds `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a string,
             either 'VALID' or 'SAME' supported, which is the padding algorithm. If `padding`
             is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or
            `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`,
            and when `data_format` is `'NCDHW'`, `padding` can be in the form
            `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
            when `data_format` is `'NDHWC'`, `padding` can be in the form
            `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
            The default value is 0.
361 362 363
        stride(int|tuple, optional): The stride size. It means the stride in transposed convolution.
            If stride is a tuple, it must contain three integers, (stride_depth, stride_height,
            stride_width). Otherwise, stride_depth = stride_height = stride_width = stride.
D
DuYao 已提交
364 365
            The default value is 1.
        dilation(int|tuple, optional): The dilation size. If dilation is a tuple, it must
L
lujun 已提交
366
            contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the
D
DuYao 已提交
367
            dilation_D = dilation_H = dilation_W = dilation. The default value is 1.
C
cnn 已提交
368
        groups(int, optional): The groups number of the Conv3D transpose layer. Inspired by
L
lujun 已提交
369 370 371 372
            grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
            when group=2, the first half of the filters is only connected to the
            first half of the input channels, while the second half of the
            filters is only connected to the second half of the input channels.
D
DuYao 已提交
373 374
            The default value is 1.
        param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights
L
lujun 已提交
375 376
            of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose
            will create ParamAttr as param_attr. If the Initializer of the param_attr
D
DuYao 已提交
377 378
            is not set, the parameter is initialized with Xavier. The default value is None.
        bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose.
L
lujun 已提交
379 380 381
            If it is set to False, no bias will be added to the output units.
            If it is set to None or one attribute of ParamAttr, conv3d_transpose
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
D
DuYao 已提交
382 383 384 385 386
            is not set, the bias is initialized zero. The default value is None.
        use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. The default value is True.
        act (str, optional): Activation type, if it is set to None, activation is not appended.
            The default value is None.
387
        name(str, optional): The default value is None. Normally there is no need for user
D
DuYao 已提交
388
            to set this property. For more information, please refer to :ref:`api_guide_Name`.
L
lujun 已提交
389

D
DuYao 已提交
390 391 392 393
    Attribute:
        **weight** (Parameter): the learnable weights of filters of this layer.

        **bias** (Parameter): the learnable bias of this layer.
394

L
lujun 已提交
395
    Returns:
D
DuYao 已提交
396
        None.
L
lujun 已提交
397 398 399 400 401 402 403 404

    Raises:
        ValueError: If the shapes of input, filter_size, stride, padding and
                    groups mismatch.

    Examples:
       .. code-block:: python

405 406 407 408 409 410
         import paddle.fluid as fluid
         import numpy

         with fluid.dygraph.guard():
             data = numpy.random.random((5, 3, 12, 32, 32)).astype('float32')
             conv3dTranspose = fluid.dygraph.nn.Conv3DTranspose(
411
                    num_channels=3,
412 413 414 415 416
                    num_filters=12,
                    filter_size=12,
                    use_cudnn=False)
             ret = conv3dTranspose(fluid.dygraph.base.to_variable(data))

L
lujun 已提交
417 418
    """

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    def __init__(
        self,
        num_channels,
        num_filters,
        filter_size,
        padding=0,
        stride=1,
        dilation=1,
        groups=None,
        param_attr=None,
        bias_attr=None,
        use_cudnn=True,
        act=None,
        dtype='float32',
    ):
434
        super().__init__()
L
lujun 已提交
435 436
        if not isinstance(use_cudnn, bool):
            raise ValueError("use_cudnn should be True or False")
437 438 439
        assert (
            param_attr is not False
        ), "param_attr should not be False in conv3d_transpose."
L
lujun 已提交
440 441 442 443
        self._padding = utils.convert_to_list(padding, 3, 'padding')
        self._stride = utils.convert_to_list(stride, 3, 'stride')
        self._dilation = utils.convert_to_list(dilation, 3, 'dilation')
        self._param_attr = param_attr
444
        self._num_channels = num_channels
L
lujun 已提交
445 446 447 448 449 450
        self._filter_size = filter_size
        self._groups = 1 if groups is None else groups
        self._num_filters = num_filters
        self._use_cudnn = use_cudnn
        self._bias_attr = bias_attr
        self._act = act
451
        self._dtype = dtype
L
lujun 已提交
452

453
        self._filter_size = utils.convert_to_list(
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            self._filter_size, 3, 'conv3d_transpose.filter_size'
        )

        filter_shape = [
            self._num_channels,
            self._num_filters // self._groups,
        ] + self._filter_size
        self.weight = self.create_parameter(
            dtype=self._dtype, shape=filter_shape, attr=self._param_attr
        )
        self.bias = self.create_parameter(
            attr=self._bias_attr,
            shape=[self._num_filters],
            dtype=self._dtype,
            is_bias=True,
        )
L
lujun 已提交
470 471 472

    def forward(self, input):
        pre_bias = self._helper.create_variable_for_type_inference(
473 474 475 476 477 478 479 480 481 482 483 484 485 486
            dtype=self._dtype
        )
        self._helper.append_op(
            type="conv3d_transpose",
            inputs={'Input': [input], 'Filter': [self.weight]},
            outputs={'Output': pre_bias},
            attrs={
                'strides': self._stride,
                'paddings': self._padding,
                'dilations': self._dilation,
                'groups': self._groups if self._groups else 1,
                'use_cudnn': self._use_cudnn,
            },
        )
L
lujun 已提交
487 488 489

        if self._bias_attr:
            pre_act = self._helper.create_variable_for_type_inference(
490 491 492 493 494 495 496 497
                dtype=self._dtype
            )
            self._helper.append_op(
                type='elementwise_add',
                inputs={'X': [pre_bias], 'Y': [self.bias]},
                outputs={'Out': [pre_act]},
                attrs={'axis': 1},
            )
L
lujun 已提交
498 499 500 501 502 503 504
        else:
            pre_act = pre_bias

        # Currently, we don't support inplace in imperative mode
        return self._helper.append_activation(pre_act, act=self._act)


S
songyouwei 已提交
505 506
class Linear(layers.Layer):
    """
507

S
songyouwei 已提交
508 509 510 511 512 513 514 515
    Fully-connected linear transformation layer:

    .. math::

        Out = Act({XW + b})

    where :math:`X` is the input Tensor, :math:`W` and :math:`b` are weight and bias respectively.

516
    Linear layer takes only one ``Tensor`` input.
S
songyouwei 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    The Linear layer multiplies input tensor with weight matrix and
    produces an output Tensor of shape [N, *, `output_dim`],
    where N is batch size and `*` means any number of additional dimensions.
    If ``bias_attr`` is not None, a bias variable will be created and added to the output.
    Finally, if ``act`` is not None, it will be applied to the output as well.

    Parameters:
        input_dim(int): The number of input units in this layer.
        output_dim(int): The number of output units in this layer.
        param_attr(ParamAttr or list of ParamAttr, optional): The parameter attribute for learnable
            weights(Parameter) of this layer. Default: None.
        bias_attr(ParamAttr or list of ParamAttr, optional): The attribute for the bias
            of this layer. If it is set to False, no bias will be added to the output units.
            If it is set to None, the bias is initialized zero. Default: None.
        act(str, optional): Activation to be applied to the output of this layer. Default: None.
        dtype(str, optional): Dtype used for weight, it can be "float32" or "float64". Default: "float32".

    Attributes:
        **weight** (Parameter): the learnable weights of this layer.

        **bias** (Parameter or None): the learnable bias of this layer.

    Returns:
        None

    Examples:
        .. code-block:: python

          from paddle.fluid.dygraph.base import to_variable
          import paddle.fluid as fluid
          from paddle.fluid.dygraph import Linear
          import numpy as np

          data = np.random.uniform(-1, 1, [30, 10, 32]).astype('float32')
          with fluid.dygraph.guard():
              linear = Linear(32, 64)
              data = to_variable(data)
              res = linear(data)  # [30, 10, 64]
    """

557 558 559 560 561 562 563 564 565
    def __init__(
        self,
        input_dim,
        output_dim,
        param_attr=None,
        bias_attr=None,
        act=None,
        dtype="float32",
    ):
566
        super().__init__()
S
songyouwei 已提交
567 568
        self._act = act
        self._dtype = dtype
569 570 571 572 573 574 575 576 577
        self.weight = self.create_parameter(
            shape=[input_dim, output_dim],
            attr=param_attr,
            dtype=dtype,
            is_bias=False,
        )
        self.bias = self.create_parameter(
            shape=[output_dim], attr=bias_attr, dtype=dtype, is_bias=True
        )
S
songyouwei 已提交
578

579
        self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"]
580

S
songyouwei 已提交
581
    def forward(self, input):
J
Jiabin Yang 已提交
582
        if _non_static_mode():
583
            pre_bias = _varbase_creator(dtype=input.dtype)
584 585 586 587 588 589 590 591 592 593 594 595 596
            _legacy_C_ops.matmul(
                input,
                self.weight,
                pre_bias,
                'transpose_X',
                False,
                'transpose_Y',
                False,
                "alpha",
                1,
                "use_mkldnn",
                self._use_mkldnn,
            )
597
            pre_act = dygraph_utils._append_bias_in_dygraph(
598 599 600
                pre_bias,
                self.bias,
                axis=len(input.shape) - 1,
601 602
                use_mkldnn=self._use_mkldnn,
            )
603

604
            return dygraph_utils._append_activation_in_dygraph(
605 606
                pre_act, self._act, use_mkldnn=self._use_mkldnn
            )
607

608 609 610
        check_variable_and_dtype(
            input, 'input', ['float16', 'float32', 'float64'], "Linear"
        )
611

612
        attrs = {
S
songyouwei 已提交
613 614 615
            "transpose_X": False,
            "transpose_Y": False,
            "alpha": 1,
616
            "use_mkldnn": self._use_mkldnn,
617 618
        }
        inputs = {"X": [input], "Y": [self.weight]}
619

S
songyouwei 已提交
620
        tmp = self._helper.create_variable_for_type_inference(self._dtype)
621 622 623
        self._helper.append_op(
            type="matmul", inputs=inputs, outputs={"Out": tmp}, attrs=attrs
        )
624
        if self.bias is not None:
S
songyouwei 已提交
625
            pre_activation = self._helper.create_variable_for_type_inference(
626 627 628 629 630 631 632 633 634 635 636
                dtype=self._dtype
            )
            self._helper.append_op(
                type='elementwise_add',
                inputs={'X': [tmp], 'Y': [self.bias]},
                outputs={'Out': [pre_activation]},
                attrs={
                    'axis': len(input.shape) - 1,
                    'use_mkldnn': self._use_mkldnn,
                },
            )
S
songyouwei 已提交
637 638 639 640 641
        else:
            pre_activation = tmp
        return self._helper.append_activation(pre_activation, act=self._act)


M
minqiyang 已提交
642
class BatchNorm(layers.Layer):
643
    r"""
644

645 646
    This interface is used to construct a callable object of the ``BatchNorm`` class.
    For more details, refer to code examples.
647
    It implements the function of the Batch Normalization Layer and can be used
648 649
    as a normalizer function for conv2d and fully connected operations.
    The data is normalized by the mean and variance of the channel based on the current batch data.
650 651 652 653
    Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/pdf/1502.03167.pdf>`_
    for more details.

654
    When use_global_stats = False, the :math:`\mu_{\beta}`
655
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
656
    Calculated as follows:
657 658 659

    ..  math::

660 661 662 663
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &
        //\ mini-batch\ mean \\
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \mu_{\beta})^2 \qquad &
        //\ mini-batch\ variance \\
664

665 666
    - :math:`x` : mini-batch data
    - :math:`m` : the size of the mini-batch data
667 668 669

    When use_global_stats = True, the :math:`\\mu_{\\beta}`
    and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch.
670 671 672 673 674 675
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
        moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global mean \\
        moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global variance \\
676

677
    The normalization function formula is as follows:
678

679 680
    ..  math::

681 682 683 684
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\
        \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift

685

686 687 688
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
689

690
    Parameters:
691
        num_channels(int): Indicate the number of channels of the input ``Tensor``.
T
tianshuo78520a 已提交
692
        act(str, optional): Activation to be applied to the output of batch normalization. Default: None.
693 694 695
        is_test (bool, optional): A flag indicating whether it is in test phrase or not.
             This flag only has effect on static graph mode. For dygraph mode, please use ``eval()``.
             Default: False.
696 697 698
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        param_attr(ParamAttr, optional): The parameter attribute for Parameter `scale`
699 700 701
             of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
             will create ParamAttr as param_attr. If the Initializer of the param_attr
             is not set, the parameter is initialized with Xavier. Default: None.
702
        bias_attr(ParamAttr, optional): The parameter attribute for the bias of batch_norm.
703 704 705
             If it is set to None or one attribute of ParamAttr, batch_norm
             will create ParamAttr as bias_attr. If the Initializer of the bias_attr
             is not set, the bias is initialized zero. Default: None.
706 707 708 709 710 711
        dtype(str, optional): Indicate the data type of the input ``Tensor``,
             which can be float32 or float64. Default: float32.
        data_layout(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW.
        in_place(bool, optional): Make the input and output of batch norm reuse memory. Default: False.
        moving_mean_name(str, optional): The name of moving_mean which store the global Mean. Default: None.
        moving_variance_name(str, optional): The name of the moving_variance which store the global Variance. Default: None.
712 713
        do_model_average_for_mean_and_var(bool, optional): Whether parameter mean and variance should do model
            average when model average is enabled. Default: True.
714
        use_global_stats(bool, optional): Whether to use global mean and
715 716 717
            variance. In inference or test mode, set use_global_stats to true
            or is_test to true, and the behavior is equivalent.
            In train mode, when setting use_global_stats True, the global mean
718 719 720 721
            and variance are also used during train period. Default: False.
        trainable_statistics(bool, optional): Whether to calculate mean and var in eval mode. In eval mode, when
            setting trainable_statistics True, mean and variance will be calculated by current batch statistics.
            Default: False.
722 723

    Returns:
724
        None
725 726 727

    Examples:
        .. code-block:: python
L
lujun 已提交
728 729

          import paddle.fluid as fluid
730 731
          from paddle.fluid.dygraph.base import to_variable
          import numpy as np
L
lujun 已提交
732

733
          x = np.random.random(size=(3, 10, 3, 7)).astype('float32')
L
lujun 已提交
734
          with fluid.dygraph.guard():
735
              x = to_variable(x)
736
              batch_norm = fluid.BatchNorm(10)
737
              hidden1 = batch_norm(x)
738 739
    """

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    def __init__(
        self,
        num_channels,
        act=None,
        is_test=False,
        momentum=0.9,
        epsilon=1e-05,
        param_attr=None,
        bias_attr=None,
        dtype='float32',
        data_layout='NCHW',
        in_place=False,
        moving_mean_name=None,
        moving_variance_name=None,
        do_model_average_for_mean_and_var=True,
        use_global_stats=False,
        trainable_statistics=False,
    ):
758
        super().__init__()
759
        self._param_attr = param_attr
760
        self._bias_attr = bias_attr
761
        self._act = act
762
        self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"]
M
minqiyang 已提交
763

764 765 766
        assert (
            bias_attr is not False
        ), "bias_attr should not be False in batch_norm."
M
minqiyang 已提交
767

768 769
        if dtype == "float16":
            self._dtype = "float32"
M
minqiyang 已提交
770 771 772 773 774 775
        else:
            self._dtype = dtype

        param_shape = [num_channels]

        # create parameter
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        self.weight = self.create_parameter(
            attr=self._param_attr,
            shape=param_shape,
            dtype=self._dtype,
            default_initializer=Constant(1.0),
        )
        self.weight.stop_gradient = (
            use_global_stats and self._param_attr.learning_rate == 0.0
        )

        self.bias = self.create_parameter(
            attr=self._bias_attr,
            shape=param_shape,
            dtype=self._dtype,
            is_bias=True,
        )
        self.bias.stop_gradient = (
            use_global_stats and self._param_attr.learning_rate == 0.0
        )

        self._mean = self.create_parameter(
            attr=ParamAttr(
                name=moving_mean_name,
                initializer=Constant(0.0),
                trainable=False,
                do_model_average=do_model_average_for_mean_and_var,
            ),
            shape=param_shape,
            dtype=self._dtype,
        )
806
        self._mean.stop_gradient = True
M
minqiyang 已提交
807

808 809 810 811 812 813 814 815 816 817
        self._variance = self.create_parameter(
            attr=ParamAttr(
                name=moving_variance_name,
                initializer=Constant(1.0),
                trainable=False,
                do_model_average=do_model_average_for_mean_and_var,
            ),
            shape=param_shape,
            dtype=self._dtype,
        )
818
        self._variance.stop_gradient = True
M
minqiyang 已提交
819 820

        self._in_place = in_place
821
        self._data_layout = data_layout
M
minqiyang 已提交
822 823 824
        self._momentum = momentum
        self._epsilon = epsilon
        self._is_test = is_test
825
        self._fuse_with_relu = False
M
minqiyang 已提交
826
        self._use_global_stats = use_global_stats
827
        self._trainable_statistics = trainable_statistics
M
minqiyang 已提交
828 829 830 831 832 833 834

    def forward(self, input):
        # create output
        # mean and mean_out share the same memory
        mean_out = self._mean
        # variance and variance out share the same memory
        variance_out = self._variance
835

J
Jiabin Yang 已提交
836
        if _non_static_mode():
H
hong 已提交
837
            if in_dygraph_mode():
838
                batch_norm_out, t1, t2, t3, t4, _ = _C_ops.batch_norm(
839 840 841
                    input,
                    self._mean,
                    self._variance,
842 843 844
                    self.weight,
                    self.bias,
                    not self.training,
845 846 847 848 849 850
                    self._momentum,
                    self._epsilon,
                    self._data_layout,
                    self._use_global_stats,
                    self._trainable_statistics,
                )
851
                return dygraph_utils._append_activation_in_dygraph(
852 853
                    batch_norm_out, act=self._act, use_mkldnn=self._use_mkldnn
                )
854 855

            elif _in_legacy_dygraph():
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
                attrs = (
                    "momentum",
                    self._momentum,
                    "epsilon",
                    self._epsilon,
                    "is_test",
                    not self.training,
                    "data_layout",
                    self._data_layout,
                    "use_mkldnn",
                    self._use_mkldnn,
                    "fuse_with_relu",
                    self._fuse_with_relu,
                    "use_global_stats",
                    self._use_global_stats,
                    'trainable_statistics',
                    self._trainable_statistics,
                )
874
                batch_norm_out, _, _, _, _, _ = _legacy_C_ops.batch_norm(
875 876 877 878 879 880 881 882 883 884
                    input,
                    self.weight,
                    self.bias,
                    self._mean,
                    self._variance,
                    None,
                    mean_out,
                    variance_out,
                    *attrs
                )
885

886
            return dygraph_utils._append_activation_in_dygraph(
887 888
                batch_norm_out, act=self._act, use_mkldnn=self._use_mkldnn
            )
889

890 891 892
        check_variable_and_dtype(
            input, 'input', ['float16', 'float32', 'float64'], 'BatchNorm'
        )
893

894 895 896 897 898 899 900
        attrs = {
            "momentum": self._momentum,
            "epsilon": self._epsilon,
            "is_test": self._is_test,
            "data_layout": self._data_layout,
            "use_mkldnn": False,
            "fuse_with_relu": self._fuse_with_relu,
901 902
            "use_global_stats": self._use_global_stats,
            "trainable_statistics": self._trainable_statistics,
903
        }
M
minqiyang 已提交
904

905 906 907 908 909
        inputs = {
            "X": [input],
            "Scale": [self.weight],
            "Bias": [self.bias],
            "Mean": [self._mean],
910
            "Variance": [self._variance],
911 912
        }

913
        saved_mean = self._helper.create_variable_for_type_inference(
914 915
            dtype=self._dtype, stop_gradient=True
        )
916
        saved_variance = self._helper.create_variable_for_type_inference(
917 918
            dtype=self._dtype, stop_gradient=True
        )
919
        reserve_space = self._helper.create_variable_for_type_inference(
920 921
            dtype=self._helper.input_dtype(input), stop_gradient=True
        )
922

923 924 925 926 927
        batch_norm_out = (
            input
            if self._in_place
            else self._helper.create_variable_for_type_inference(self._dtype)
        )
928 929 930 931 932 933

        outputs = {
            "Y": [batch_norm_out],
            "MeanOut": [mean_out],
            "VarianceOut": [variance_out],
            "SavedMean": [saved_mean],
934
            "SavedVariance": [saved_variance],
935
        }
936
        if reserve_space is not None:
937
            outputs["ReserveSpace"] = [reserve_space]
938

939 940 941
        self._helper.append_op(
            type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs
        )
M
minqiyang 已提交
942

L
lujun 已提交
943
        # Currently, we don't support inplace in dygraph mode
944
        return self._helper.append_activation(batch_norm_out, self._act)
945 946


947
class Embedding(layers.Layer):
948
    r"""
949
    :alias_main: paddle.nn.Embedding
950 951
        :alias: paddle.nn.Embedding,paddle.nn.layer.Embedding,paddle.nn.layer.common.Embedding
        :old_api: paddle.fluid.dygraph.Embedding
952

953 954
    **Embedding Layer**

Z
zhongpu 已提交
955 956 957 958 959 960
    This interface is used to construct a callable object of the ``Embedding`` class.
    For specific usage, refer to code examples. It implements the function of the Embedding Layer.
    This layer is used to lookup embeddings vector of ids provided by :attr:`input` .
    It automatically constructs a 2D embedding matrix based on the
    input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` .

961 962
    The shape of output Tensor is generated by appending an emb_size dimension to the
    last dimension of the input Tensor shape.
Z
zhongpu 已提交
963

964
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
Z
zhongpu 已提交
965 966 967 968 969 970 971
    otherwise the program will throw an exception and exit.

    .. code-block:: text

        Case 1:

        input is a Tensor. padding_idx = -1
972 973
            input.data = [[1, 3], [2, 4], [4, 127]
            input.shape = [3, 2]
Z
zhongpu 已提交
974 975 976 977 978 979 980 981
        Given size = [128, 16]
        output is a Tensor:
            out.shape = [3, 2, 16]
            out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
                        [0.345421456, 0.524563927, ..., 0.144534654]],

                        [[0.345249859, 0.124939536, ..., 0.194353745],
                        [0.945345345, 0.435394634, ..., 0.435345365]],
982

Z
zhongpu 已提交
983 984 985 986
                        [[0.945345345, 0.435394634, ..., 0.435345365],
                        [0.0,         0.0,         ..., 0.0        ]]]  # padding data
        The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
        It will pad all-zero data when ids is 127.
987

988
    Parameters:
L
lujun 已提交
989 990
        size(tuple|list): The shape of the look up table parameter. It should have two elements which indicate the size
            of the dictionary of embeddings and the size of each embedding vector respectively.
Z
zhongpu 已提交
991
        is_sparse(bool): The flag indicating whether to use sparse update. This parameter only
992
            affects the performance of the backwards gradient update. It is recommended to set
Z
zhongpu 已提交
993
            True because sparse update is faster. But some optimizer does not support sparse update,
994
            such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` ,
Z
zhongpu 已提交
995 996 997 998 999
            :ref:`api_fluid_optimizer_DecayedAdagradOptimizer` , :ref:`api_fluid_optimizer_FtrlOptimizer` ,
            :ref:`api_fluid_optimizer_LambOptimizer` and :ref:`api_fluid_optimizer_LarsMomentumOptimizer` .
            In these case, is_sparse must be False. Default: False.
        is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used
            in multi-machine distributed CPU training. Default: False.
1000
        padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
Z
zhongpu 已提交
1001 1002 1003 1004 1005 1006
            If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
            to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup
            encounters :math:`padding\_idx` in id. And the padding data will not be updated while training.
            If set None, it makes no effect to output. Default: None.
        param_attr(ParamAttr): 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` . In addition,
1007
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
Z
zhongpu 已提交
1008
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tianshuo78520a 已提交
1009
            vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer`
Z
zhongpu 已提交
1010 1011 1012
            is used to load custom or pre-trained word vectors. See code example 2 for details.
        dtype(np.dtype|core.VarDesc.VarType|str): It refers to the data type of output Tensor.
            It must be "float32" or "float64". Default: "float32".
1013

Z
zhongpu 已提交
1014 1015
    Attribute:
        **weight** (Parameter): the learnable weights of this layer.
1016

1017
    Returns:
Z
zhongpu 已提交
1018
        Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
1019 1020

    Examples:
1021

1022 1023
        .. code-block:: python

L
lujun 已提交
1024 1025 1026 1027
          import paddle.fluid as fluid
          import paddle.fluid.dygraph.base as base
          import numpy as np

Z
zhongpu 已提交
1028
          # example 1
1029 1030
          inp_word = np.array([[2, 3, 5], [4, 2, 1]]).astype('int64')
          inp_word.shape  # [2, 3]
1031 1032
          dict_size = 20
          with fluid.dygraph.guard():
L
lujun 已提交
1033
              emb = fluid.dygraph.Embedding(
1034 1035 1036
                  size=[dict_size, 32],
                  param_attr='emb.w',
                  is_sparse=False)
L
lujun 已提交
1037
              static_rlt3 = emb(base.to_variable(inp_word))
1038
              static_rlt3.shape  # [2, 3, 32]
Z
zhongpu 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

          # example 2: load custom or pre-trained word vectors
          weight_data = np.random.random(size=(128, 100))  # word vectors with numpy format
          w_param_attrs = fluid.ParamAttr(
              name="emb_weight",
              learning_rate=0.5,
              initializer=fluid.initializer.NumpyArrayInitializer(weight_data),
              trainable=True)
          with fluid.dygraph.guard():
              emb = fluid.dygraph.Embedding(
                  size=[128, 100],
                  param_attr= w_param_attrs,
                  is_sparse=False)
1052
              static_rlt3 = emb(base.to_variable(inp_word))
1053 1054
    """

1055 1056 1057 1058 1059 1060 1061 1062 1063
    def __init__(
        self,
        size,
        is_sparse=False,
        is_distributed=False,
        padding_idx=None,
        param_attr=None,
        dtype='float32',
    ):
1064
        super().__init__()
1065 1066 1067
        self._size = size
        self._is_sparse = is_sparse
        self._is_distributed = is_distributed
1068 1069 1070 1071 1072 1073 1074
        self._padding_idx = (
            -1
            if padding_idx is None
            else padding_idx
            if padding_idx >= 0
            else (size[0] + padding_idx)
        )
1075 1076 1077

        self._param_attr = param_attr
        self._dtype = dtype
J
JiabinYang 已提交
1078
        self._remote_prefetch = self._is_sparse and (not self._is_distributed)
1079 1080 1081
        if self._remote_prefetch:
            assert self._is_sparse is True and self._is_distributed is False

1082 1083 1084 1085 1086 1087
        self.weight = self.create_parameter(
            attr=self._param_attr,
            shape=self._size,
            dtype=self._dtype,
            is_bias=False,
        )
1088 1089

    def forward(self, input):
J
Jiabin Yang 已提交
1090
        if _non_static_mode():
1091
            return _legacy_C_ops.lookup_table_v2(
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
                self.weight,
                input,
                'is_sparse',
                self._is_sparse,
                'is_distributed',
                self._is_distributed,
                'remote_prefetch',
                self._remote_prefetch,
                'padding_idx',
                self._padding_idx,
            )
1103

1104 1105 1106 1107 1108 1109
        check_variable_and_dtype(
            input,
            'input',
            ['uint8', 'int8', 'int16', 'int32', 'int64'],
            'Embedding',
        )
1110 1111 1112 1113
        attrs = {
            'is_sparse': self._is_sparse,
            'is_distributed': self._is_distributed,
            'remote_prefetch': self._remote_prefetch,
1114
            'padding_idx': self._padding_idx,
1115
        }
1116

1117
        out = self._helper.create_variable_for_type_inference(self._dtype)
1118 1119 1120 1121 1122 1123
        self._helper.append_op(
            type='lookup_table_v2',
            inputs={'Ids': input, 'W': self.weight},
            outputs={'Out': out},
            attrs=attrs,
        )
1124 1125

        return out
M
minqiyang 已提交
1126 1127


L
lujun 已提交
1128
class RowConv(layers.Layer):
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    """
    ***Row-convolution operator***

    The row convolution is called lookahead convolution.  This operator was introduced in the following paper for DeepSpeech2:
    http://www.cs.cmu.edu/~dyogatam/papers/wang+etal.iclrworkshop2016.pdf

    The main motivation is that a bidirectional RNN, useful in DeepSpeech like speech models, learns representation for a sequence by performing a
    forward and a backward pass through the entire sequence. However, unlike
    unidirectional RNNs, bidirectional RNNs are challenging to deploy in an online
    and low-latency setting. The lookahead convolution incorporates information
    from future subsequences in a computationally efficient manner to improve
    unidirectional recurrent neural networks. The row convolution operator is
    different from the 1D sequence convolution, and is computed as follows:

    Given an input sequence X of length t and input dimension D, and a filter (W) of size context * D.

    More details about row_conv please refer to the design document https://github.com/PaddlePaddle/Paddle/issues/2228#issuecomment-303903645 .

1147
    Parameters:
L
lujun 已提交
1148
        name_scope(str): The name of this class.
1149 1150 1151
        future_context_size (int): Future context size. Please note, the shape
            of convolution kernel is [future_context_size + 1, D].
        param_attr (ParamAttr): Attributes of parameters, including
L
lujun 已提交
1152 1153
            name, initializer etc. Default: None.
        act (str): Non-linear activation to be applied to output variable. Default: None.
1154

1155 1156 1157
    Attributes:
        weight (Parameter): the learnable weights of this layer.

1158
    Returns:
L
lujun 已提交
1159 1160
        the output(Out) is a LodTensor, which supports variable time-length input sequences.
        The underlying tensor in this LodTensor is a matrix with shape T x N, i.e., the same shape as X.
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          import numpy

          with fluid.dygraph.guard():
              x = numpy.random.random((16)).astype('float32')
              rowConv = fluid.dygraph.nn.RowConv(
                    'RowConv', future_context_size=2)
              ret = rowConv(fluid.dygraph.base.to_variable(x))

    """

1176 1177 1178 1179 1180
    def __init__(
        self, name_scope, future_context_size, param_attr=None, act=None
    ):
        assert (
            not _non_static_mode()
1181
        ), "RowConv is not supported by dynamic graph mode yet!"
1182
        super().__init__(name_scope)
L
lujun 已提交
1183 1184 1185 1186
        self._act = act
        self._param_attr = param_attr
        self._future_context_size = future_context_size

1187
    def _build_once(self, input):
L
lujun 已提交
1188 1189
        self._dtype = self._helper.input_dtype(input)
        filter_shape = [self._future_context_size + 1, input.shape[1]]
1190 1191 1192 1193 1194 1195
        self.weight = self.create_parameter(
            attr=self._param_attr,
            shape=filter_shape,
            dtype=self._dtype,
            is_bias=False,
        )
L
lujun 已提交
1196 1197 1198

    def forward(self, input):
        out = self._helper.create_variable_for_type_inference(self._dtype)
1199 1200 1201 1202 1203
        self._helper.append_op(
            type='row_conv',
            inputs={'X': [input], 'Filter': [self.weight]},
            outputs={'Out': [out]},
        )
L
lujun 已提交
1204 1205 1206 1207 1208
        return self._helper.append_activation(out, act=self._act)


class GroupNorm(layers.Layer):
    """
1209
    :alias_main: paddle.nn.GroupNorm
1210 1211
        :alias: paddle.nn.GroupNorm,paddle.nn.layer.GroupNorm,paddle.nn.layer.norm.GroupNorm
        :old_api: paddle.fluid.dygraph.GroupNorm
1212

1213 1214 1215 1216 1217 1218
    This interface is used to construct a callable object of the ``GroupNorm`` class.
    For more details, refer to code examples.
    It implements the function of the Group Normalization Layer.
    Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_ .

    Parameters:
1219
        channels(int): The number of channels of input.
1220 1221 1222 1223 1224 1225 1226 1227 1228
        groups(int): The number of groups that divided from channels.
        epsilon(float, optional): The small value added to the variance to prevent
                                  division by zero. Default: 1e-05.
        param_attr(ParamAttr, optional): The parameter attribute for the learnable
                                         scale :math:`g`. If it is set to False, no scale will be added to the output units.
                                         If it is set to None, the bias is initialized one. Default: None.
        bias_attr(ParamAttr, optional): The parameter attribute for the learnable
                                        bias :math:`b`. If it is set to False, no bias will be added to the output units.
                                        If it is set to None, the bias is initialized zero. Default: None.
T
tianshuo78520a 已提交
1229
        act(str, optional): Activation to be applied to the output of group normalization. Default: None.
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        data_layout(str, optional): Specify the input data format. Only NCHW is supported. Default: NCHW.

    Returns:
        None

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          import numpy as np

          with fluid.dygraph.guard():
              x = np.random.random((8, 32, 32)).astype('float32')
1243
              groupNorm = fluid.dygraph.nn.GroupNorm(channels=32, groups=4)
1244
              ret = groupNorm(fluid.dygraph.base.to_variable(x))
L
lujun 已提交
1245 1246 1247

    """

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    def __init__(
        self,
        channels,
        groups,
        epsilon=1e-05,
        param_attr=None,
        bias_attr=None,
        act=None,
        data_layout='NCHW',
        dtype='float32',
    ):
1259
        super().__init__()
L
lujun 已提交
1260 1261 1262
        self._param_attr = param_attr
        self._bias_attr = bias_attr
        self._epsilon = epsilon
1263
        self._channels = channels
L
lujun 已提交
1264 1265
        self._groups = groups
        self._act = act
1266
        self._dtype = dtype
L
lujun 已提交
1267 1268 1269
        if data_layout != 'NCHW':
            raise ValueError("unsupported data layout:" + data_layout)

1270
        param_shape = [self._channels]
L
lujun 已提交
1271

1272 1273 1274 1275 1276 1277
        self.weight = self.create_parameter(
            attr=self._param_attr or False,
            shape=param_shape,
            dtype=self._dtype,
            default_initializer=Constant(1.0),
        )
1278

1279 1280 1281 1282 1283 1284
        self.bias = self.create_parameter(
            attr=self._bias_attr or False,
            shape=param_shape,
            dtype=self._dtype,
            is_bias=True,
        )
L
lujun 已提交
1285 1286

    def forward(self, input):
1287
        mean_out = self._helper.create_variable_for_type_inference(
1288 1289
            dtype=self._dtype, stop_gradient=True
        )
1290
        variance_out = self._helper.create_variable_for_type_inference(
1291 1292
            dtype=self._dtype, stop_gradient=True
        )
1293
        if in_dygraph_mode():
1294 1295 1296 1297 1298 1299 1300 1301
            out = _C_ops.group_norm(
                input,
                self.weight,
                self.bias,
                self._epsilon,
                self._groups,
                "NCHW",
            )
1302

1303 1304 1305
            return dygraph_utils._append_activation_in_dygraph(out, self._act)

        elif _in_legacy_dygraph():
1306
            attrs = ('epsilon', self._epsilon, 'groups', self._groups)
1307 1308 1309
            out, _, _ = _legacy_C_ops.group_norm(
                input, self.weight, self.bias, mean_out, variance_out, *attrs
            )
1310 1311

            return dygraph_utils._append_activation_in_dygraph(out, self._act)
J
Jiabin Yang 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320
        else:
            inputs = {'X': input}
            if self.bias is not None:
                inputs['Bias'] = self.bias
            if self.weight is not None:
                inputs['Scale'] = self.weight

            # create output
            group_norm_out = self._helper.create_variable_for_type_inference(
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
                dtype=self._dtype
            )

            self._helper.append_op(
                type="group_norm",
                inputs=inputs,
                outputs={
                    "Y": group_norm_out,
                    "Mean": mean_out,
                    "Variance": variance_out,
                },
                attrs={"epsilon": self._epsilon, "groups": self._groups},
            )
J
Jiabin Yang 已提交
1334 1335

            return self._helper.append_activation(group_norm_out, self._act)
L
lujun 已提交
1336 1337 1338


class SpectralNorm(layers.Layer):
1339
    r"""
1340 1341
    This interface is used to construct a callable object of the ``SpectralNorm`` class.
    For more details, refer to code examples. It implements the function of the Spectral Normalization Layer.
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    This layer calculates the spectral normalization value of weight parameters of
    fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D
    Parameters. Calculations are showed as follows.

    Step 1:
    Generate vector U in shape of [H], and V in shape of [W].
    While H is the :attr:`dim` th dimension of the input weights,
    and W is the product result of remaining dimensions.

    Step 2:
T
tianshuo78520a 已提交
1352
    :attr:`power_iters` should be a positive integer, do following
1353 1354 1355 1356
    calculations with U and V for :attr:`power_iters` rounds.

    .. math::

1357
        \mathbf{v} := \frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2}
1358

1359
        \mathbf{u} := \frac{\mathbf{W}^{T} \mathbf{v}}{\|\mathbf{W}^{T} \mathbf{v}\|_2}
1360 1361 1362 1363 1364 1365 1366 1367

    Step 3:
    Calculate :math:`\sigma(\mathbf{W})` and normalize weight values.

    .. math::

        \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v}

1368
        \mathbf{W} = \frac{\mathbf{W}}{\sigma(\mathbf{W})}
1369 1370 1371 1372


    Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ .

1373
    Parameters:
1374
        weight_shape(list or tuple): The shape of weight parameter.
1375 1376 1377 1378
        dim(int, optional): The index of dimension which should be permuted to the first before reshaping Input(Weight) to matrix, it should be set as 0 if Input(Weight) is the weight of fc layer, and should be set as 1 if Input(Weight) is the weight of conv layer. Default: 0.
        power_iters(int, optional): The number of power iterations to calculate spectral norm. Default: 1.
        eps(float, optional): The epsilon for numerical stability in calculating norms. Default: 1e-12.
        name (str, optional): The default value is None.  Normally there is no need for user to set this property.  For more information, please refer to :ref:`api_guide_Name` .
1379
        dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32".
1380 1381

    Returns:
1382
        None
1383 1384 1385 1386

    Examples:
       .. code-block:: python

C
Chen Long 已提交
1387 1388
            import paddle
            x = paddle.rand((2,8,32,32))
1389

C
Chen Long 已提交
1390 1391 1392 1393
            spectral_norm = paddle.nn.SpectralNorm(x.shape, dim=1, power_iters=2)
            spectral_norm_out = spectral_norm(x)

            print(spectral_norm_out.shape) # [2, 8, 32, 32]
1394 1395 1396

    """

1397 1398 1399
    def __init__(
        self, weight_shape, dim=0, power_iters=1, eps=1e-12, dtype='float32'
    ):
1400
        super().__init__()
L
lujun 已提交
1401 1402 1403
        self._power_iters = power_iters
        self._eps = eps
        self._dim = dim
1404
        self._dtype = dtype
L
lujun 已提交
1405

1406
        self._weight_shape = list(weight_shape)
1407 1408 1409 1410 1411
        assert (
            np.prod(self._weight_shape) > 0
        ), "Any dimension of `weight_shape` cannot be equal to 0."
        assert dim < len(self._weight_shape), (
            "The input `dim` should be less than the "
1412
            "length of `weight_shape`, but received dim="
1413 1414
            "{}".format(dim)
        )
1415 1416
        h = self._weight_shape[self._dim]
        w = np.prod(self._weight_shape) // h
L
lujun 已提交
1417

1418 1419 1420 1421 1422 1423
        self.weight_u = self.create_parameter(
            attr=ParamAttr(),
            shape=[h],
            dtype=self._dtype,
            default_initializer=Normal(0.0, 1.0),
        )
1424
        self.weight_u.stop_gradient = True
L
lujun 已提交
1425

1426 1427 1428 1429 1430 1431
        self.weight_v = self.create_parameter(
            attr=ParamAttr(),
            shape=[w],
            dtype=self._dtype,
            default_initializer=Normal(0.0, 1.0),
        )
1432
        self.weight_v.stop_gradient = True
L
lujun 已提交
1433 1434

    def forward(self, weight):
1435
        if in_dygraph_mode():
1436 1437 1438 1439 1440 1441 1442 1443
            return _C_ops.spectral_norm(
                weight,
                self.weight_u,
                self.weight_v,
                self._dim,
                self._power_iters,
                self._eps,
            )
1444

1445 1446 1447
        check_variable_and_dtype(
            weight, "weight", ['float32', 'float64'], 'SpectralNorm'
        )
1448
        inputs = {'Weight': weight, 'U': self.weight_u, 'V': self.weight_v}
L
lujun 已提交
1449
        out = self._helper.create_variable_for_type_inference(self._dtype)
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        self._helper.append_op(
            type="spectral_norm",
            inputs=inputs,
            outputs={
                "Out": out,
            },
            attrs={
                "dim": self._dim,
                "power_iters": self._power_iters,
                "eps": self._eps,
            },
        )
L
lujun 已提交
1462 1463 1464 1465 1466

        return out


class TreeConv(layers.Layer):
1467
    """
1468 1469 1470 1471 1472 1473 1474 1475
    This interface is used to construct a callable object of the ``TreeConv`` class.
    For more details, refer to code examples.
    Tree-Based Convolution is a kind of convolution based on tree structure.
    Tree-Based Convolution is a part of Tree-Based Convolution Neural Network(TBCNN),
    which is used to classify tree structures, such as Abstract Syntax Tree.
    Tree-Based Convolution proposed a kind of data structure called continuous binary tree,
    which regards multiway tree as binary tree.
    The paper of Tree-Based Convolution Operator is here: `tree-based convolution <https://arxiv.org/abs/1409.5718v1/>`_ .
1476

1477
    Parameters:
1478
        feature_size(int): last dimension of nodes_vector.
1479 1480 1481 1482 1483 1484 1485
        output_size(int): output feature width.
        num_filters(int, optional): number of filters, Default: 1.
        max_depth(int, optional): max depth of filters, Default: 2.
        act(str, optional): activation function, Default: tanh.
        param_attr(ParamAttr, optional): the parameter attribute for the filters, Default: None.
        bias_attr(ParamAttr, optional): the parameter attribute for the bias of this layer, Default: None.
        name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` .
1486
        dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32".
1487

1488 1489
    Attribute:
        **weight** (Parameter): the learnable weights of filters of this layer.
1490

1491
        **bias** (Parameter or None): the learnable bias of this layer.
1492

1493 1494
    Returns:
        None
L
lujun 已提交
1495

1496
    Examples:
L
lujun 已提交
1497

1498
        .. code-block:: python
1499

1500 1501
          import paddle.fluid as fluid
          import numpy
1502

1503 1504 1505 1506
          with fluid.dygraph.guard():
              nodes_vector = numpy.random.random((1, 10, 5)).astype('float32')
              edge_set = numpy.random.random((1, 9, 2)).astype('int32')
              treeConv = fluid.dygraph.nn.TreeConv(
1507
                feature_size=5, output_size=6, num_filters=1, max_depth=2)
1508
              ret = treeConv(fluid.dygraph.base.to_variable(nodes_vector), fluid.dygraph.base.to_variable(edge_set))
1509 1510
    """

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    def __init__(
        self,
        feature_size,
        output_size,
        num_filters=1,
        max_depth=2,
        act='tanh',
        param_attr=None,
        bias_attr=None,
        name=None,
        dtype='float32',
    ):
1523
        super().__init__()
L
lujun 已提交
1524
        self._name = name
1525
        self._feature_size = feature_size
L
lujun 已提交
1526 1527 1528 1529 1530 1531
        self._output_size = output_size
        self._act = act
        self._max_depth = max_depth
        self._num_filters = num_filters
        self._bias_attr = bias_attr
        self._param_attr = param_attr
1532 1533
        self._dtype = dtype
        w_shape = [self._feature_size, 3, self._output_size, self._num_filters]
L
lujun 已提交
1534
        if self._bias_attr:
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
            self.bias = self.create_parameter(
                attr=self._bias_attr,
                shape=[self._num_filters],
                dtype=self._dtype,
                is_bias=True,
            )
        self.weight = self.create_parameter(
            attr=self._param_attr,
            shape=w_shape,
            dtype=self._dtype,
            is_bias=False,
        )
L
lujun 已提交
1547 1548

    def forward(self, nodes_vector, edge_set):
1549 1550
        check_type(nodes_vector, 'nodes_vector', (Variable), 'TreeConv')
        check_type(edge_set, 'edge_set', (Variable), 'TreeConv')
L
lujun 已提交
1551
        if self._name:
1552 1553 1554
            out = self.create_variable(
                name=self._name, dtype=self._dtype, persistable=False
            )
L
lujun 已提交
1555 1556
        else:
            out = self._helper.create_variable_for_type_inference(
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
                dtype=self._dtype
            )
        self._helper.append_op(
            type='tree_conv',
            inputs={
                'NodesVector': nodes_vector,
                'EdgeSet': edge_set,
                'Filter': self.weight,
            },
            outputs={
                'Out': out,
            },
            attrs={'max_depth': self._max_depth},
        )
L
lujun 已提交
1571 1572
        if self._bias_attr:
            pre_activation = self._helper.create_variable_for_type_inference(
1573 1574 1575 1576 1577 1578 1579 1580
                dtype=self._dtype
            )
            self._helper.append_op(
                type='elementwise_add',
                inputs={'X': [out], 'Y': [self.bias]},
                outputs={'Out': [pre_activation]},
                attrs={'axis': 1},
            )
L
lujun 已提交
1581 1582 1583
        else:
            pre_activation = out
        return self._helper.append_activation(pre_activation, act=self._act)
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594


class Flatten(layers.Layer):
    """
    This interface is used to construct a callable object of the ``FLatten`` class.
    For more details, refer to code examples.
    It implements flatten a contiguous range of dims into a tensor.

    Parameters:
        start_axis(int): first dim to flatten (default = 1)
        stop_axis(int): last dim to flatten (default = -1).
1595

1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
    Returns:
        None

    Examples:

        .. code-block:: python

          import paddle
          import numpy as np

          inp_np = np.ones([5, 2, 3, 4]).astype('float32')
Z
Zhou Wei 已提交
1607
          inp_np = paddle.to_tensor(inp_np)
1608 1609 1610 1611 1612 1613
          flatten = paddle.nn.Flatten(start_axis=1, stop_axis=2)
          flatten_res = flatten(inp_np)

    """

    def __init__(self, start_axis=1, stop_axis=-1):
1614
        super().__init__()
1615 1616 1617 1618
        self.start_axis = start_axis
        self.stop_axis = stop_axis

    def forward(self, input):
1619 1620 1621
        out = paddle.tensor.manipulation.flatten(
            input, start_axis=self.start_axis, stop_axis=self.stop_axis
        )
1622
        return out