nn.py 100.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.
Y
Yu Yang 已提交
14
"""
15
All layers just related to the neural network.
Y
Yu Yang 已提交
16
"""
P
peizhilin 已提交
17
import os
S
sneaxiy 已提交
18
import inspect
19 20 21 22 23
import warnings

import numpy as np

import paddle
Y
Yu Yang 已提交
24
from ..layer_helper import LayerHelper
25
from paddle.fluid.framework import _in_legacy_dygraph
26
from ..initializer import Normal, Constant
27 28 29 30 31 32 33 34 35 36 37 38 39
from ..framework import (
    Variable,
    OpProtoHolder,
    _non_static_mode,
    dygraph_only,
    _dygraph_tracer,
    default_main_program,
    _varbase_creator,
    static_only,
    _global_flags,
    _in_legacy_dygraph,
    in_dygraph_mode,
)
40
from ..framework import _current_expected_place
41
from .. import dygraph_utils
Y
yangyaming 已提交
42
from ..param_attr import ParamAttr
43 44 45 46 47
from .layer_function_generator import (
    autodoc,
    templatedoc,
    _generate_doc_string_,
)
48
from .tensor import concat, assign, fill_constant, zeros, tensor_array_to_tensor
49
from . import utils
F
fengjiayi 已提交
50
from .. import unique_name
51
from functools import reduce
52
from .. import core
53
from ...utils import deprecated
54 55 56 57 58 59
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
60
from paddle.utils import deprecated
61
from paddle import _C_ops, _legacy_C_ops
62 63
from collections.abc import Iterable

Y
Yu Yang 已提交
64 65

__all__ = [
X
Xin Pan 已提交
66 67 68 69 70 71 72 73 74 75
    'fc',
    'embedding',
    'linear_chain_crf',
    'crf_decoding',
    'conv2d',
    'dropout',
    'split',
    'l2_normalize',
    'row_conv',
    'layer_norm',
D
dengkaipeng 已提交
76
    'spectral_norm',
X
Xin Pan 已提交
77 78 79 80 81 82 83 84
    'one_hot',
    'autoincreased_step_counter',
    'unsqueeze',
    'lod_reset',
    'relu',
    'clip',
    'clip_by_norm',
    'mul',
C
chengduo 已提交
85 86
    'merge_selected_rows',
    'get_tensor_from_selected_rows',
Y
Yu Yang 已提交
87 88
]

89
OP_NAMEMAPPING = {
90 91 92 93 94 95 96 97
    'elementwise_max': 'maximum',
    'elementwise_min': 'minimum',
    'elementwise_pow': 'elementwise_pow',
    'elementwise_floordiv': 'floor_divide',
    'elementwise_add': 'add',
    'elementwise_sub': 'subtract',
    'elementwise_mul': 'multiply',
    'elementwise_div': 'divide',
C
Chen Weihang 已提交
98
    'elementwise_mod': 'remainder',
99 100
}

Y
Yu Yang 已提交
101

102 103
def _get_reduce_dim(dim, input):
    """
104
    Internal function for reduce_sum, reduce_mean, reduce_prod.
105 106 107 108 109 110 111 112 113
    It computes the attribute reduce_all value based on axis.
    """
    if dim is not None and not isinstance(dim, list):
        if isinstance(dim, (tuple, range)):
            dim = list(dim)
        elif isinstance(dim, int):
            dim = [dim]
        else:
            raise TypeError(
114
                "The type of dim must be int, list, tuple or range, but received {}".format(
115
                    type(dim)
116 117
                )
            )
118 119 120 121 122 123 124 125 126 127
    if dim is None:
        dim = []
    if dim == [] or len(dim) == len(input.shape):
        reduce_all = True
    else:
        reduce_all = False

    return reduce_all, dim


128
@dygraph_only
129 130 131
def _elementwise_op_in_dygraph(
    x, y, axis=-1, act=None, use_mkldnn=False, op_name=None
):
132 133 134 135
    def is_inplace(op_name):
        return op_name[-1] == "_"

    if op_name not in OP_NAMEMAPPING.keys() or axis != -1:
136
        op = getattr(_legacy_C_ops, op_name)
137 138 139
        out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn)
    else:
        if in_dygraph_mode():
140 141
            op = getattr(
                _C_ops,
142 143
                OP_NAMEMAPPING[op_name] if not is_inplace(op_name) else op_name,
            )
144 145 146
            out = op(x, y)

        if _in_legacy_dygraph():
147
            op = getattr(_legacy_C_ops, op_name)
148
            out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn)
149 150 151 152 153 154 155 156 157 158 159 160 161 162
    return dygraph_utils._append_activation_in_dygraph(
        out, act, use_mkldnn=use_mkldnn
    )


def fc(
    input,
    size,
    num_flatten_dims=1,
    param_attr=None,
    bias_attr=None,
    act=None,
    name=None,
):
163
    r"""
164 165
    :api_attr: Static Graph

166
    **Fully Connected Layer**
Y
Yu Yang 已提交
167

168 169 170
    This operator creates a fully connected layer in the network. It can take
    a Tensor(or LoDTensor) or a list of Tensor(or LoDTensor) as its inputs(see
    Args in detail). It creates a variable called weight for each input Tensor,
171
    which represents a fully connected weight matrix from each input unit to
172 173 174 175
    each output unit. The fully connected layer multiplies each input Tensor
    with its corresponding weight to produce an output Tensor with shape :math:`[M, size]` ,
    where M is batch size. If a list of Tensor is given, the results of
    multiple output Tensors with shape :math:`[M, size]` will be summed up. If :attr:`bias_attr`
176
    is not None, a bias variable will be created and added to the output.
177
    Finally, if :attr:`act` is not None, it will be applied to the output as well.
C
caoying03 已提交
178

179
    When the input is a single Tensor(or LoDTensor):
C
caoying03 已提交
180

181 182 183 184
    .. math::

        Out = Act({XW + b})

185
    When the input is a list of Tensor(or LoDTensor):
186 187 188

    .. math::

189
        Out = Act({\sum_{i=0}^{N-1}X_iW_i + b})
190 191 192

    In the above equation:

193 194 195
    * :math:`N`: Number of the input. N equals to len(input) if input is list of Variable.
    * :math:`X_i`: The i-th input tensor.
    * :math:`W_i`: The i-th weights matrix corresponding i-th input tensor.
C
caoying03 已提交
196
    * :math:`b`: The bias parameter created by this layer (if needed).
197
    * :math:`Act`: The activation function.
198
    * :math:`Out`: The output Tensor.
199 200 201

    .. code-block:: text

202 203 204 205 206 207 208 209 210 211 212 213 214 215
        Case 1:
        Given a single Tensor data_1, and num_flatten_dims = 2:
            data_1.data = [[[0.1, 0.2],
                            [0.3, 0.4]]]
            data_1.shape = (1, 2, 2) # 1 is batch_size

            out = fluid.layers.fc(input=data_1, size=1, num_flatten_dims=2)

        Then output is:
            out.data = [[0.83234344], [0.34936576]]
            out.shape = (1, 2, 1)

        Case 2:
        Given a list of Tensor:
216 217 218 219 220 221 222 223 224 225 226 227 228
            data_1.data = [[[0.1, 0.2],
                           [0.3, 0.4]]]
            data_1.shape = (1, 2, 2) # 1 is batch_size

            data_2 = [[[0.1, 0.2, 0.3]]]
            data_2.shape = (1, 1, 3)

            out = fluid.layers.fc(input=[data_1, data_2], size=2)

        Then:
            out.data = [[0.18669507, 0.1893476]]
            out.shape = (1, 2)

Y
Yu Yang 已提交
229
    Args:
230 231 232
        input (Variable|list of Variable): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` or
            a list of Tensor(or LoDTensor). The dimensions of the input Tensor is at least 2 and the data
            type should be float32 or float64.
T
tianshuo78520a 已提交
233
        size(int): The number of output units in this layer, which also means the feature size of output
234 235
            Tensor(or LoDTensor).
        num_flatten_dims (int): The fc layer can accept an input Tensor with more than
R
ranqiu 已提交
236
            two dimensions. If this happens, the multidimensional tensor will first be flattened
237 238
            into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input
            Tensor is flattened: the first :attr:`num_flatten_dims` (inclusive, index starts from 1)
R
ranqiu 已提交
239
            dimensions will be flatten to form the first dimension of the final matrix (height of
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            the matrix), and the rest :math:`rank(X) - num\_flatten\_dims` dimensions are flattened to
            form the second dimension of the final matrix (width of the matrix). For example, assuming that
            X is a 5-dimensional Tensor with a shape [2, 3, 4, 5, 6], and :attr:`num_flatten_dims` = 3.
            Then, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default: 1.
        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` .
        bias_attr (ParamAttr): 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` .
        act (str): Activation to be applied to the output of this layer, such as tanh, softmax,
            sigmoid, relu. For more information, please refer to :ref:`api_guide_activations_en` . 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` .

    Returns:
        Variable: Tensor or LoDTensor calculated by fc layer. The data type is same with input.
255 256

    Raises:
257
        ValueError: If dimensions of the input Tensor is less than 2.
258 259 260 261

    Examples:
        .. code-block:: python

262
          import paddle.fluid as fluid
263 264
          import paddle
          paddle.enable_static()
265
          # when input is single tensor
266
          data = fluid.data(name="data", shape=[-1, 32], dtype="float32")
267
          fc = fluid.layers.fc(input=data, size=1000, act="tanh")
268 269

          # when input are multiple tensors
270 271
          data_1 = fluid.data(name="data_1", shape=[-1, 32], dtype="float32")
          data_2 = fluid.data(name="data_2", shape=[-1, 36], dtype="float32")
272
          fc = fluid.layers.fc(input=[data_1, data_2], size=1000, act="tanh")
Y
Yu Yang 已提交
273
    """
C
caoying03 已提交
274
    helper = LayerHelper("fc", **locals())
275
    check_type(input, 'input', (list, tuple, Variable), 'fc')
276 277
    if isinstance(input, (list, tuple)):
        for i, input_x in enumerate(input):
278
            check_type(input_x, 'input[' + str(i) + ']', Variable, 'fc')
Y
Yu Yang 已提交
279
    dtype = helper.input_dtype()
280 281 282
    check_dtype(
        dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc'
    )
Y
Yu Yang 已提交
283
    mul_results = []
284 285
    for input_var, param_attr in helper.iter_inputs_and_params():
        input_shape = input_var.shape
286 287
        if num_flatten_dims == -1:
            num_flatten_dims = len(input_shape) - 1
Y
Yu Yang 已提交
288 289 290
        param_shape = [
            reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
        ] + [size]
Y
ying 已提交
291

292 293 294
        w = helper.create_parameter(
            attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False
        )
X
Xin Pan 已提交
295
        tmp = helper.create_variable_for_type_inference(dtype)
296 297 298 299 300 301
        helper.append_op(
            type="mul",
            inputs={"X": input_var, "Y": w},
            outputs={"Out": tmp},
            attrs={"x_num_col_dims": num_flatten_dims, "y_num_col_dims": 1},
        )
302 303 304 305
        mul_results.append(tmp)

    if len(mul_results) == 1:
        pre_bias = mul_results[0]
306
    else:
X
Xin Pan 已提交
307
        pre_bias = helper.create_variable_for_type_inference(dtype)
308 309 310 311 312 313
        helper.append_op(
            type="sum",
            inputs={"X": mul_results},
            outputs={"Out": pre_bias},
            attrs={"use_mkldnn": False},
        )
314 315 316 317
    # add bias
    pre_activation = helper.append_bias_op(pre_bias, dim_start=num_flatten_dims)
    # add activation
    return helper.append_activation(pre_activation)
Y
Yu Yang 已提交
318 319


T
tangwei12 已提交
320
@deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding")
321 322 323 324 325 326 327 328 329
def embedding(
    input,
    size,
    is_sparse=False,
    is_distributed=False,
    padding_idx=None,
    param_attr=None,
    dtype='float32',
):
330
    r"""
331
    :api_attr: Static Graph
332

333 334 335 336 337 338 339 340 341 342 343 344
    **WARING:** This OP will be deprecated in a future release. This OP requires the
    last dimension of Tensor shape must be equal to 1. It is recommended to use
    fluid. :ref:`api_fluid_embedding` .

    The operator 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` .

    This OP requires the last dimension of Tensor shape must be equal to 1. The shape
    of output Tensor is generated by replacing the last dimension of the input Tensor shape
    with emb_size.

345
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    otherwise the program will throw an exception and exit.

    .. code-block:: text

        Case 1:

        input is a Tensor. padding_idx = -1
            input.data = [[[1], [3]], [[2], [4]], [[4], [127]]]
            input.shape = [3, 2, 1]
        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]],
363

364 365 366 367
                        [[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.
368

369
        Case 2:
370

371 372 373 374 375 376 377 378 379 380 381 382 383 384
        input is a LoDTensor with 1-level LoD. padding_idx = 0
            input.lod = [[2, 3]]
            input.data = [[1], [3], [2], [4], [0]]
            input.shape = [5, 1]
        Given size = [128, 16]
        output is a LoDTensor:
            out.lod = [[2, 3]]
            out.shape = [5, 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],
                        [0.0,         0.0,         ..., 0.0        ]]  # padding data
        It will pad all-zero data when ids is 0.
Y
Yu Yang 已提交
385 386

    Args:
387 388 389 390 391 392
        input(Variable): A Tensor or LoDTensor with type int64, which contains the id information.
            The last dimension of Tensor shape must be equal to 1. The value of the input id should
            satisfy :math:`0<= id < size[0]` .
        size(tuple|list): The shape of lookup table parameter. It should have two elements which
            indicates the size of the dictionary of embeddings and the size of each embedding vector respectively.
        is_sparse(bool): The flag indicating whether to use sparse update. This parameter only
393
            affects the performance of the backwards gradient update. It is recommended to set
394
            True because sparse update is faster. But some optimizer does not support sparse update,
395
            such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` ,
396 397 398 399 400
            :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.
401
        padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
402 403 404 405 406 407
            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,
408
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
409
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tianshuo78520a 已提交
410
            vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer`
411 412 413
            is used to load custom or pre-trained word vectors. See code example 2 for details.
        dtype(str|core.VarDesc.VarType): It refers to the data type of output Tensor.
            It must be float32 or float64. Default: float32.
Y
Yu Yang 已提交
414

415
    Returns:
416
        Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
Y
Yu Yang 已提交
417

418 419
    Examples:
        .. code-block:: python
Y
Yu Yang 已提交
420

B
bdzhuxiaoning 已提交
421
          import paddle.fluid as fluid
422
          import numpy as np
423 424
          import paddle
          paddle.enable_static()
425

426 427
          data = fluid.data(name='x', shape=[None, 1], dtype='int64')

T
tianshuo78520a 已提交
428
          # example 1
429 430 431 432 433 434 435 436 437
          emb_1 = fluid.embedding(input=data, size=[128, 64])

          # 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)
438
          emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32')
Y
Yu Yang 已提交
439 440 441
    """

    helper = LayerHelper('embedding', **locals())
442 443 444 445 446 447 448 449 450
    check_variable_and_dtype(
        input, 'input', ['int64'], 'fluid.layers.embedding'
    )
    check_dtype(
        dtype,
        'dtype',
        ['uint16', 'float16', 'float32', 'float64'],
        'fluid.layers.embedding',
    )
451 452 453 454 455 456 457 458 459

    if is_distributed:
        is_distributed = False
        warnings.warn(
            "is_distributed is go out of use, `fluid.contrib.layers.sparse_embedding` is your needed"
        )

    remote_prefetch = True if is_sparse else False

460 461 462
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
    )
X
Xin Pan 已提交
463
    tmp = helper.create_variable_for_type_inference(dtype)
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    padding_idx = (
        -1
        if padding_idx is None
        else padding_idx
        if padding_idx >= 0
        else (size[0] + padding_idx)
    )
    helper.append_op(
        type='lookup_table',
        inputs={'Ids': input, 'W': w},
        outputs={'Out': tmp},
        attrs={
            'is_sparse': is_sparse,
            'is_distributed': is_distributed,
            'remote_prefetch': remote_prefetch,
            'padding_idx': padding_idx,
        },
    )
Y
Yu Yang 已提交
482 483 484
    return tmp


485 486 487 488 489 490 491 492 493 494 495
def _pull_sparse(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
496
    r"""
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    **Pull Fleet Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    Fleet lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
            contains the IDs information.
        size(int): The embedding size parameter, which indicates the size of
            each embedding vector respectively.
        table_id(int): the fleet table id of this embedding.
        accessor_class(str): the pslib accessor of the table, default is DownpourCtrAccessor.
        ctr_label_name(str): the layer name of click.
        padding_id(int): the padding id during lookup, default is 0.
        dtype(str): The dtype refers to the data type of output tensor. Only supports
            float32 now.
        scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default
            is True.

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1)
          emb = fluid.layers.nn._pull_sparse(
              input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor")
    """
    helper = LayerHelper(name, **locals())
    inputs = helper.multiple_input()
    outs = [helper.create_variable_for_type_inference(dtype)]
    input_names = [i.name for i in inputs]
    attrs = {
        'EmbeddingDim': size,
        'TableId': table_id,
        'AccessorClass': accessor_class,
        'CtrLabelName': ctr_label_name,
        'PaddingId': padding_id,
        'ScaleSparseGrad': scale_sparse_grad,
        'InputNames': input_names,
        # this is only for compatible with embedding op
542
        'is_distributed': True,
543 544
    }
    # this is only for compatible with embedding op
545 546 547 548 549 550 551 552 553
    w, _ = helper.create_or_get_global_variable(
        name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True
    )
    helper.append_op(
        type='pull_sparse',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs=attrs,
    )
554 555 556 557 558
    if len(outs) == 1:
        return outs[0]
    return outs


559 560 561 562 563 564 565 566 567 568 569
def _pull_sparse_v2(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
570
    r"""
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    **Pull Fleet Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    Fleet lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
            contains the IDs information.
        size(int): The embedding size parameter, which indicates the size of
            each embedding vector respectively.
        table_id(int): the pslib table id of this embedding.
        accessor_class(str): the fleet accessor of the table, default is DownpourCtrAccessor.
        ctr_label_name(str): the layer name of click.
        padding_id(int): the padding id during lookup, default is 0.
        dtype(str): The dtype refers to the data type of output tensor. Only supports
            float32 now.
        scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default
            is True.

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1)
          emb = fluid.layers.nn._pull_sparse_v2(
              input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor")
    """
    helper = LayerHelper(name, **locals())
    inputs = helper.multiple_input()
    outs = [helper.create_variable_for_type_inference(dtype)]
    input_names = [i.name for i in inputs]
    attrs = {
        'EmbeddingDim': size,
        'TableId': table_id,
        'AccessorClass': accessor_class,
        'CtrLabelName': ctr_label_name,
        'PaddingId': padding_id,
        'ScaleSparseGrad': scale_sparse_grad,
        'InputNames': input_names,
        # this is only for compatible with embedding op
616
        'is_distributed': True,
617 618
    }
    # this is only for compatible with embedding op
619 620 621 622 623 624 625 626 627
    w, _ = helper.create_or_get_global_variable(
        name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True
    )
    helper.append_op(
        type='pull_sparse_v2',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs=attrs,
    )
628
    if len(outs) == 1:
Y
yaoxuefeng 已提交
629 630 631 632
        return outs[0]
    return outs


633 634 635
def _pull_gpups_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
Y
yaoxuefeng 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648
    r"""
    **Pull GpuPS Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    GpuPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
            contains the IDs information.
        size(int|list of int): The embedding size parameter of each input, which indicates the size of
            each embedding vector respectively.
        dtype(str): The dtype refers to the data type of output tensor. Only supports
649
        float32 now.
Y
yaoxuefeng 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs, whose size are indicated by size respectively.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          slots = []
          data_1 = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1)
          slots.append(data_1)
          data_2 = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1)
          slots.append(data_2)
          embs = fluid.layers.pull_gpups_sparse(input=slots, size=[11, 35])
    """
    helper = LayerHelper('pull_gpups_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
669 670 671
            "GpuPS only support float type embedding now, and your type is: "
            + dtype
        )
Y
yaoxuefeng 已提交
672 673 674 675 676 677
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
678 679 680 681 682 683 684 685 686 687 688 689 690
    w = helper.create_parameter(
        attr=helper.param_attr, shape=[size[0]], dtype=dtype, is_bias=False
    )
    helper.append_op(
        type='pull_gpups_sparse',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs={
            'size': size,
            'is_distributed': is_distributed,
            'is_sparse': is_sparse,
        },
    )
Y
yaoxuefeng 已提交
691
    if len(outs) == 1:
692 693 694 695
        return outs[0]
    return outs


696 697 698
def _pull_box_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
699
    r"""
H
hutuxian 已提交
700 701 702 703 704 705 706
    **Pull Box Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    BoxPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
707
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
H
hutuxian 已提交
708
            contains the IDs information.
709
        size(int): The embedding size parameter, which indicates the size of
H
hutuxian 已提交
710
            each embedding vector respectively.
711
        dtype(str): The dtype refers to the data type of output tensor. Only supports
712
        float32 now.
H
hutuxian 已提交
713 714 715 716 717 718 719 720 721 722

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1)
723
          emb = fluid.layers.pull_box_sparse(input=data, size=[11])
H
hutuxian 已提交
724 725 726 727
    """
    helper = LayerHelper('pull_box_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
728 729 730
            "BoxPS only support float type embedding now, and your type is: "
            + dtype
        )
H
hutuxian 已提交
731 732 733 734 735 736
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
737 738 739 740 741 742 743 744 745 746 747 748 749
    w = helper.create_parameter(
        attr=helper.param_attr, shape=[size], dtype=dtype, is_bias=False
    )
    helper.append_op(
        type='pull_box_sparse',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs={
            'size': size,
            'is_distributed': is_distributed,
            'is_sparse': is_sparse,
        },
    )
H
hutuxian 已提交
750 751 752 753 754
    if len(outs) == 1:
        return outs[0]
    return outs


Y
yuyang18 已提交
755
@templatedoc()
756
def linear_chain_crf(input, label, param_attr=None, length=None):
Y
yuyang18 已提交
757
    """
758 759
    :api_attr: Static Graph

Y
yuyang18 已提交
760 761 762 763 764
    Linear Chain CRF.

    ${comment}

    Args:
765
        input(${emission_type}): ${emission_comment}
Y
yuyang18 已提交
766
        label(${label_type}): ${label_comment}
767
        Length(${length_type}): ${length_comment}
768
        param_attr(ParamAttr): The attribute of the learnable parameter for transition parameter.
Y
yuyang18 已提交
769 770

    Returns:
D
dzhwinter 已提交
771 772
        output(${emission_exps_type}): ${emission_exps_comment} \n
        output(${transition_exps_type}): ${transition_exps_comment} \n
773
        output(${log_likelihood_type}): ${log_likelihood_comment} \n
Y
yuyang18 已提交
774

J
JesseyXujin 已提交
775 776 777
    Examples:
        .. code-block:: python

778 779
            import paddle.fluid as fluid
            import numpy as np
780 781
            import paddle
            paddle.enable_static()
782 783 784 785 786

            #define net structure, using LodTensor
            train_program = fluid.Program()
            startup_program = fluid.Program()
            with fluid.program_guard(train_program, startup_program):
787 788
                input_data = fluid.data(name='input_data', shape=[-1,10], dtype='float32')
                label = fluid.data(name='label', shape=[-1,1], dtype='int')
789 790 791 792 793 794
                emission= fluid.layers.fc(input=input_data, size=10, act="tanh")
                crf_cost = fluid.layers.linear_chain_crf(
                    input=emission,
                    label=label,
                    param_attr=fluid.ParamAttr(
                    name='crfw',
795
                    learning_rate=0.01))
796 797 798
            use_cuda = False
            place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
            exe = fluid.Executor(place)
799
            exe.run(startup_program)
800 801 802 803 804
            #define data, using LoDTensor
            a = fluid.create_lod_tensor(np.random.rand(12,10).astype('float32'), [[3,3,4,2]], place)
            b = fluid.create_lod_tensor(np.array([[1],[1],[2],[3],[1],[1],[1],[3],[1],[1],[1],[1]]),[[3,3,4,2]] , place)
            feed1 = {'input_data':a,'label':b}
            loss= exe.run(train_program,feed=feed1, fetch_list=[crf_cost])
805
            print(loss)
806 807 808 809 810

            #define net structure, using padding
            train_program = fluid.Program()
            startup_program = fluid.Program()
            with fluid.program_guard(train_program, startup_program):
811 812 813
                input_data2 = fluid.data(name='input_data2', shape=[-1,10,10], dtype='float32')
                label2 = fluid.data(name='label2', shape=[-1,10,1], dtype='int')
                label_length = fluid.data(name='length', shape=[-1,1], dtype='int')
814 815 816 817 818 819
                emission2= fluid.layers.fc(input=input_data2, size=10, act="tanh", num_flatten_dims=2)
                crf_cost2 = fluid.layers.linear_chain_crf(
                    input=emission2,
                    label=label2,
                    length=label_length,
                    param_attr=fluid.ParamAttr(
J
JesseyXujin 已提交
820
                     name='crfw',
821 822 823 824 825 826
                     learning_rate=0.01))

            use_cuda = False
            place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(startup_program)
J
JesseyXujin 已提交
827

828 829 830
            #define data, using padding
            cc=np.random.rand(4,10,10).astype('float32')
            dd=np.random.rand(4,10,1).astype('int64')
831
            ll=np.array([[3],[3],[4],[2]])
832 833
            feed2 = {'input_data2':cc,'label2':dd,'length':ll}
            loss2= exe.run(train_program,feed=feed2, fetch_list=[crf_cost2])
834
            print(loss2)
835 836 837 838 839
            #[array([[ 7.8902354],
            #        [ 7.3602567],
            #        [ 10.004011],
            #        [ 5.86721  ]], dtype=float32)]

840 841 842
            #you can use find_var to get transition parameter.
            transition=np.array(fluid.global_scope().find_var('crfw').get_tensor())
            print(transition)
843

Y
yuyang18 已提交
844
    """
845 846 847
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'linear_chain_crf'
    )
848
    check_variable_and_dtype(label, 'label', ['int64'], 'linear_chain_crf')
Y
Yu Yang 已提交
849
    helper = LayerHelper('linear_chain_crf', **locals())
850
    size = input.shape[2] if length else input.shape[1]
851 852 853 854 855
    transition = helper.create_parameter(
        attr=helper.param_attr,
        shape=[size + 2, size],
        dtype=helper.input_dtype(),
    )
X
Xin Pan 已提交
856
    alpha = helper.create_variable_for_type_inference(
857 858
        dtype=helper.input_dtype()
    )
X
Xin Pan 已提交
859
    emission_exps = helper.create_variable_for_type_inference(
860 861
        dtype=helper.input_dtype()
    )
X
Xin Pan 已提交
862
    transition_exps = helper.create_variable_for_type_inference(
863 864
        dtype=helper.input_dtype()
    )
X
Xin Pan 已提交
865
    log_likelihood = helper.create_variable_for_type_inference(
866 867
        dtype=helper.input_dtype()
    )
868 869 870
    this_inputs = {
        "Emission": [input],
        "Transition": transition,
871
        "Label": [label],
872 873
    }
    if length:
874
        this_inputs['Length'] = [length]
875 876 877 878 879 880 881 882 883 884
    helper.append_op(
        type='linear_chain_crf',
        inputs=this_inputs,
        outputs={
            "Alpha": [alpha],
            "EmissionExps": [emission_exps],
            "TransitionExps": transition_exps,
            "LogLikelihood": log_likelihood,
        },
    )
Y
Yu Yang 已提交
885 886 887 888

    return log_likelihood


W
wopeizl 已提交
889
@templatedoc()
890
def crf_decoding(input, param_attr, label=None, length=None):
W
wopeizl 已提交
891
    """
892
    :api_attr: Static Graph
893

W
wopeizl 已提交
894
    ${comment}
Y
yi.wu 已提交
895

W
wopeizl 已提交
896
    Args:
897
        input(Tensor): ${emission_comment}
Y
yi.wu 已提交
898

899 900
        param_attr (ParamAttr|None): To specify the weight parameter attribute.
            Default: None, which means the default weight parameter property is
901
            used. See usage for details in :ref:`api_paddle_fluid_param_attr_ParamAttr` .
Y
yuyang18 已提交
902

Y
Yibing Liu 已提交
903
        label(${label_type}, optional): ${label_comment}
904

Y
Yibing Liu 已提交
905
        length(${length_type}, optional): ${length_comment}
906

W
wopeizl 已提交
907
    Returns:
908
        Tensor: ${viterbi_path_comment}
Y
yi.wu 已提交
909

W
wopeizl 已提交
910 911
    Examples:
        .. code-block:: python
Y
yi.wu 已提交
912

913 914
           import paddle
           paddle.enable_static()
915 916 917

           # LoDTensor-based example
           num_labels = 10
918 919 920
           feature = paddle.static.data(name='word_emb', shape=[-1, 784], dtype='float32', lod_level=1)
           label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64', lod_level=1)
           emission = paddle.static.nn.fc(feature, size=num_labels)
921

922 923 924 925
           crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label,
                     param_attr=paddle.ParamAttr(name="crfw"))
           crf_decode = paddle.static.nn.crf_decoding(input=emission,
                     param_attr=paddle.ParamAttr(name="crfw"))
926 927 928

           # Common tensor example
           num_labels, max_len = 10, 20
929 930 931 932
           feature = paddle.static.data(name='word_emb_pad', shape=[-1, max_len, 784], dtype='float32')
           label = paddle.static.data(name='label_pad', shape=[-1, max_len, 1], dtype='int64')
           length = paddle.static.data(name='length', shape=[-1, 1], dtype='int64')
           emission = paddle.static.nn.fc(feature, size=num_labels,
933
                                      num_flatten_dims=2)
934

935 936 937 938
           crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label, length=length,
                     param_attr=paddle.ParamAttr(name="crfw_pad"))
           crf_decode = paddle.static.nn.crf_decoding(input=emission, length=length,
                     param_attr=paddle.ParamAttr(name="crfw_pad"))
W
wopeizl 已提交
939
    """
940 941 942
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'crf_decoding'
    )
W
wopeizl 已提交
943 944 945
    helper = LayerHelper('crf_decoding', **locals())
    transition = helper.get_parameter(param_attr.name)
    viterbi_path = helper.create_variable_for_type_inference(
946 947
        dtype=core.VarDesc.VarType.INT64
    )
948 949 950
    inputs = {"Emission": [input], "Transition": transition, "Label": label}
    if length:
        inputs['Length'] = length
951 952 953 954 955
    helper.append_op(
        type='crf_decoding',
        inputs=inputs,
        outputs={"ViterbiPath": [viterbi_path]},
    )
Y
Yu Yang 已提交
956

W
wopeizl 已提交
957
    return viterbi_path
Y
Yu Yang 已提交
958 959


960
@deprecated(since="2.0.0", update_to="paddle.nn.functional.dropout")
961 962 963 964 965 966 967 968
def dropout(
    x,
    dropout_prob,
    is_test=None,
    seed=None,
    name=None,
    dropout_implementation="downgrade_in_infer",
):
969
    """
970

971 972 973 974
    Computes dropout.

    Drop or keep each element of `x` independently. Dropout is a regularization
    technique for reducing overfitting by preventing neuron co-adaption during
975
    training. The dropout operator randomly sets (according to the given dropout
976 977 978
    probability) the outputs of some units to zero, while others are remain
    unchanged.

H
haowang101779990 已提交
979 980
    dropout op can be removed from the program to make the program more efficient.

981
    Args:
L
lvmengsi 已提交
982
        x (Variable): The input tensor variable. The data type is float16 or float32 or float64.
983
        dropout_prob (float): Probability of setting units to zero.
984
        is_test (bool): A flag indicating whether it is in test phrase or not.
985
                        Default None, in dynamic graph, it use global tracer mode; in static graph, it means False.
986 987 988
        seed (int): A Python integer used to create random seeds. If this
                    parameter is set to None, a random seed is used.
                    NOTE: If an integer seed is given, always the same output
L
lvmengsi 已提交
989
                    units will be dropped. DO NOT use a fixed seed in training.Default: None.
990 991
        name (str|None): A name for this layer(optional). If set None, the layer
                         will be named automatically.
H
haowang101779990 已提交
992 993
        dropout_implementation(string): ['downgrade_in_infer'(default)|'upscale_in_train']

P
phlrain 已提交
994
                                        1. downgrade_in_infer(default), downgrade the outcome at inference
H
haowang101779990 已提交
995 996

                                           - train: out = input * mask
C
ceci3 已提交
997
                                           - inference: out = input * (1.0 - dropout_prob)
H
haowang101779990 已提交
998 999 1000

                                           (mask is a tensor same shape with input, value is 0 or 1
                                           ratio of 0 is dropout_prob)
P
phlrain 已提交
1001
                                        2. upscale_in_train, upscale the outcome at training time
1002

H
haowang101779990 已提交
1003 1004
                                           - train: out = input * mask / ( 1.0 - dropout_prob )
                                           - inference: out = input
P
phlrain 已提交
1005

H
haowang101779990 已提交
1006 1007
                                           (mask is a tensor same shape with input, value is 0 or 1
                                           ratio of 0 is dropout_prob)
1008

M
minqiyang 已提交
1009

1010
    Returns:
L
lvmengsi 已提交
1011
        A Variable holding Tensor representing the dropout, has same shape and data type with `x`.
1012 1013

    Examples:
1014

1015 1016
        .. code-block:: python

1017
            import paddle
1018
            import paddle.fluid as fluid
1019

1020
            paddle.enable_static()
L
lvmengsi 已提交
1021
            x = fluid.data(name="data", shape=[None, 32, 32], dtype="float32")
T
tianshuo78520a 已提交
1022
            dropped = fluid.layers.dropout(x, dropout_prob=0.5)
1023
    """
1024 1025
    if not isinstance(dropout_prob, (float, int, Variable)):
        raise TypeError(
1026 1027
            "dropout_prob argument should be a number(int|float) or Variable"
        )
1028
    # fast return for p == 0
1029
    if isinstance(dropout_prob, (int, float)) and dropout_prob == 0:
1030
        return x
1031

J
Jiabin Yang 已提交
1032
    if _non_static_mode():
1033 1034 1035
        if (
            seed is None or seed == 0
        ) and default_main_program().random_seed != 0:
1036
            seed = default_main_program().random_seed
1037 1038
        if is_test is None:
            is_test = not _dygraph_tracer()._train_mode
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        out, mask = _legacy_C_ops.dropout(
            x,
            'dropout_prob',
            dropout_prob,
            'is_test',
            is_test,
            'fix_seed',
            seed is not None,
            'seed',
            seed if seed is not None else 0,
            'dropout_implementation',
            dropout_implementation,
        )
1052
        return out
1053

W
wanghuancoder 已提交
1054 1055 1056
    def get_attrs(prog, dropout_prob, is_test, seed):
        if (seed is None or seed == 0) and prog.random_seed != 0:
            seed = prog.random_seed
1057 1058
        if isinstance(dropout_prob, Variable) and not dropout_prob.shape != [1]:
            raise TypeError(
1059 1060 1061 1062
                "Required dropout_prob.shape == [1] if type(dropout_prob) is Variable, but received dropout_prob.shape = {}".format(
                    dropout_prob.shape
                )
            )
W
wanghuancoder 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071
        attrs = {
            'dropout_prob': dropout_prob,
            'is_test': is_test,
            'fix_seed': seed is not None,
            'seed': seed if seed is not None else 0,
            'dropout_implementation': dropout_implementation,
        }
        return attrs

F
fengjiayi 已提交
1072
    helper = LayerHelper('dropout', **locals())
1073 1074 1075
    check_variable_and_dtype(
        x, 'x', ['float16', 'float32', 'float64'], 'dropout'
    )
1076

X
Xin Pan 已提交
1077 1078
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
    mask = helper.create_variable_for_type_inference(
1079 1080
        dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
    )
C
chengduo 已提交
1081

1082
    attrs = get_attrs(helper.main_program, dropout_prob, is_test, seed)
C
chengduo 已提交
1083

1084 1085 1086 1087 1088 1089
    helper.append_op(
        type='dropout',
        inputs={'X': [x]},
        outputs={'Out': [out], 'Mask': [mask]},
        attrs=attrs,
    )
1090 1091 1092
    return out


1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
def conv2d(
    input,
    num_filters,
    filter_size,
    stride=1,
    padding=0,
    dilation=1,
    groups=None,
    param_attr=None,
    bias_attr=None,
    use_cudnn=True,
    act=None,
    name=None,
    data_format="NCHW",
):
1108
    r"""
1109 1110
    :api_attr: Static Graph

C
chengduoZH 已提交
1111
    The convolution2D layer calculates the output based on the input, filter
T
tensor-tang 已提交
1112
    and strides, paddings, dilations, groups parameters. Input and
L
liym27 已提交
1113
    Output are in NCHW or NHWC format, where N is batch size, C is the number of
1114
    channels, H is the height of the feature, and W is the width of the feature.
T
tensor-tang 已提交
1115 1116 1117 1118 1119 1120
    Filter is in MCHW format, where M is the number of output image channels,
    C is the number of input image channels, H is the height of the filter,
    and W is the width of the filter. If the groups is greater than 1,
    C will equal the number of input image channels divided by the groups.
    Please refer to UFLDL's `convolution
    <http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_
1121
    for more details.
1122 1123 1124
    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.
C
chengduoZH 已提交
1125

1126
    For each input :math:`X`, the equation is:
C
refine  
chengduoZH 已提交
1127

C
chengduoZH 已提交
1128 1129
    .. math::

C
refine  
chengduoZH 已提交
1130
        Out = \sigma (W \\ast X + b)
C
chengduoZH 已提交
1131

T
tensor-tang 已提交
1132
    Where:
C
chengduoZH 已提交
1133

L
liym27 已提交
1134
    * :math:`X`: Input value, a tensor with NCHW or NHWC format.
1135 1136 1137 1138
    * :math:`W`: Filter value, a tensor with MCHW format.
    * :math:`\\ast`: Convolution operation.
    * :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
    * :math:`\\sigma`: Activation function.
T
tensor-tang 已提交
1139
    * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
C
chengduoZH 已提交
1140 1141 1142

    Example:

1143 1144
        - Input:

W
weixing02 已提交
1145
          Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
C
refine  
chengduoZH 已提交
1146

W
weixing02 已提交
1147
          Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
C
refine  
chengduoZH 已提交
1148

1149
        - Output:
T
tensor-tang 已提交
1150

W
weixing02 已提交
1151
          Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
C
refine  
chengduoZH 已提交
1152

C
chengduoZH 已提交
1153
        Where
1154 1155

        .. math::
C
chengduoZH 已提交
1156

W
weixing02 已提交
1157 1158
            H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\
            W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
C
chengduoZH 已提交
1159 1160

    Args:
1161
        input (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type
L
lvmengsi 已提交
1162
            of input is float16 or float32 or float64.
T
tensor-tang 已提交
1163
        num_filters(int): The number of filter. It is as same as the output
1164
            image channel.
1165 1166
        filter_size (int|tuple): The filter size. If filter_size
            is a tuple, it must contain two integers, (filter_size_height,
L
lvmengsi 已提交
1167 1168
            filter_size_width). Otherwise, filter_size_height = filter_size_width =\
            filter_size.
1169 1170
        stride (int|tuple): The stride size. It means the stride in convolution.
            If stride is a tuple, it must contain two integers, (stride_height, stride_width).
L
lvmengsi 已提交
1171 1172
            Otherwise, stride_height = stride_width = stride. Default: stride = 1.
        padding (string|int|list|tuple): The padding size. It means the number of zero-paddings
T
tianshuo78520a 已提交
1173
            on both sides for each dimension.If `padding` is a string, either 'VALID' or
L
liym27 已提交
1174 1175
            'SAME' which is the padding algorithm. If padding size is a tuple or list,
            it could be in three forms: `[pad_height, pad_width]` or
1176 1177
            `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when
            `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0],
L
lvmengsi 已提交
1178
            [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
L
liym27 已提交
1179 1180 1181
            when `data_format` is `"NHWC"`, `pool_padding` can be in the form
            `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
            Default: padding = 0.
L
lvmengsi 已提交
1182
        dilation (int|tuple): The dilation size. It means the spacing between the kernel
1183 1184
            points. If dilation is a tuple, it must contain two integers, (dilation_height,
            dilation_width). Otherwise, dilation_height = dilation_width = dilation.
L
lvmengsi 已提交
1185
            Default: dilation = 1.
1186 1187 1188 1189
        groups (int): The groups number of the Conv2d Layer. According to grouped
            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
C
chengduo 已提交
1190 1191 1192 1193 1194
            connected to the second half of the input channels. Default: groups=1.
        param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights
            of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
            will create ParamAttr as param_attr. If the Initializer of the param_attr
            is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
H
haowang101779990 已提交
1195
            and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
C
chengduo 已提交
1196 1197 1198 1199 1200
        bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d.
            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, conv2d
            will create ParamAttr as bias_attr. If the Initializer of the bias_attr
            is not set, the bias is initialized zero. Default: None.
1201 1202
        use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn
            library is installed. Default: True
C
chengduo 已提交
1203 1204
        act (str): Activation type, if it is set to None, activation is not appended.
            Default: None
1205 1206
        name(str|None): For detailed information, please refer
           to :ref:`api_guide_Name`. Usually name is no need to set and
L
lvmengsi 已提交
1207
           None by default.
1208
        data_format (str, optional): Specify the data format of the input, and the data format of the output
1209
            will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`.
L
liym27 已提交
1210 1211
            The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`.
C
chengduoZH 已提交
1212 1213

    Returns:
1214 1215 1216
        A Tensor representing the conv2d, whose data type is the
        same with input. If act is None, the tensor storing the convolution
        result, and if act is not None, the tensor storing convolution
L
lvmengsi 已提交
1217
        and non-linearity activation result.
C
refine  
chengduoZH 已提交
1218

1219 1220 1221 1222 1223
    Raises:
        ValueError: If the type of `use_cudnn` is not bool.
        ValueError: If `data_format` is not "NCHW" or "NHWC".
        ValueError: If the channel dimmention of the input is less than or equal to zero.
        ValueError: If `padding` is a string, but not "SAME" or "VALID".
1224
        ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0
1225 1226 1227 1228 1229 1230 1231
            or the element corresponding to the input's channel is not 0.
        ShapeError: If the input is not 4-D Tensor.
        ShapeError: If the input's dimension size and filter's dimension size not equal.
        ShapeError: If the dimension size of input minus the size of `stride` is not 2.
        ShapeError: If the number of input channels is not equal to filter's channels * groups.
        ShapeError: If the number of output channels is not be divided by groups.

C
chengduoZH 已提交
1232 1233 1234
    Examples:
        .. code-block:: python

1235 1236
          import paddle
          paddle.enable_static()
1237

1238 1239 1240
          data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32')
          conv2d = paddle.static.nn.conv2d(input=data, num_filters=2, filter_size=3, act="relu")
          print(conv2d.shape) # [-1, 2, 30, 30]
Y
Yu Yang 已提交
1241 1242
    """

1243 1244 1245
    check_variable_and_dtype(
        input, 'input', ['float16', 'float32', 'float64'], 'conv2d'
    )
1246
    if len(input.shape) != 4:
1247 1248 1249 1250
        raise ValueError(
            "Input size should be 4, "
            "but received {}".format(len(input.shape))
        )
1251
    num_channels = input.shape[1]
L
liym27 已提交
1252
    if not isinstance(use_cudnn, bool):
1253 1254 1255 1256
        raise ValueError(
            "Attr(use_cudnn) should be True or False. Received "
            "Attr(use_cudnn): %s. " % str(use_cudnn)
        )
L
liym27 已提交
1257 1258 1259 1260

    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
1261 1262
            "Attr(data_format): %s." % str(data_format)
        )
L
liym27 已提交
1263

1264
    channel_last = data_format == "NHWC"
L
liym27 已提交
1265 1266 1267 1268
    num_channels = input.shape[3] if channel_last else input.shape[1]
    if num_channels < 0:
        raise ValueError(
            "The channel dimmention of the input(%s) should be defined. "
1269 1270
            "Received: %s." % (str(input.shape), str(num_channels))
        )
C
chengduo 已提交
1271
    assert param_attr is not False, "param_attr should not be False here."
L
liym27 已提交
1272

1273 1274 1275
    if groups is None:
        num_filter_channels = num_channels
    elif groups <= 0:
1276 1277
        raise ValueError(
            "the groups of input must be greater than 0, "
1278 1279
            "but received the groups of input is {}".format(groups)
        )
1280 1281 1282 1283 1284
    else:
        if num_channels % groups != 0:
            raise ValueError(
                "the channel of input must be divisible by groups,"
                "received: the channel of input is {}, the shape of input is {}"
1285 1286
                ", the groups is {}".format(num_channels, input.shape, groups)
            )
1287 1288
        num_filter_channels = num_channels // groups

1289
    l_type = 'conv2d'
1290 1291 1292 1293 1294
    if (
        num_channels == groups
        and num_filters % num_channels == 0
        and not use_cudnn
    ):
1295
        l_type = 'depthwise_conv2d'
1296

1297 1298 1299 1300 1301
    if (
        num_channels == groups
        and num_filters % num_channels == 0
        and core.is_compiled_with_rocm()
    ):
1302 1303
        l_type = 'depthwise_conv2d'

1304 1305
    # NPU only supports depthwise_conv2d when  "input_channel = output_channel = groups"
    if core.is_compiled_with_npu():
1306
        if num_channels == groups and num_channels == num_filters:
1307 1308 1309 1310
            l_type = 'depthwise_conv2d'
        else:
            l_type = 'conv2d'

1311 1312 1313
    helper = LayerHelper(l_type, **locals())
    dtype = helper.input_dtype()

C
chengduoZH 已提交
1314 1315
    filter_size = utils.convert_to_list(filter_size, 2, 'filter_size')
    stride = utils.convert_to_list(stride, 2, 'stride')
1316
    dilation = utils.convert_to_list(dilation, 2, 'dilation')
C
chengduoZH 已提交
1317

L
liym27 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    # padding
    def _update_padding(padding, data_format):
        def is_list_or_tuple(ele):
            if isinstance(ele, list) or isinstance(ele, tuple):
                return True
            return False

        if is_list_or_tuple(padding) and len(padding) == 4:
            if is_list_or_tuple(padding[0]) and (data_format == "NCHW"):
                if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
                    raise ValueError(
                        "Non-zero padding(%s) in the batch or channel dimensions "
1330 1331
                        "is not supported." % str(padding)
                    )
L
liym27 已提交
1332 1333 1334 1335 1336 1337
                padding = padding[2:4]
                padding = [ele for a_list in padding for ele in a_list]
            elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"):
                if not (padding[0] == [0, 0] and padding[3] == [0, 0]):
                    raise ValueError(
                        "Non-zero padding(%s) in the batch or channel dimensions "
1338 1339
                        "is not supported." % str(padding)
                    )
L
liym27 已提交
1340 1341 1342
                padding = padding[1:3]
                padding = [ele for a_list in padding for ele in a_list]
            padding = utils.convert_to_list(padding, 4, 'padding')
1343 1344 1345
            if utils._is_symmetric_padding(padding, 2):
                padding = [padding[0], padding[2]]

L
liym27 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        else:
            padding = utils.convert_to_list(padding, 2, 'padding')

        return padding

    padding_algorithm = "EXPLICIT"
    if isinstance(padding, str):
        padding = padding.upper()
        if padding not in ["SAME", "VALID"]:
            raise ValueError(
1356 1357 1358
                "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'."
                % str(padding)
            )
L
liym27 已提交
1359 1360
        if padding == "VALID":
            padding_algorithm = "VALID"
1361
            padding = [0, 0]
L
liym27 已提交
1362 1363
        elif padding == "SAME":
            padding_algorithm = "SAME"
1364
            padding = [0, 0]
L
liym27 已提交
1365 1366

    padding = _update_padding(padding, data_format)
Y
Yu Yang 已提交
1367

M
minqiyang 已提交
1368
    filter_shape = [num_filters, int(num_filter_channels)] + filter_size
Y
Yu Yang 已提交
1369 1370

    def _get_default_param_initializer():
C
chengduo 已提交
1371
        filter_elem_num = filter_size[0] * filter_size[1] * num_channels
1372 1373 1374 1375
        if filter_elem_num <= 0:
            raise ValueError(
                "Invalid filter number, excepted number is larger than 0, but"
                " received {}, please check the input shape and "
1376 1377 1378
                "filter size.".format(filter_elem_num)
            )
        std = (2.0 / filter_elem_num) ** 0.5
Y
Yu Yang 已提交
1379 1380 1381 1382 1383 1384
        return Normal(0.0, std, 0)

    filter_param = helper.create_parameter(
        attr=helper.param_attr,
        shape=filter_shape,
        dtype=dtype,
1385 1386
        default_initializer=_get_default_param_initializer(),
    )
Y
Yu Yang 已提交
1387

X
Xin Pan 已提交
1388
    pre_bias = helper.create_variable_for_type_inference(dtype)
Y
Yu Yang 已提交
1389

1390 1391 1392 1393 1394 1395
    if (
        core.is_compiled_with_cuda()
        and paddle.fluid.get_flags("FLAGS_conv2d_disable_cudnn")[
            "FLAGS_conv2d_disable_cudnn"
        ]
    ):
1396 1397
        use_cudnn = False

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
    helper.append_op(
        type=l_type,
        inputs={
            'Input': input,
            'Filter': filter_param,
        },
        outputs={"Output": pre_bias},
        attrs={
            'strides': stride,
            'paddings': padding,
            'dilations': dilation,
            'groups': groups,
            'use_cudnn': use_cudnn,
            'use_mkldnn': False,
            'fuse_relu_before_depthwise_conv': False,
            "padding_algorithm": padding_algorithm,
            "data_format": data_format,
        },
    )
Y
Yu Yang 已提交
1417

1418 1419 1420 1421
    if data_format == 'NCHW':
        pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2)
    else:
        pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4)
Y
Yu Yang 已提交
1422 1423 1424 1425

    return helper.append_activation(pre_act)


Y
yuyang18 已提交
1426
@templatedoc()
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
def layer_norm(
    input,
    scale=True,
    shift=True,
    begin_norm_axis=1,
    epsilon=1e-05,
    param_attr=None,
    bias_attr=None,
    act=None,
    name=None,
):
1438
    r"""
1439 1440
    :api_attr: Static Graph

1441 1442 1443 1444
    **Layer Normalization Layer**

    The API implements the function of the Layer Normalization Layer and can be applied to mini-batch input data.
    Refer to `Layer Normalization <https://arxiv.org/pdf/1607.06450v1.pdf>`_
G
guosheng 已提交
1445 1446 1447

    The formula is as follows:

Y
yuyang18 已提交
1448
    ..  math::
G
guosheng 已提交
1449

1450
        \\mu & = \\frac{1}{H}\\sum_{i=1}^{H} x_i
G
guosheng 已提交
1451

1452
        \\sigma & = \\sqrt{\\frac{1}{H}\sum_{i=1}^{H}{(x_i - \\mu)^2} + \\epsilon}
Y
yuyang18 已提交
1453

1454
        y & = f(\\frac{g}{\\sigma}(x - \\mu) + b)
Y
yuyang18 已提交
1455

1456 1457 1458 1459 1460
    - :math:`x`: the vector representation of the summed inputs to the neurons in that layer.
    - :math:`H`: the number of hidden units in a layers
    - :math:`\\epsilon`: the small value added to the variance to prevent division by zero.
    - :math:`g`: the trainable scale parameter.
    - :math:`b`: the trainable bias parameter.
Y
yuyang18 已提交
1461

G
guosheng 已提交
1462
    Args:
1463
        input(Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64.
1464 1465 1466 1467 1468
        scale(bool, optional): Whether to learn the adaptive gain :math:`g` after
            normalization. Default: True.
        shift(bool, optional): Whether to learn the adaptive bias :math:`b` after
            normalization. Default: True.
        begin_norm_axis(int, optional): The normalization will be performed along
G
guosheng 已提交
1469
            dimensions from :attr:`begin_norm_axis` to :attr:`rank(input)`.
1470 1471 1472 1473
            Default: 1.
        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
S
sneaxiy 已提交
1474 1475
            gain :math:`g`. If :attr:`scale` is False, :attr:`param_attr` is
            omitted. If :attr:`scale` is True and :attr:`param_attr` is None,
1476
            a default :code:`ParamAttr` would be added as scale. The
1477 1478
            :attr:`param_attr` is initialized as 1 if it is added. Default: None.
        bias_attr(ParamAttr, optional): The parameter attribute for the learnable
S
sneaxiy 已提交
1479 1480
            bias :math:`b`. If :attr:`shift` is False, :attr:`bias_attr` is
            omitted. If :attr:`shift` is True and :attr:`param_attr` is None,
1481
            a default :code:`ParamAttr` would be added as bias. The
1482
            :attr:`bias_attr` is initialized as 0 if it is added. Default: None.
T
tianshuo78520a 已提交
1483
        act(str, optional): Activation to be applied to the output of layer normalization.
1484 1485
                  Default: None.
        name(str): 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` .
G
guosheng 已提交
1486 1487

    Returns:
1488
        Tensor: ``Tensor``  indicating the normalized result, the data type is the same as  ``input`` , and the return dimension is the same as  ``input`` .
G
guosheng 已提交
1489 1490 1491

    Examples:

1492 1493
        .. code-block:: python

1494 1495
            import paddle
            paddle.enable_static()
1496 1497 1498
            x = paddle.static.data(name='x', shape=[8, 32, 32], dtype='float32')
            output = paddle.static.nn.layer_norm(input=x, begin_norm_axis=1)
            print(output.shape)  # [8, 32, 32]
G
guosheng 已提交
1499
    """
1500 1501 1502
    assert (
        _non_static_mode() is not True
    ), "please use LayerNorm instead of layer_norm in dygraph mode!"
G
guosheng 已提交
1503
    helper = LayerHelper('layer_norm', **locals())
1504 1505 1506
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'layer_norm'
    )
G
guosheng 已提交
1507 1508 1509 1510 1511 1512 1513
    dtype = helper.input_dtype()

    # create intput and parameters
    inputs = {'X': input}
    input_shape = input.shape
    param_shape = [reduce(lambda x, y: x * y, input_shape[begin_norm_axis:])]
    if scale:
1514 1515 1516 1517 1518 1519 1520 1521 1522
        assert (
            param_attr is not False
        ), "param_attr should not be False when using scale."
        scale = helper.create_parameter(
            attr=helper.param_attr,
            shape=param_shape,
            dtype=dtype,
            default_initializer=Constant(1.0),
        )
G
guosheng 已提交
1523
        inputs['Scale'] = scale
1524 1525
    else:
        if param_attr:
T
tianshuo78520a 已提交
1526
            warnings.warn("param_attr is only available with scale is True.")
G
guosheng 已提交
1527
    if shift:
1528 1529 1530 1531 1532 1533
        assert (
            bias_attr is not False
        ), "bias_attr should not be False when using shift."
        bias = helper.create_parameter(
            attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True
        )
G
guosheng 已提交
1534
        inputs['Bias'] = bias
1535 1536
    else:
        if bias_attr:
T
tianshuo78520a 已提交
1537
            warnings.warn("bias_attr is only available with shift is True.")
G
guosheng 已提交
1538 1539

    # create output
1540 1541 1542 1543 1544 1545
    mean_out = helper.create_variable_for_type_inference(
        dtype=dtype, stop_gradient=True
    )
    variance_out = helper.create_variable_for_type_inference(
        dtype=dtype, stop_gradient=True
    )
X
Xin Pan 已提交
1546
    layer_norm_out = helper.create_variable_for_type_inference(dtype)
G
guosheng 已提交
1547

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
    helper.append_op(
        type="layer_norm",
        inputs=inputs,
        outputs={
            "Y": layer_norm_out,
            "Mean": mean_out,
            "Variance": variance_out,
        },
        attrs={"epsilon": epsilon, "begin_norm_axis": begin_norm_axis},
    )
G
guosheng 已提交
1558 1559 1560 1561

    return helper.append_activation(layer_norm_out)


D
dengkaipeng 已提交
1562
@templatedoc()
1563
def spectral_norm(weight, dim=0, power_iters=1, eps=1e-12, name=None):
1564
    r"""
1565 1566
    :api_attr: Static Graph

D
dengkaipeng 已提交
1567 1568
    **Spectral Normalization Layer**

K
Kaipeng Deng 已提交
1569
    This operation calculates the spectral normalization value of weight parameters of
1570
    fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D
K
Kaipeng Deng 已提交
1571 1572
    Parameters. Output tensor will be in same shape with input tensor.
    Calculations are showed as follows.
1573

D
dengkaipeng 已提交
1574 1575 1576
    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,
D
dengkaipeng 已提交
1577
    and W is the product result of remaining dimensions.
D
dengkaipeng 已提交
1578 1579

    Step 2:
T
tianshuo78520a 已提交
1580
    :attr:`power_iters` should be a positive integer, do following
K
Kaipeng Deng 已提交
1581 1582
    calculations with U and V for :attr:`power_iters` rounds. Calculations
    as follows:
D
dengkaipeng 已提交
1583

1584
    .. math::
D
dengkaipeng 已提交
1585 1586 1587 1588 1589 1590

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

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

    Step 3:
D
dengkaipeng 已提交
1591
    Calculate :math:`\sigma(\mathbf{W})` and normalize weight values.
D
dengkaipeng 已提交
1592 1593 1594 1595

    .. math::

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

D
dengkaipeng 已提交
1597
        \mathbf{W} = \\frac{\mathbf{W}}{\sigma(\mathbf{W})}
1598

1599

D
dengkaipeng 已提交
1600 1601 1602
    Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ .

    Args:
C
Chen Long 已提交
1603
        weight(Tensor): ${weight_comment}
D
dengkaipeng 已提交
1604 1605 1606
        dim(int): ${dim_comment}
        power_iters(int): ${power_iters_comment}
        eps(float): ${eps_comment}
K
Kaipeng Deng 已提交
1607 1608 1609
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
D
dengkaipeng 已提交
1610 1611

    Returns:
C
Chen Long 已提交
1612
        Tensor: A tensor of weight parameters after spectral normalization.
K
Kaipeng Deng 已提交
1613
                  The data type and shape is same as input tensor.
D
dengkaipeng 已提交
1614 1615

    Examples:
K
Kaipeng Deng 已提交
1616
       .. code-block:: python
D
dengkaipeng 已提交
1617

1618
            import paddle
K
Kaipeng Deng 已提交
1619

1620
            paddle.enable_static()
C
Chen Long 已提交
1621
            weight = paddle.static.data(name='weight', shape=[2, 8, 32, 32], dtype='float32')
1622
            x = paddle.static.nn.spectral_norm(weight=weight, dim=1, power_iters=2)
C
Chen Long 已提交
1623
            print(x.shape) # [2, 8, 32, 32]
D
dengkaipeng 已提交
1624 1625
    """
    helper = LayerHelper('spectral_norm', **locals())
1626 1627 1628
    check_variable_and_dtype(
        weight, 'weight', ['float32', 'float64'], 'spectral_norm'
    )
1629 1630 1631
    check_type(dim, 'dim', int, 'spectral_norm')
    check_type(power_iters, 'power_iters', int, 'spectral_norm')
    check_type(eps, 'eps', float, 'spectral_norm')
1632
    dtype = weight.dtype
D
dengkaipeng 已提交
1633 1634

    # create intput and parameters
1635
    input_shape = weight.shape
1636
    assert weight.numel() > 0, "Any dimension of input cannot be equal to 0."
1637 1638 1639 1640 1641
    assert dim < len(input_shape), (
        "The input `dim` should be less than the "
        "rank of `weight`, but received dim="
        "{}".format(dim)
    )
1642 1643 1644
    h = input_shape[dim]
    w = np.prod(input_shape) // h

1645 1646 1647 1648 1649 1650
    u = helper.create_parameter(
        attr=ParamAttr(),
        shape=[h],
        dtype=dtype,
        default_initializer=Normal(0.0, 1.0),
    )
1651
    u.stop_gradient = True
1652 1653 1654 1655 1656 1657
    v = helper.create_parameter(
        attr=ParamAttr(),
        shape=[w],
        dtype=dtype,
        default_initializer=Normal(0.0, 1.0),
    )
1658
    v.stop_gradient = True
D
dengkaipeng 已提交
1659

1660 1661 1662 1663 1664 1665 1666
    if in_dygraph_mode():
        return _C_ops.spectral_norm(weight, u, v, dim, power_iters, eps)

    inputs = {'Weight': weight}
    inputs['U'] = u
    inputs['V'] = v

D
dengkaipeng 已提交
1667
    # create output
1668
    out = helper.create_variable(dtype=dtype)
D
Dun 已提交
1669

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    helper.append_op(
        type="spectral_norm",
        inputs=inputs,
        outputs={
            "Out": out,
        },
        attrs={
            "dim": dim,
            "power_iters": power_iters,
            "eps": eps,
        },
    )
D
Dun 已提交
1682

1683
    return out
D
Dun 已提交
1684 1685


C
caoying03 已提交
1686
def reduce_sum(input, dim=None, keep_dim=False, name=None):
G
guosheng 已提交
1687
    """
1688

Y
yangyaming 已提交
1689
    Computes the sum of tensor elements over the given dimension.
G
guosheng 已提交
1690 1691

    Args:
1692 1693 1694
        input (Variable): The input variable which is a Tensor, the data type is float32,
            float64, int32, int64.
        dim (list|int, optional): The dimensions along which the sum is performed. If
Y
yangyaming 已提交
1695 1696
            :attr:`None`, sum all elements of :attr:`input` and return a
            Tensor variable with a single element, otherwise must be in the
W
whs 已提交
1697 1698
            range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`,
            the dimension to reduce is :math:`rank + dim[i]`.
1699
        keep_dim (bool, optional): Whether to reserve the reduced dimension in the
Y
yangyaming 已提交
1700
            output Tensor. The result tensor will have one fewer dimension
1701 1702 1703 1704
            than the :attr:`input` unless :attr:`keep_dim` is true, default
            value is False.
        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`
G
guosheng 已提交
1705 1706

    Returns:
1707 1708
        Variable: Tensor, results of summation operation on the specified dim of input tensor,
        it's data type is the same as input's Tensor.
F
fengjiayi 已提交
1709

1710 1711
    Raises:
        TypeError, if out data type is different with the input data type.
1712

G
guosheng 已提交
1713 1714 1715
    Examples:
        .. code-block:: python

1716
            import paddle.fluid as fluid
1717 1718
            import paddle
            paddle.enable_static()
G
guosheng 已提交
1719 1720 1721
            # x is a Tensor variable with following elements:
            #    [[0.2, 0.3, 0.5, 0.9]
            #     [0.1, 0.2, 0.6, 0.7]]
Q
qiaolongfei 已提交
1722
            # Each example is followed by the corresponding output tensor.
1723
            x = fluid.data(name='x', shape=[2, 4], dtype='float32')
G
guosheng 已提交
1724 1725 1726 1727
            fluid.layers.reduce_sum(x)  # [3.5]
            fluid.layers.reduce_sum(x, dim=0)  # [0.3, 0.5, 1.1, 1.6]
            fluid.layers.reduce_sum(x, dim=-1)  # [1.9, 1.6]
            fluid.layers.reduce_sum(x, dim=1, keep_dim=True)  # [[1.9], [1.6]]
W
whs 已提交
1728

1729
            # y is a Tensor variable with shape [2, 2, 2] and elements as below:
W
whs 已提交
1730 1731
            #      [[[1, 2], [3, 4]],
            #      [[5, 6], [7, 8]]]
Q
qiaolongfei 已提交
1732
            # Each example is followed by the corresponding output tensor.
1733
            y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32')
1734 1735
            fluid.layers.reduce_sum(y, dim=[1, 2]) # [10, 26]
            fluid.layers.reduce_sum(y, dim=[0, 1]) # [16, 20]
W
whs 已提交
1736

G
guosheng 已提交
1737
    """
1738 1739
    reduce_all, dim = _get_reduce_dim(dim, input)

1740
    if in_dygraph_mode():
1741
        return _C_ops.sum(input, dim, None, keep_dim)
1742
    elif _in_legacy_dygraph():
1743 1744 1745
        return _legacy_C_ops.reduce_sum(
            input, 'dim', dim, 'keep_dim', keep_dim, 'reduce_all', reduce_all
        )
1746
    attrs = {'dim': dim, 'keep_dim': keep_dim, 'reduce_all': reduce_all}
1747
    check_variable_and_dtype(
1748 1749 1750 1751 1752
        input,
        'input',
        ['float16', 'float32', 'float64', 'int32', 'int64'],
        'reduce_sum',
    )
1753
    helper = LayerHelper('reduce_sum', **locals())
X
Xin Pan 已提交
1754
    out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
1755 1756 1757 1758 1759 1760
    helper.append_op(
        type='reduce_sum',
        inputs={'X': input},
        outputs={'Out': out},
        attrs=attrs,
    )
G
guosheng 已提交
1761
    return out
G
guosheng 已提交
1762 1763


C
caoying03 已提交
1764
def split(input, num_or_sections, dim=-1, name=None):
G
guosheng 已提交
1765
    """
1766
    Split the input tensor into multiple sub-Tensors.
G
guosheng 已提交
1767 1768

    Args:
1769
        input (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64.
1770
        num_or_sections (int|list|tuple): If ``num_or_sections`` is int, then the ``num_or_sections``
1771
            indicates the number of equal sized sub-Tensors that the ``input``
1772
            will be divided into. If ``num_or_sections`` is a list or tuple, the length of it
1773 1774 1775 1776 1777
            indicates the number of sub-Tensors and the elements in it indicate the sizes of sub-Tensors'
            dimension orderly. The length of the list mustn't be larger than the ``input`` 's size of specified dim.
        dim (int|Tensor, optional): The dimension along which to split, it can be a scalar with type ``int`` or
            a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``. If :math:`dim < 0`,
            the dimension to split along is :math:`rank(input) + dim`. Default is -1.
1778
        name (str, optional): The default value is None.  Normally there is no need for user to set this property.
1779
            For more information, please refer to :ref:`api_guide_Name` .
G
guosheng 已提交
1780 1781

    Returns:
1782
        list(Tensor): The list of segmented Tensors.
G
guosheng 已提交
1783

1784
    Example:
G
guosheng 已提交
1785 1786
        .. code-block:: python

1787 1788
            import paddle.fluid as fluid

1789
            # input is a Tensor which shape is [3, 9, 5]
1790
            input = fluid.data(
1791 1792
                 name="input", shape=[3, 9, 5], dtype="float32")

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
            out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=1)
            # out0.shape [3, 3, 5]
            # out1.shape [3, 3, 5]
            # out2.shape [3, 3, 5]

            out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, 4], dim=1)
            # out0.shape [3, 2, 5]
            # out1.shape [3, 3, 5]
            # out2.shape [3, 4, 5]

            out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, -1], dim=1)
            # out0.shape [3, 2, 5]
            # out1.shape [3, 3, 5]
            # out2.shape [3, 4, 5]
1807

1808 1809 1810 1811 1812 1813
            # dim is negative, the real dim is (rank(input) + axis) which real
            # value is 1.
            out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=-2)
            # out0.shape [3, 3, 5]
            # out1.shape [3, 3, 5]
            # out2.shape [3, 3, 5]
1814

G
guosheng 已提交
1815
    """
J
Jiabin Yang 已提交
1816
    if _non_static_mode():
1817 1818 1819
        num = None
        attrs = ()

S
songyouwei 已提交
1820 1821
        if isinstance(dim, Variable):
            dim = dim.numpy()
1822
            dim = dim.item(0)
W
wangzhen38 已提交
1823
        assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0"
S
songyouwei 已提交
1824
        dim = (len(input.shape) + dim) if dim < 0 else dim
1825
        attrs += ('axis', dim)
1826 1827 1828

        if isinstance(num_or_sections, int):
            num = num_or_sections
1829
            attrs += ('num', num_or_sections)
L
Leo Chen 已提交
1830
        elif isinstance(num_or_sections, (list, tuple)):
1831
            num = len(num_or_sections)
L
Leo Chen 已提交
1832
            if utils._contain_var(num_or_sections):
1833 1834
                for index, item in enumerate(num_or_sections):
                    if isinstance(item, Variable):
1835 1836 1837
                        num_or_sections[index] = num_or_sections[index].numpy()[
                            0
                        ]
1838
                attrs += ('sections', list(num_or_sections))
L
Leo Chen 已提交
1839
            else:
1840
                attrs += ('sections', list(num_or_sections))
1841 1842
        else:
            raise TypeError(
1843
                "The type of 'num_or_sections' in split must be int, list or tuple in imperative mode, but "
1844 1845
                "received %s." % (type(num_or_sections))
            )
1846
        if in_dygraph_mode():
C
Charles-hit 已提交
1847 1848 1849 1850
            if isinstance(num_or_sections, int):
                return _C_ops.split_with_num(input, num_or_sections, dim)
            else:
                return _C_ops.split(input, num_or_sections, dim)
1851 1852
        elif _in_legacy_dygraph():
            out = [_varbase_creator() for n in range(num)]
1853
            _legacy_C_ops.split(input, out, *attrs)
1854
            return out
L
Leo Chen 已提交
1855

1856
    check_variable_and_dtype(
1857 1858 1859 1860 1861
        input,
        'input',
        ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
        'split',
    )
1862 1863 1864 1865
    check_type(num_or_sections, 'num_or_sections', (list, int, tuple), 'split')
    check_type(dim, 'dim', (int, Variable), 'split')
    if isinstance(dim, Variable):
        check_dtype(dim.dtype, 'dim', ['int32', 'int64'], 'split')
1866

G
guosheng 已提交
1867
    helper = LayerHelper('split', **locals())
1868

G
guosheng 已提交
1869
    input_shape = input.shape
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
    inputs = {'X': input}
    attrs = {'num': num_or_sections if isinstance(num_or_sections, int) else 0}

    def _get_SectionsTensorList(one_list):
        tensor_list = []
        unk_dim_idx = -1
        for idx, dim_size in enumerate(one_list):
            if isinstance(dim_size, Variable):
                dim_size.stop_gradient = True
                tensor_list.append(dim_size)
            else:
1881
                assert isinstance(dim_size, int)
1882 1883 1884
                if dim_size == -1:
                    assert unk_dim_idx == -1, (
                        "Only one value of 'num_or_section' in split can "
1885 1886 1887
                        "be -1. But received num_or_section[%d] is also -1."
                        % idx
                    )
1888 1889
                    unk_dim_idx = idx
                temp_out = helper.create_variable_for_type_inference('int32')
1890 1891 1892
                fill_constant(
                    [1], 'int32', dim_size, force_cpu=True, out=temp_out
                )
1893 1894 1895 1896 1897 1898 1899
                tensor_list.append(temp_out)
        return tensor_list

    if isinstance(dim, Variable):
        dim.stop_gradient = True
        inputs['AxisTensor'] = dim
    else:
W
wangzhen38 已提交
1900
        assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0"
1901 1902 1903
        dim = (len(input_shape) + dim) if dim < 0 else dim
        attrs['axis'] = dim

G
guosheng 已提交
1904 1905
    if isinstance(num_or_sections, int):
        assert num_or_sections > 1, 'num_or_sections must be more than 1.'
1906
        if isinstance(dim, int) and input_shape[dim] > 0:
1907 1908 1909 1910 1911 1912
            assert input_shape[dim] % num_or_sections == 0, (
                "The input's size along the split dimension "
                "must be evenly divisible by Attr(num_or_sections). "
                "But %d is not evenly divisible by %d. "
                % (num_or_sections, input_shape[dim])
            )
G
guosheng 已提交
1913 1914
        num = num_or_sections
    else:
1915
        if isinstance(dim, int) and input_shape[dim] > 0:
1916 1917 1918
            assert (
                len(num_or_sections) <= input_shape[dim]
            ), 'len(num_or_sections) must not be more than input.shape[dim].'
G
guosheng 已提交
1919
        num = len(num_or_sections)
1920
        attrs['sections'] = list(
1921 1922 1923 1924 1925
            map(
                lambda ele: -1 if isinstance(ele, Variable) else ele,
                num_or_sections,
            )
        )
L
Leo Chen 已提交
1926
        if utils._contain_var(num_or_sections):
1927
            inputs['SectionsTensorList'] = _get_SectionsTensorList(
1928 1929
                num_or_sections
            )
1930

G
guosheng 已提交
1931
    outs = [
X
Xin Pan 已提交
1932
        helper.create_variable_for_type_inference(dtype=helper.input_dtype())
G
guosheng 已提交
1933 1934
        for i in range(num)
    ]
1935 1936 1937
    helper.append_op(
        type='split', inputs=inputs, outputs={'Out': outs}, attrs=attrs
    )
G
guosheng 已提交
1938
    return outs
C
caoying03 已提交
1939 1940 1941


def l2_normalize(x, axis, epsilon=1e-12, name=None):
1942
    r"""
1943

R
ruri 已提交
1944
    This op normalizes `x` along dimension `axis` using an L2
C
caoying03 已提交
1945 1946
    norm. For a 1-D tensor (`dim` is fixed to 0), this layer computes

1947
    .. math::
1948 1949

        y = \\frac{x}{ \sqrt{\sum {x^2} + epsion }}
C
caoying03 已提交
1950 1951 1952 1953 1954

    For `x` with more dimensions, this layer independently normalizes each 1-D
    slice along dimension `axis`.

    Args:
1955
        x(Variable|list): The input tensor could be N-D tensor, and the input data type could be float16, float32 or float64.
1956
        axis(int): The axis on which to apply normalization. If `axis < 0`, \
1957 1958
            the dimension to normalization is rank(X) + axis. -1 is the
            last dimension.
1959
        epsilon(float): The epsilon value is used to avoid division by zero, \
翟飞跃 已提交
1960
            the default value is 1e-12.
1961
    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`
1962

C
caoying03 已提交
1963
    Returns:
R
ruri 已提交
1964
        Variable: The output has the same shape and data type with `x`.
C
caoying03 已提交
1965 1966

    Examples:
1967

1968 1969
    .. code-block:: python
        :name: code-example1
1970

1971
        import paddle
1972

1973 1974
        X = paddle.randn(shape=[3, 5], dtype='float64')
        out = paddle.fluid.layers.l2_normalize(X, axis=-1)
G
Guoxia Wang 已提交
1975
        print(out)
R
ruri 已提交
1976

1977 1978 1979
        # [[ 0.21558504  0.56360189  0.47466096  0.46269539 -0.44326736]
        #  [-0.70602414 -0.52745777  0.37771788 -0.2804768  -0.04449922]
        #  [-0.33972208 -0.43014923  0.31772556  0.76617881 -0.10761525]]
1980

C
caoying03 已提交
1981
    """
F
fengjiayi 已提交
1982 1983
    if len(x.shape) == 1:
        axis = 0
J
Jiabin Yang 已提交
1984
    if _non_static_mode():
1985 1986 1987
        if in_dygraph_mode():
            out, _ = _C_ops.norm(x, 1 if axis is None else axis, epsilon, False)
        elif _in_legacy_dygraph():
1988 1989 1990
            _, out = _legacy_C_ops.norm(
                x, 'axis', 1 if axis is None else axis, 'epsilon', epsilon
            )
1991 1992 1993
        return out

    check_variable_and_dtype(x, "X", ("float16", "float32", "float64"), "norm")
C
caoying03 已提交
1994

1995
    helper = LayerHelper("l2_normalize", **locals())
X
Xin Pan 已提交
1996 1997
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
    norm = helper.create_variable_for_type_inference(dtype=x.dtype)
1998 1999 2000 2001 2002 2003 2004 2005 2006
    helper.append_op(
        type="norm",
        inputs={"X": x},
        outputs={"Out": out, "Norm": norm},
        attrs={
            "axis": 1 if axis is None else axis,
            "epsilon": epsilon,
        },
    )
C
caoying03 已提交
2007
    return out
2008 2009


Y
yuyang18 已提交
2010
@templatedoc()
2011
def row_conv(input, future_context_size, param_attr=None, act=None):
Y
yuyang18 已提交
2012
    """
2013 2014
    :api_attr: Static Graph

Y
yuyang18 已提交
2015
    ${comment}
2016 2017

    Args:
Y
yuyang18 已提交
2018
        input (${x_type}): ${x_comment}.
Y
yangyaming 已提交
2019 2020
        future_context_size (int): Future context size. Please note, the shape
            of convolution kernel is [future_context_size + 1, D].
2021 2022 2023 2024 2025
        param_attr (ParamAttr): Attributes of parameters, including
            name, initializer etc.
        act (str): Non-linear activation to be applied to output variable.

    Returns:
Y
yuyang18 已提交
2026
        ${out_comment}.
2027 2028

    Examples:
B
Bai Yifan 已提交
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040

      .. code-block:: python

        # for LodTensor inputs
        import paddle
        paddle.enable_static()
        x = paddle.static.data(name='x', shape=[9, 16],
                               dtype='float32', lod_level=1)
        out = paddle.static.nn.row_conv(input=x, future_context_size=2)
        # for Tensor inputs
        x = paddle.static.data(name='x', shape=[9, 4, 16], dtype='float32')
        out = paddle.static.nn.row_conv(input=x, future_context_size=2)
2041 2042
    """
    helper = LayerHelper('row_conv', **locals())
2043
    check_variable_and_dtype(input, 'input', ['float32'], 'row_conv')
2044
    dtype = helper.input_dtype()
2045
    filter_shape = [future_context_size + 1, input.shape[-1]]
2046 2047 2048
    filter_param = helper.create_parameter(
        attr=helper.param_attr, shape=filter_shape, dtype=dtype
    )
X
Xin Pan 已提交
2049
    out = helper.create_variable_for_type_inference(dtype)
2050 2051 2052 2053 2054
    helper.append_op(
        type='row_conv',
        inputs={'X': [input], 'Filter': [filter_param]},
        outputs={'Out': [out]},
    )
Y
yangyaming 已提交
2055
    return helper.append_activation(out)
2056 2057


2058
@deprecated(since='2.0.0', update_to='paddle.nn.functional.one_hot')
2059
def one_hot(input, depth, allow_out_of_range=False):
2060
    """
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098

    **WARING:** This OP requires the last dimension of Tensor shape must be equal to 1.
    This OP will be deprecated in a future release. It is recommended to use fluid. :ref:`api_fluid_one_hot` .

    The operator converts each id in the input to an one-hot vector with a
    :attr:`depth` length. The value in the vector dimension corresponding to the id
    is 1, and the value in the remaining dimension is 0.

    The shape of output Tensor or LoDTensor is generated by adding :attr:`depth` dimension
    behind the last dimension of the input shape.

    .. code-block:: text

        Example 1 (allow_out_of_range=False):

        input:
            X.shape = [4, 1]
            X.data = [[1], [1], [3], [0]]
            depth = 4

        output:
            Out.shape = [4, 4]
            Out.data = [[0., 1., 0., 0.],
                        [0., 1., 0., 0.],
                        [0., 0., 0., 1.],
                        [1., 0., 0., 0.]]

        Example 2 (allow_out_of_range=True):

        input:
            X.shape = [4, 1]
            X.data = [[1], [1], [5], [0]]
            depth = 4
            allow_out_of_range = True

        output:
            Out.shape = [4, 4]
            Out.data = [[0., 1., 0., 0.],
2099
                        [0., 1., 0., 0.],
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
                        [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data.
                        [1., 0., 0., 0.]]

        Example 3 (allow_out_of_range=False):

        input:
            X.shape = [4, 1]
            X.data = [[1], [1], [5], [0]]
            depth = 4
            allow_out_of_range = False

        output: Throw an exception for Illegal value
2112
            The second dimension in X is 5, which is greater than depth.
2113 2114
            Allow_out_of_range =False means that does not allow the word id to exceed depth,
            so it throws an exception.
2115 2116

    Args:
2117 2118 2119
        input(Variable): Tensor or LoDTensor with shape :math:`[N_1, N_2, ..., N_k, 1]` ,
            which contains at least one dimension and the last dimension must be 1.
            The data type is int32 or int64.
2120
        depth(scalar): An integer defining the :attr:`depth` of the one hot dimension. If input
2121
            is word id, depth is generally the dictionary size.
2122
        allow_out_of_range(bool): A bool value indicating whether the input
2123 2124 2125 2126
            indices could be out of range :math:`[0, depth)` . When input indices are
            out of range, exceptions :code:`Illegal value` is raised if :attr:`allow_out_of_range`
            is False, or zero-filling representations is created if it is set True.
            Default: False.
2127 2128

    Returns:
2129
        Variable: The one-hot representations of input. A Tensor or LoDTensor with type float32.
2130 2131

    Examples:
C
caoying03 已提交
2132
        .. code-block:: python
2133

2134
            import paddle
2135
            import paddle.fluid as fluid
2136 2137
            paddle.enable_static()

2138 2139 2140
            # Correspond to the first example above, where label.shape is [4, 1] and one_hot_label.shape is [4, 4].
            label = fluid.data(name="label", shape=[4, 1], dtype="int64")
            one_hot_label = fluid.layers.one_hot(input=label, depth=4)
2141
    """
J
Jiabin Yang 已提交
2142
    if _non_static_mode():
S
songyouwei 已提交
2143 2144 2145
        if isinstance(depth, Variable):
            depth = depth.numpy()
            assert depth.shape == (
2146 2147
                1,
            ), "depth of type Variable should have shape [1]"
2148
            depth = depth.item(0)
2149 2150 2151
        out = _legacy_C_ops.one_hot(
            input, 'depth', depth, 'allow_out_of_range', allow_out_of_range
        )
2152 2153
        out.stop_gradient = True
        return out
2154

2155
    helper = LayerHelper("one_hot", **locals())
2156
    check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'one_hot')
2157
    check_type(depth, 'depth', (int, Variable), 'one_hot')
X
Xin Pan 已提交
2158
    one_hot_out = helper.create_variable_for_type_inference(dtype='float32')
2159

2160 2161
    if not isinstance(depth, Variable):
        # user attribute
2162
        inputs = {'X': input}
Y
Yi Liu 已提交
2163
        attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range}
2164
    else:
2165 2166 2167
        depth.stop_gradient = True
        inputs = {'X': input, 'depth_tensor': depth}
        attrs = {'allow_out_of_range': allow_out_of_range}
2168 2169 2170
    helper.append_op(
        type="one_hot", inputs=inputs, attrs=attrs, outputs={'Out': one_hot_out}
    )
2171
    one_hot_out.stop_gradient = True
2172
    return one_hot_out
Y
Yu Yang 已提交
2173 2174


Y
Yu Yang 已提交
2175
def autoincreased_step_counter(counter_name=None, begin=1, step=1):
Y
Yu Yang 已提交
2176
    """
2177 2178
    :api_attr: Static Graph

2179 2180
    Create an auto-increase variable. which will be automatically increased
    by 1 in every iteration. By default, the first return of this counter is 1,
Y
Yibing Liu 已提交
2181
    and the step size is 1.
Y
Yu Yang 已提交
2182 2183

    Args:
Y
Yibing Liu 已提交
2184 2185 2186
        counter_name(str, optional): The counter name. Default '@STEP_COUNTER@'.
        begin(int, optional): The first return value of this counter. Default 1.
        step(int, optional): The step size. Default 1.
Y
Yu Yang 已提交
2187

2188
    Returns:
Y
Yibing Liu 已提交
2189
        Variable: The auto-increased Variable with data type int64.
Y
yi.wu 已提交
2190 2191 2192 2193

    Examples:
        .. code-block:: python

2194
           import paddle.fluid as fluid
2195 2196
           import paddle
           paddle.enable_static()
Y
yi.wu 已提交
2197
           global_step = fluid.layers.autoincreased_step_counter(
Y
Yibing Liu 已提交
2198
               counter_name='@LR_DECAY_COUNTER@', begin=0, step=1)
Y
Yu Yang 已提交
2199 2200
    """
    helper = LayerHelper('global_step_counter')
Y
Yu Yang 已提交
2201 2202
    if counter_name is None:
        counter_name = '@STEP_COUNTER@'
Y
Yu Yang 已提交
2203
    counter, is_new_var = helper.create_or_get_global_variable(
H
hong 已提交
2204 2205 2206 2207
        name=counter_name,
        dtype='int64',
        shape=[1],
        persistable=True,
2208 2209
        belong_to_optimizer=True,
    )
Y
Yu Yang 已提交
2210
    if is_new_var:
2211 2212 2213
        helper.set_variable_initializer(
            counter, initializer=Constant(value=begin - 1, force_cpu=True)
        )
W
Wu Yi 已提交
2214
        helper.main_program.global_block()._prepend_op(
Y
Yu Yang 已提交
2215 2216
            type='increment',
            inputs={'X': [counter]},
Y
Yu Yang 已提交
2217
            outputs={'Out': [counter]},
2218 2219
            attrs={'step': float(step)},
        )
Y
Yu Yang 已提交
2220 2221 2222
        counter.stop_gradient = True

    return counter
Y
yangyaming 已提交
2223 2224


2225
def unsqueeze(input, axes, name=None):
Y
Yibing Liu 已提交
2226
    """
2227
    Insert single-dimensional entries to the shape of a Tensor. Takes one
M
minqiyang 已提交
2228 2229
    required argument axes, a list of dimensions that will be inserted.
    Dimension indices in axes are as seen in the output tensor.
Y
Yibing Liu 已提交
2230

M
minqiyang 已提交
2231
    For example:
H
haowang101779990 已提交
2232 2233 2234

    .. code-block:: text

M
minqiyang 已提交
2235
      Given a tensor such that tensor with shape [3, 4, 5],
Y
Yibing Liu 已提交
2236
      then Unsqueezed tensor with axes=[0, 4] has shape [1, 3, 4, 5, 1].
M
minqiyang 已提交
2237

Y
Yibing Liu 已提交
2238
    Args:
2239
        input (Variable): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64.
2240
        axes (int|list|tuple|Variable): Indicates the dimensions to be inserted. The data type is ``int32`` . If ``axes`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``axes`` is an Variable, it should be an 1-D Tensor .
2241
        name (str|None): Name for this layer.
Y
Yibing Liu 已提交
2242 2243

    Returns:
2244
        Variable: Unsqueezed Tensor, with the same data type as input.
Y
Yibing Liu 已提交
2245 2246 2247 2248

    Examples:
        .. code-block:: python

2249 2250 2251
            import paddle.fluid as fluid
            x = fluid.layers.data(name='x', shape=[5, 10])
            y = fluid.layers.unsqueeze(input=x, axes=[1])
2252

Y
Yibing Liu 已提交
2253
    """
J
Jiabin Yang 已提交
2254
    if _non_static_mode():
L
Leo Chen 已提交
2255 2256 2257
        if isinstance(axes, int):
            axes = [axes]
        elif isinstance(axes, Variable):
2258
            axes = axes.numpy().tolist()
L
Leo Chen 已提交
2259 2260 2261 2262 2263
        elif isinstance(axes, (list, tuple)):
            axes = [
                item.numpy().item(0) if isinstance(item, Variable) else item
                for item in axes
            ]
2264
        if _in_legacy_dygraph():
2265
            out, _ = _legacy_C_ops.unsqueeze2(input, 'axes', axes)
2266
            return out
2267
        return _C_ops.unsqueeze(input, axes)
2268 2269

    check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze')
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
    check_variable_and_dtype(
        input,
        'input',
        [
            'float16',
            'float32',
            'float64',
            'bool',
            'int8',
            'int16',
            'int32',
            'int64',
            'complex64',
            'complex128',
        ],
        'unsqueeze',
    )
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    helper = LayerHelper("unsqueeze2", **locals())
    inputs = {"X": input}
    attrs = {}

    if isinstance(axes, int):
        axes = [axes]
    if isinstance(axes, Variable):
        axes.stop_gradient = True
        inputs["AxesTensor"] = axes
    elif isinstance(axes, (list, tuple)):
L
Leo Chen 已提交
2297
        if utils._contain_var(axes):
2298
            inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes)
2299 2300 2301
        else:
            attrs["axes"] = axes

X
Xin Pan 已提交
2302 2303
    out = helper.create_variable_for_type_inference(dtype=input.dtype)
    x_shape = helper.create_variable_for_type_inference(dtype=input.dtype)
2304 2305 2306 2307 2308 2309
    helper.append_op(
        type="unsqueeze2",
        inputs=inputs,
        attrs=attrs,
        outputs={"Out": out, "XShape": x_shape},
    )
Y
Yibing Liu 已提交
2310

2311 2312
    return out

2313

Y
yangyaming 已提交
2314
def lod_reset(x, y=None, target_lod=None):
Y
yangyaming 已提交
2315
    """
Y
Yibing Liu 已提交
2316
    Set LoD of :attr:`x` to a new one specified by :attr:`y` or
2317 2318 2319 2320
    :attr:`target_lod`. When :attr:`y` provided, :attr:`y.lod` would be
    considered as target LoD first, otherwise :attr:`y.data` would be
    considered as target LoD. If :attr:`y` is not provided, target LoD should
    be specified by :attr:`target_lod`. If target LoD is specified by
2321
    :attr:`y.data` or :attr:`target_lod`, only one level LoD is supported.
Y
yangyaming 已提交
2322 2323 2324 2325 2326 2327

    .. code-block:: text

        * Example 1:

            Given a 1-level LoDTensor x:
2328
                x.lod =  [[ 2,           3,                   1 ]]
Y
yangyaming 已提交
2329 2330 2331
                x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                x.dims = [6, 1]

2332
            target_lod: [4, 2]
Y
yangyaming 已提交
2333 2334

            then we get a 1-level LoDTensor:
2335
                out.lod =  [[4,                          2]]
Y
yangyaming 已提交
2336 2337 2338 2339 2340 2341
                out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                out.dims = [6, 1]

        * Example 2:

            Given a 1-level LoDTensor x:
2342
                x.lod =  [[2,            3,                   1]]
Y
yangyaming 已提交
2343 2344 2345 2346
                x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                x.dims = [6, 1]

            y is a Tensor:
2347
                y.data = [[2, 4]]
Y
yangyaming 已提交
2348 2349 2350
                y.dims = [1, 3]

            then we get a 1-level LoDTensor:
2351
                out.lod =  [[2,            4]]
Y
yangyaming 已提交
2352 2353 2354 2355 2356 2357
                out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                out.dims = [6, 1]

        * Example 3:

            Given a 1-level LoDTensor x:
2358
                x.lod =  [[2,            3,                   1]]
Y
yangyaming 已提交
2359 2360 2361 2362
                x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                x.dims = [6, 1]

            y is a 2-level LoDTensor:
2363
                y.lod =  [[2, 2], [2, 2, 1, 1]]
Y
yangyaming 已提交
2364 2365 2366 2367
                y.data = [[1.1], [2.1], [3.1], [4.1], [5.1], [6.1]]
                y.dims = [6, 1]

            then we get a 2-level LoDTensor:
2368
                out.lod =  [[2, 2], [2, 2, 1, 1]]
Y
yangyaming 已提交
2369 2370 2371 2372
                out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
                out.dims = [6, 1]

    Args:
2373
        x (Variable): Input variable which could be a Tensor or LoDTensor.
2374
                      The data type should be int32, int64, float32 or float64.
2375 2376
        y (Variable, optional): If provided, output's LoD would be derived from :attr:`y`.
                                If y's lod level>0, the data type can be any type.
2377 2378
                                If y's lod level=0, the data type should be int32.
        target_lod (list|tuple, optional): One level LoD which should be considered
Y
Yibing Liu 已提交
2379
                                      as target LoD when :attr:`y` not provided.
Y
yangyaming 已提交
2380 2381

    Returns:
Y
Yibing Liu 已提交
2382
        Variable: Output variable with LoD specified by this layer.
Y
yangyaming 已提交
2383 2384

    Raises:
Y
Yibing Liu 已提交
2385
        ValueError: If :attr:`y` and :attr:`target_lod` are both None.
Y
yangyaming 已提交
2386 2387 2388 2389

    Examples:
        .. code-block:: python

2390
            import paddle.fluid as fluid
2391 2392 2393
            x = fluid.layers.data(name='x', shape=[10])
            y = fluid.layers.data(name='y', shape=[10, 20], lod_level=2)
            out = fluid.layers.lod_reset(x=x, y=y)
Y
yangyaming 已提交
2394
    """
2395 2396 2397
    check_variable_and_dtype(
        x, 'x', ['float32', 'float64', 'int32', 'int64'], 'lod_reset'
    )
Y
yangyaming 已提交
2398
    helper = LayerHelper("lod_reset", **locals())
X
Xin Pan 已提交
2399
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
Y
yangyaming 已提交
2400
    if y is not None:
2401
        check_type(y, 'y', (Variable), 'lod_reset')
2402 2403 2404 2405
        # TODO: check y.lod_level = 0 dtype
        helper.append_op(
            type="lod_reset", inputs={'X': x, 'Y': y}, outputs={'Out': out}
        )
Y
yangyaming 已提交
2406
    elif target_lod is not None:
2407 2408 2409 2410 2411 2412
        helper.append_op(
            type="lod_reset",
            inputs={'X': x},
            attrs={'target_lod': target_lod},
            outputs={'Out': out},
        )
Y
yangyaming 已提交
2413
    else:
2414 2415 2416 2417
        raise ValueError("y and target_lod should not be both none.")
    return out


2418
@deprecated(since="2.0.0", update_to="paddle.nn.functional.relu")
2419
def relu(x, name=None):
W
wanghaoshuang 已提交
2420
    """
Z
zhupengyang 已提交
2421
    ${comment}
W
wanghaoshuang 已提交
2422 2423

    Args:
Z
zhupengyang 已提交
2424 2425 2426 2427
        x(Variable): ${x_comment}
        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`.
W
wanghaoshuang 已提交
2428 2429

    Returns:
Z
zhupengyang 已提交
2430
        Variable: ${out_comment}
W
wanghaoshuang 已提交
2431 2432 2433 2434 2435

    Examples:

        .. code-block:: python

2436
            import paddle.fluid as fluid
Z
zhupengyang 已提交
2437 2438 2439 2440 2441 2442 2443
            import numpy as np
            in1 = np.array([[-1,0],[1,2.6]])
            with fluid.dygraph.guard():
                x1 = fluid.dygraph.to_variable(in1)
                out1 = fluid.layers.relu(x1)
                print(out1.numpy())
                # [[0.  0. ]
2444
                #  [1.  2.6]]"""
2445 2446

    if in_dygraph_mode():
W
wanghuancoder 已提交
2447
        return _C_ops.relu(x)
2448 2449
    if _in_legacy_dygraph():
        return _legacy_C_ops.relu(x)
2450

2451 2452
    check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu')

2453
    inputs = {'X': [x]}
W
wanghaoshuang 已提交
2454
    helper = LayerHelper('relu', **locals())
W
wanghaoshuang 已提交
2455
    dtype = helper.input_dtype(input_param_name='x')
X
Xin Pan 已提交
2456
    out = helper.create_variable_for_type_inference(dtype)
2457 2458 2459
    helper.append_op(
        type="relu", inputs={"X": helper.input('x')}, outputs={"Out": out}
    )
W
wanghaoshuang 已提交
2460
    return out
2461 2462


2463
def _logical_op(op_name, x, y, out=None, name=None, binary_op=True):
J
Jiabin Yang 已提交
2464
    if _non_static_mode():
2465
        op = getattr(_legacy_C_ops, op_name)
2466 2467 2468 2469
        if binary_op:
            return op(x, y)
        else:
            return op(x)
2470
    check_variable_and_dtype(
2471 2472
        x,
        "x",
2473
        ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
2474 2475
        op_name,
    )
2476
    if y is not None:
2477
        check_variable_and_dtype(
2478 2479
            y,
            "y",
2480
            ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
2481 2482
            op_name,
        )
2483
    if out is not None:
2484
        check_type(out, "out", Variable, op_name)
2485

M
minqiyang 已提交
2486 2487
    helper = LayerHelper(op_name, **locals())

2488 2489 2490
    if binary_op and x.dtype != y.dtype:
        raise ValueError(
            "(InvalidArgument) The DataType of %s Op's Variable must be consistent, but received %s and %s."
2491 2492
            % (op_name, x.dtype, y.dtype)
        )
M
minqiyang 已提交
2493 2494

    if out is None:
2495
        out = helper.create_variable_for_type_inference(dtype=x.dtype)
M
minqiyang 已提交
2496 2497

    if binary_op:
2498 2499 2500
        helper.append_op(
            type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}
        )
M
minqiyang 已提交
2501 2502 2503 2504 2505 2506
    else:
        helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out})

    return out


2507 2508 2509
@templatedoc()
def clip(x, min, max, name=None):
    """
2510
        :old_api: paddle.fluid.layers.clip
2511

2512 2513 2514 2515
    ${comment}

    Args:
        x(${x_type}): ${x_comment}
S
SunGaofeng 已提交
2516 2517
        min(float): ${min_comment}
        max(float): ${max_comment}
2518 2519
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
S
SunGaofeng 已提交
2520
                             For more information, please refer to :ref:`api_guide_Name`
2521 2522

    Returns:
S
SunGaofeng 已提交
2523 2524 2525 2526
        ${out_comment}

    Return Type:
        ${out_type}
2527 2528 2529 2530

    Examples:
        .. code-block:: python

S
SunGaofeng 已提交
2531
            import paddle.fluid as fluid
S
SunGaofeng 已提交
2532
            input = fluid.data(
2533 2534
                name='data', shape=[1], dtype='float32')
            reward = fluid.layers.clip(x=input, min=-1.0, max=1.0)
2535 2536 2537
    """

    helper = LayerHelper("clip", **locals())
2538
    check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'clip')
2539 2540

    if name is None:
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
        name = unique_name.generate_with_ignorable_key(
            ".".join([helper.name, 'tmp'])
        )

    out = helper.create_variable(
        type=x.type, name=name, dtype=x.dtype, persistable=False
    )

    helper.append_op(
        type="clip",
        inputs={"X": x},
        attrs={"min": min, "max": max},
        outputs={"Out": out},
    )
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566

    return out


@templatedoc()
def clip_by_norm(x, max_norm, name=None):
    """
    ${comment}

    Args:
        x(${x_type}): ${x_comment}
        max_norm(${max_norm_type}): ${max_norm_comment}
2567 2568 2569
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
2570 2571

    Returns:
2572
        Tensor:
W
wangguanzhong 已提交
2573

2574
        out(${out_type}): ${out_comment}
2575

W
wangguanzhong 已提交
2576

2577 2578 2579
    Examples:
        .. code-block:: python

2580
            import paddle
2581
            import paddle.fluid as fluid
2582

2583 2584 2585
            input = paddle.to_tensor([[2.0, 2.0], [2.0, 2.0]], dtype='float32')
            reward = fluid.layers.clip_by_norm(x=input, max_norm=1.0)
            # [[0.5, 0.5], [0.5, 0.5]]
2586 2587
    """

L
lyq 已提交
2588
    if in_dygraph_mode():
2589
        return _C_ops.clip_by_norm(x, max_norm)
J
Jiabin Yang 已提交
2590
    if _non_static_mode():
2591
        return _legacy_C_ops.clip_by_norm(x, 'max_norm', max_norm)
2592

2593
    helper = LayerHelper("clip_by_norm", **locals())
2594
    check_variable_and_dtype(x, 'X', ['float32', 'float16'], 'clip_by_norm')
2595
    check_type(max_norm, 'max_norm', (float), 'clip_by_norm')
2596 2597

    if name is None:
2598 2599 2600
        name = unique_name.generate_with_ignorable_key(
            ".".join([helper.name, 'tmp'])
        )
S
sneaxiy 已提交
2601

2602 2603 2604
    out = helper.create_variable(
        type=x.type, name=name, dtype=x.dtype, persistable=False
    )
2605

2606 2607 2608 2609 2610 2611
    helper.append_op(
        type="clip_by_norm",
        inputs={"X": x},
        attrs={"max_norm": max_norm},
        outputs={"Out": out},
    )
2612 2613

    return out
X
Xin Pan 已提交
2614 2615


C
chengduo 已提交
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
@templatedoc()
def merge_selected_rows(x, name=None):
    """
    ${comment}

    Args:
        x(${x_type}): ${x_comment}
        name(basestring|None): Name of the output.

    Returns:
        out(${out_type}): ${out_comment}
2627 2628 2629 2630

    Examples:
        .. code-block:: python

2631
            import paddle.fluid as fluid
2632 2633 2634 2635 2636
            b = fluid.default_main_program().global_block()
            var = b.create_var(
                name="X", dtype="float32", persistable=True,
                type=fluid.core.VarDesc.VarType.SELECTED_ROWS)
            y = fluid.layers.merge_selected_rows(var)
C
chengduo 已提交
2637
    """
2638 2639 2640
    if in_dygraph_mode():
        return _C_ops.merge_selected_rows(x)

2641
    if _non_static_mode():
2642
        return _legacy_C_ops.merge_selected_rows(x)
C
chengduo 已提交
2643 2644 2645

    helper = LayerHelper("merge_selected_rows", **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
2646 2647 2648 2649 2650 2651
    helper.append_op(
        type="merge_selected_rows",
        inputs={"X": x},
        attrs={},
        outputs={"Out": out},
    )
C
chengduo 已提交
2652 2653 2654
    return out


X
Xin Pan 已提交
2655 2656
def mul(x, y, x_num_col_dims=1, y_num_col_dims=1, name=None):
    """
L
liu zhengxi 已提交
2657 2658 2659 2660 2661 2662 2663 2664
    Mul Operator.
    This operator is used to perform matrix multiplication for input $x$ and $y$.
    The equation is:

    ..  math::
        Out = x * y

    Both the input $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $x$.
X
Xin Pan 已提交
2665 2666

    Args:
L
liu zhengxi 已提交
2667 2668
        x (Variable): The first input Tensor/LoDTensor of mul_op.
        y (Variable): The second input Tensor/LoDTensor of mul_op.
2669 2670 2671
        x_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $x$ is a tensor with more than two dimensions, $x$ will be flattened into a two-dimensional matrix first. The flattening rule is: the first `num_col_dims` will be flattened to form the first dimension of the final matrix (the height of the matrix), and the rest `rank(x) - num_col_dims` dimensions are flattened to form the second dimension of the final matrix (the width of the matrix). As a result, height of the flattened matrix is equal to the product of $x$'s first `x_num_col_dims` dimensions' sizes, and width of the flattened matrix is equal to the product of $x$'s last `rank(x) - num_col_dims` dimensions' size. For example, suppose $x$ is a 6-dimensional tensor with the shape [2, 3, 4, 5, 6], and `x_num_col_dims` = 3. Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default is 1.
        y_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $y$ is a tensor with more than two dimensions, $y$ will be flattened into a two-dimensional matrix first. The attribute `y_num_col_dims` determines how $y$ is flattened. See comments of `x_num_col_dims` for more details. Default is 1.
        name (str, optional): Name of the output. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None.
X
Xin Pan 已提交
2672 2673

    Returns:
L
liu zhengxi 已提交
2674
        Variable(Tensor/LoDTensor): The output Tensor/LoDTensor of mul op.
2675 2676

    Examples:
L
liu zhengxi 已提交
2677
        ..  code-block:: python
2678

2679
            import paddle.fluid as fluid
2680 2681
            import paddle
            paddle.enable_static()
2682 2683 2684 2685 2686
            dataX = fluid.layers.data(name="dataX", append_batch_size = False, shape=[2, 5], dtype="float32")
            dataY = fluid.layers.data(name="dataY", append_batch_size = False, shape=[5, 3], dtype="float32")
            output = fluid.layers.mul(dataX, dataY,
                                      x_num_col_dims = 1,
                                      y_num_col_dims = 1)
2687

2688

X
Xin Pan 已提交
2689
    """
J
Jiabin Yang 已提交
2690
    if _non_static_mode():
2691 2692 2693 2694 2695 2696 2697 2698
        return _legacy_C_ops.mul(
            x,
            y,
            'x_num_col_dims',
            x_num_col_dims,
            'y_num_col_dims',
            y_num_col_dims,
        )
X
Xin Pan 已提交
2699

2700 2701
    inputs = {"X": [x], "Y": [y]}
    attrs = {"x_num_col_dims": x_num_col_dims, "y_num_col_dims": y_num_col_dims}
X
Xin Pan 已提交
2702
    helper = LayerHelper("mul", **locals())
2703 2704
    check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mul')
    check_variable_and_dtype(y, 'y', ['float16', 'float32', 'float64'], 'mul')
2705
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
X
Xin Pan 已提交
2706

2707 2708 2709
    helper.append_op(
        type="mul", inputs={"X": x, "Y": y}, attrs=attrs, outputs={"Out": out}
    )
X
Xin Pan 已提交
2710 2711 2712
    return out


C
chengduo 已提交
2713 2714 2715
@templatedoc()
def get_tensor_from_selected_rows(x, name=None):
    """
2716 2717 2718 2719 2720 2721 2722 2723 2724
    This operator gets tensor data from input with SelectedRows type, and outputs a LoDTensor.

    .. code-block:: text

        input x is SelectedRows:
           x.rows = [0, 5, 5, 4, 19]
           x.height = 20
           x.value = [[1, 1] [2, 2] [2, 2] [3, 3] [6, 6]]

2725
        Output is LoDTensor:
2726 2727 2728 2729 2730 2731
           out.shape = [5, 2]
           out.data = [[1, 1],
                       [2, 2],
                       [2, 2],
                       [3, 3],
                       [6, 6]]
C
chengduo 已提交
2732 2733

    Args:
2734 2735 2736
        x(SelectedRows): Input with SelectedRows type. The data type is float32, float64, int32 or int64.
        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` .
C
chengduo 已提交
2737 2738

    Returns:
2739
        Variable: LoDTensor transformed from SelectedRows. The data type is same with input.
B
bdzhuxiaoning 已提交
2740 2741 2742

    Examples:
        .. code-block:: python
2743

B
bdzhuxiaoning 已提交
2744 2745 2746 2747
            import paddle.fluid as fluid
            b = fluid.default_main_program().global_block()
            input = b.create_var(name="X", dtype="float32", persistable=True, type=fluid.core.VarDesc.VarType.SELECTED_ROWS)
            out = fluid.layers.get_tensor_from_selected_rows(input)
C
chengduo 已提交
2748 2749
    """

2750 2751 2752 2753 2754
    check_type(x, 'x', Variable, 'get_tensor_from_selected_rows')
    if x.type != core.VarDesc.VarType.SELECTED_ROWS:
        raise TypeError(
            "The type of 'x' in get_tensor_from_selected_rows must be SELECTED_ROWS."
        )
C
chengduo 已提交
2755 2756
    helper = LayerHelper('get_tensor_from_selected_rows', **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
2757 2758 2759 2760 2761 2762
    helper.append_op(
        type='get_tensor_from_selected_rows',
        inputs={'X': x},
        outputs={'Out': out},
        attrs={},
    )
C
chengduo 已提交
2763
    return out