nn.py 51.0 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
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
    'fc',
    'embedding',
    'row_conv',
D
dengkaipeng 已提交
69
    'spectral_norm',
X
Xin Pan 已提交
70 71 72 73
    'one_hot',
    'autoincreased_step_counter',
    'clip',
    'clip_by_norm',
C
chengduo 已提交
74 75
    'merge_selected_rows',
    'get_tensor_from_selected_rows',
Y
Yu Yang 已提交
76 77
]

78
OP_NAMEMAPPING = {
79 80 81 82 83 84 85 86
    '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 已提交
87
    'elementwise_mod': 'remainder',
88 89
}

Y
Yu Yang 已提交
90

91 92
def _get_reduce_dim(dim, input):
    """
93
    Internal function for reduce_sum, reduce_mean, reduce_prod.
94 95 96 97 98 99 100 101 102
    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(
103
                "The type of dim must be int, list, tuple or range, but received {}".format(
104
                    type(dim)
105 106
                )
            )
107 108 109 110 111 112 113 114 115 116
    if dim is None:
        dim = []
    if dim == [] or len(dim) == len(input.shape):
        reduce_all = True
    else:
        reduce_all = False

    return reduce_all, dim


117
@dygraph_only
118 119 120
def _elementwise_op_in_dygraph(
    x, y, axis=-1, act=None, use_mkldnn=False, op_name=None
):
121 122 123 124
    def is_inplace(op_name):
        return op_name[-1] == "_"

    if op_name not in OP_NAMEMAPPING.keys() or axis != -1:
125
        op = getattr(_legacy_C_ops, op_name)
126 127 128
        out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn)
    else:
        if in_dygraph_mode():
129 130
            op = getattr(
                _C_ops,
131 132
                OP_NAMEMAPPING[op_name] if not is_inplace(op_name) else op_name,
            )
133 134 135
            out = op(x, y)

        if _in_legacy_dygraph():
136
            op = getattr(_legacy_C_ops, op_name)
137
            out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn)
138 139 140 141 142 143 144 145 146 147 148 149 150 151
    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,
):
152
    r"""
153 154
    :api_attr: Static Graph

155
    **Fully Connected Layer**
Y
Yu Yang 已提交
156

157 158 159
    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,
160
    which represents a fully connected weight matrix from each input unit to
161 162 163 164
    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`
165
    is not None, a bias variable will be created and added to the output.
166
    Finally, if :attr:`act` is not None, it will be applied to the output as well.
C
caoying03 已提交
167

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

170 171 172 173
    .. math::

        Out = Act({XW + b})

174
    When the input is a list of Tensor(or LoDTensor):
175 176 177

    .. math::

178
        Out = Act({\sum_{i=0}^{N-1}X_iW_i + b})
179 180 181

    In the above equation:

182 183 184
    * :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 已提交
185
    * :math:`b`: The bias parameter created by this layer (if needed).
186
    * :math:`Act`: The activation function.
187
    * :math:`Out`: The output Tensor.
188 189 190

    .. code-block:: text

191 192 193 194 195 196 197 198 199 200 201 202 203 204
        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:
205 206 207 208 209 210 211 212 213 214 215 216 217
            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 已提交
218
    Args:
219 220 221
        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 已提交
222
        size(int): The number of output units in this layer, which also means the feature size of output
223 224
            Tensor(or LoDTensor).
        num_flatten_dims (int): The fc layer can accept an input Tensor with more than
R
ranqiu 已提交
225
            two dimensions. If this happens, the multidimensional tensor will first be flattened
226 227
            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 已提交
228
            dimensions will be flatten to form the first dimension of the final matrix (height of
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            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.
244 245

    Raises:
246
        ValueError: If dimensions of the input Tensor is less than 2.
247 248 249 250

    Examples:
        .. code-block:: python

251
          import paddle.fluid as fluid
252 253
          import paddle
          paddle.enable_static()
254
          # when input is single tensor
255
          data = fluid.data(name="data", shape=[-1, 32], dtype="float32")
256
          fc = fluid.layers.fc(input=data, size=1000, act="tanh")
257 258

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

281 282 283
        w = helper.create_parameter(
            attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False
        )
X
Xin Pan 已提交
284
        tmp = helper.create_variable_for_type_inference(dtype)
285 286 287 288 289 290
        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},
        )
291 292 293 294
        mul_results.append(tmp)

    if len(mul_results) == 1:
        pre_bias = mul_results[0]
295
    else:
X
Xin Pan 已提交
296
        pre_bias = helper.create_variable_for_type_inference(dtype)
297 298 299 300 301 302
        helper.append_op(
            type="sum",
            inputs={"X": mul_results},
            outputs={"Out": pre_bias},
            attrs={"use_mkldnn": False},
        )
303 304 305 306
    # 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 已提交
307 308


T
tangwei12 已提交
309
@deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding")
310 311 312 313 314 315 316 317 318
def embedding(
    input,
    size,
    is_sparse=False,
    is_distributed=False,
    padding_idx=None,
    param_attr=None,
    dtype='float32',
):
319
    r"""
320
    :api_attr: Static Graph
321

322 323 324 325 326 327 328 329 330 331 332 333
    **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.

334
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    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]],
352

353 354 355 356
                        [[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.
357

358
        Case 2:
359

360 361 362 363 364 365 366 367 368 369 370 371 372 373
        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 已提交
374 375

    Args:
376 377 378 379 380 381
        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
382
            affects the performance of the backwards gradient update. It is recommended to set
383
            True because sparse update is faster. But some optimizer does not support sparse update,
384
            such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` ,
385 386 387 388 389
            :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.
390
        padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
391 392 393 394 395 396
            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,
397
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
398
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tianshuo78520a 已提交
399
            vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer`
400 401 402
            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 已提交
403

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

407 408
    Examples:
        .. code-block:: python
Y
Yu Yang 已提交
409

B
bdzhuxiaoning 已提交
410
          import paddle.fluid as fluid
411
          import numpy as np
412 413
          import paddle
          paddle.enable_static()
414

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

T
tianshuo78520a 已提交
417
          # example 1
418 419 420 421 422 423 424 425 426
          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)
427
          emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32')
Y
Yu Yang 已提交
428 429 430
    """

    helper = LayerHelper('embedding', **locals())
431 432 433 434 435 436 437 438 439
    check_variable_and_dtype(
        input, 'input', ['int64'], 'fluid.layers.embedding'
    )
    check_dtype(
        dtype,
        'dtype',
        ['uint16', 'float16', 'float32', 'float64'],
        'fluid.layers.embedding',
    )
440 441 442 443 444 445 446 447 448

    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

449 450 451
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
    )
X
Xin Pan 已提交
452
    tmp = helper.create_variable_for_type_inference(dtype)
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    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 已提交
471 472 473
    return tmp


474 475 476 477 478 479 480 481 482 483 484
def _pull_sparse(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
485
    r"""
486 487 488 489 490 491 492 493 494 495 496 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
    **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
531
        'is_distributed': True,
532 533
    }
    # this is only for compatible with embedding op
534 535 536 537 538 539 540 541 542
    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,
    )
543 544 545 546 547
    if len(outs) == 1:
        return outs[0]
    return outs


548 549 550 551 552 553 554 555 556 557 558
def _pull_sparse_v2(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
559
    r"""
560 561 562 563 564 565 566 567 568 569 570 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
    **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
605
        'is_distributed': True,
606 607
    }
    # this is only for compatible with embedding op
608 609 610 611 612 613 614 615 616
    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,
    )
617
    if len(outs) == 1:
Y
yaoxuefeng 已提交
618 619 620 621
        return outs[0]
    return outs


622 623 624
def _pull_gpups_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
Y
yaoxuefeng 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637
    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
638
        float32 now.
Y
yaoxuefeng 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

    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(
658 659 660
            "GpuPS only support float type embedding now, and your type is: "
            + dtype
        )
Y
yaoxuefeng 已提交
661 662 663 664 665 666
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
667 668 669 670 671 672 673 674 675 676 677 678 679
    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 已提交
680
    if len(outs) == 1:
681 682 683 684
        return outs[0]
    return outs


685 686 687
def _pull_box_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
688
    r"""
H
hutuxian 已提交
689 690 691 692 693 694 695
    **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:
696
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
H
hutuxian 已提交
697
            contains the IDs information.
698
        size(int): The embedding size parameter, which indicates the size of
H
hutuxian 已提交
699
            each embedding vector respectively.
700
        dtype(str): The dtype refers to the data type of output tensor. Only supports
701
        float32 now.
H
hutuxian 已提交
702 703 704 705 706 707 708 709 710 711

    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)
712
          emb = fluid.layers.pull_box_sparse(input=data, size=[11])
H
hutuxian 已提交
713 714 715 716
    """
    helper = LayerHelper('pull_box_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
717 718 719
            "BoxPS only support float type embedding now, and your type is: "
            + dtype
        )
H
hutuxian 已提交
720 721 722 723 724 725
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
726 727 728 729 730 731 732 733 734 735 736 737 738
    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 已提交
739 740 741 742 743
    if len(outs) == 1:
        return outs[0]
    return outs


D
dengkaipeng 已提交
744
@templatedoc()
745
def spectral_norm(weight, dim=0, power_iters=1, eps=1e-12, name=None):
746
    r"""
747 748
    :api_attr: Static Graph

D
dengkaipeng 已提交
749 750
    **Spectral Normalization Layer**

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

D
dengkaipeng 已提交
756 757 758
    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 已提交
759
    and W is the product result of remaining dimensions.
D
dengkaipeng 已提交
760 761

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

766
    .. math::
D
dengkaipeng 已提交
767 768 769 770 771 772

        \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 已提交
773
    Calculate :math:`\sigma(\mathbf{W})` and normalize weight values.
D
dengkaipeng 已提交
774 775 776 777

    .. math::

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

D
dengkaipeng 已提交
779
        \mathbf{W} = \\frac{\mathbf{W}}{\sigma(\mathbf{W})}
780

781

D
dengkaipeng 已提交
782 783 784
    Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ .

    Args:
C
Chen Long 已提交
785
        weight(Tensor): ${weight_comment}
D
dengkaipeng 已提交
786 787 788
        dim(int): ${dim_comment}
        power_iters(int): ${power_iters_comment}
        eps(float): ${eps_comment}
K
Kaipeng Deng 已提交
789 790 791
        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 已提交
792 793

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

    Examples:
K
Kaipeng Deng 已提交
798
       .. code-block:: python
D
dengkaipeng 已提交
799

800
            import paddle
K
Kaipeng Deng 已提交
801

802
            paddle.enable_static()
C
Chen Long 已提交
803
            weight = paddle.static.data(name='weight', shape=[2, 8, 32, 32], dtype='float32')
804
            x = paddle.static.nn.spectral_norm(weight=weight, dim=1, power_iters=2)
C
Chen Long 已提交
805
            print(x.shape) # [2, 8, 32, 32]
D
dengkaipeng 已提交
806 807
    """
    helper = LayerHelper('spectral_norm', **locals())
808 809 810
    check_variable_and_dtype(
        weight, 'weight', ['float32', 'float64'], 'spectral_norm'
    )
811 812 813
    check_type(dim, 'dim', int, 'spectral_norm')
    check_type(power_iters, 'power_iters', int, 'spectral_norm')
    check_type(eps, 'eps', float, 'spectral_norm')
814
    dtype = weight.dtype
D
dengkaipeng 已提交
815 816

    # create intput and parameters
817
    input_shape = weight.shape
818
    assert weight.numel() > 0, "Any dimension of input cannot be equal to 0."
819 820 821 822 823
    assert dim < len(input_shape), (
        "The input `dim` should be less than the "
        "rank of `weight`, but received dim="
        "{}".format(dim)
    )
824 825 826
    h = input_shape[dim]
    w = np.prod(input_shape) // h

827 828 829 830 831 832
    u = helper.create_parameter(
        attr=ParamAttr(),
        shape=[h],
        dtype=dtype,
        default_initializer=Normal(0.0, 1.0),
    )
833
    u.stop_gradient = True
834 835 836 837 838 839
    v = helper.create_parameter(
        attr=ParamAttr(),
        shape=[w],
        dtype=dtype,
        default_initializer=Normal(0.0, 1.0),
    )
840
    v.stop_gradient = True
D
dengkaipeng 已提交
841

842 843 844 845 846 847 848
    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 已提交
849
    # create output
850
    out = helper.create_variable(dtype=dtype)
D
Dun 已提交
851

852 853 854 855 856 857 858 859 860 861 862 863
    helper.append_op(
        type="spectral_norm",
        inputs=inputs,
        outputs={
            "Out": out,
        },
        attrs={
            "dim": dim,
            "power_iters": power_iters,
            "eps": eps,
        },
    )
D
Dun 已提交
864

865
    return out
D
Dun 已提交
866 867


C
caoying03 已提交
868
def reduce_sum(input, dim=None, keep_dim=False, name=None):
G
guosheng 已提交
869
    """
870

Y
yangyaming 已提交
871
    Computes the sum of tensor elements over the given dimension.
G
guosheng 已提交
872 873

    Args:
874 875 876
        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 已提交
877 878
            :attr:`None`, sum all elements of :attr:`input` and return a
            Tensor variable with a single element, otherwise must be in the
W
whs 已提交
879 880
            range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`,
            the dimension to reduce is :math:`rank + dim[i]`.
881
        keep_dim (bool, optional): Whether to reserve the reduced dimension in the
Y
yangyaming 已提交
882
            output Tensor. The result tensor will have one fewer dimension
883 884 885 886
            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 已提交
887 888

    Returns:
889 890
        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 已提交
891

892 893
    Raises:
        TypeError, if out data type is different with the input data type.
894

G
guosheng 已提交
895 896 897
    Examples:
        .. code-block:: python

898
            import paddle.fluid as fluid
899 900
            import paddle
            paddle.enable_static()
G
guosheng 已提交
901 902 903
            # 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 已提交
904
            # Each example is followed by the corresponding output tensor.
905
            x = fluid.data(name='x', shape=[2, 4], dtype='float32')
G
guosheng 已提交
906 907 908 909
            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 已提交
910

911
            # y is a Tensor variable with shape [2, 2, 2] and elements as below:
W
whs 已提交
912 913
            #      [[[1, 2], [3, 4]],
            #      [[5, 6], [7, 8]]]
Q
qiaolongfei 已提交
914
            # Each example is followed by the corresponding output tensor.
915
            y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32')
916 917
            fluid.layers.reduce_sum(y, dim=[1, 2]) # [10, 26]
            fluid.layers.reduce_sum(y, dim=[0, 1]) # [16, 20]
W
whs 已提交
918

G
guosheng 已提交
919
    """
920 921
    reduce_all, dim = _get_reduce_dim(dim, input)

922
    if in_dygraph_mode():
923
        return _C_ops.sum(input, dim, None, keep_dim)
924
    elif _in_legacy_dygraph():
925 926 927
        return _legacy_C_ops.reduce_sum(
            input, 'dim', dim, 'keep_dim', keep_dim, 'reduce_all', reduce_all
        )
928
    attrs = {'dim': dim, 'keep_dim': keep_dim, 'reduce_all': reduce_all}
929
    check_variable_and_dtype(
930 931 932 933 934
        input,
        'input',
        ['float16', 'float32', 'float64', 'int32', 'int64'],
        'reduce_sum',
    )
935
    helper = LayerHelper('reduce_sum', **locals())
X
Xin Pan 已提交
936
    out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
937 938 939 940 941 942
    helper.append_op(
        type='reduce_sum',
        inputs={'X': input},
        outputs={'Out': out},
        attrs=attrs,
    )
G
guosheng 已提交
943
    return out
G
guosheng 已提交
944 945


Y
yuyang18 已提交
946
@templatedoc()
947
def row_conv(input, future_context_size, param_attr=None, act=None):
Y
yuyang18 已提交
948
    """
949 950
    :api_attr: Static Graph

Y
yuyang18 已提交
951
    ${comment}
952 953

    Args:
Y
yuyang18 已提交
954
        input (${x_type}): ${x_comment}.
Y
yangyaming 已提交
955 956
        future_context_size (int): Future context size. Please note, the shape
            of convolution kernel is [future_context_size + 1, D].
957 958 959 960 961
        param_attr (ParamAttr): Attributes of parameters, including
            name, initializer etc.
        act (str): Non-linear activation to be applied to output variable.

    Returns:
Y
yuyang18 已提交
962
        ${out_comment}.
963 964

    Examples:
B
Bai Yifan 已提交
965 966 967 968 969 970 971 972 973 974 975 976

      .. 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)
977 978
    """
    helper = LayerHelper('row_conv', **locals())
979
    check_variable_and_dtype(input, 'input', ['float32'], 'row_conv')
980
    dtype = helper.input_dtype()
981
    filter_shape = [future_context_size + 1, input.shape[-1]]
982 983 984
    filter_param = helper.create_parameter(
        attr=helper.param_attr, shape=filter_shape, dtype=dtype
    )
X
Xin Pan 已提交
985
    out = helper.create_variable_for_type_inference(dtype)
986 987 988 989 990
    helper.append_op(
        type='row_conv',
        inputs={'X': [input], 'Filter': [filter_param]},
        outputs={'Out': [out]},
    )
Y
yangyaming 已提交
991
    return helper.append_activation(out)
992 993


994
@deprecated(since='2.0.0', update_to='paddle.nn.functional.one_hot')
995
def one_hot(input, depth, allow_out_of_range=False):
996
    """
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

    **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.],
1035
                        [0., 1., 0., 0.],
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
                        [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
1048
            The second dimension in X is 5, which is greater than depth.
1049 1050
            Allow_out_of_range =False means that does not allow the word id to exceed depth,
            so it throws an exception.
1051 1052

    Args:
1053 1054 1055
        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.
1056
        depth(scalar): An integer defining the :attr:`depth` of the one hot dimension. If input
1057
            is word id, depth is generally the dictionary size.
1058
        allow_out_of_range(bool): A bool value indicating whether the input
1059 1060 1061 1062
            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.
1063 1064

    Returns:
1065
        Variable: The one-hot representations of input. A Tensor or LoDTensor with type float32.
1066 1067

    Examples:
C
caoying03 已提交
1068
        .. code-block:: python
1069

1070
            import paddle
1071
            import paddle.fluid as fluid
1072 1073
            paddle.enable_static()

1074 1075 1076
            # 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)
1077
    """
J
Jiabin Yang 已提交
1078
    if _non_static_mode():
S
songyouwei 已提交
1079 1080 1081
        if isinstance(depth, Variable):
            depth = depth.numpy()
            assert depth.shape == (
1082 1083
                1,
            ), "depth of type Variable should have shape [1]"
1084
            depth = depth.item(0)
1085 1086 1087
        out = _legacy_C_ops.one_hot(
            input, 'depth', depth, 'allow_out_of_range', allow_out_of_range
        )
1088 1089
        out.stop_gradient = True
        return out
1090

1091
    helper = LayerHelper("one_hot", **locals())
1092
    check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'one_hot')
1093
    check_type(depth, 'depth', (int, Variable), 'one_hot')
X
Xin Pan 已提交
1094
    one_hot_out = helper.create_variable_for_type_inference(dtype='float32')
1095

1096 1097
    if not isinstance(depth, Variable):
        # user attribute
1098
        inputs = {'X': input}
Y
Yi Liu 已提交
1099
        attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range}
1100
    else:
1101 1102 1103
        depth.stop_gradient = True
        inputs = {'X': input, 'depth_tensor': depth}
        attrs = {'allow_out_of_range': allow_out_of_range}
1104 1105 1106
    helper.append_op(
        type="one_hot", inputs=inputs, attrs=attrs, outputs={'Out': one_hot_out}
    )
1107
    one_hot_out.stop_gradient = True
1108
    return one_hot_out
Y
Yu Yang 已提交
1109 1110


Y
Yu Yang 已提交
1111
def autoincreased_step_counter(counter_name=None, begin=1, step=1):
Y
Yu Yang 已提交
1112
    """
1113 1114
    :api_attr: Static Graph

1115 1116
    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 已提交
1117
    and the step size is 1.
Y
Yu Yang 已提交
1118 1119

    Args:
Y
Yibing Liu 已提交
1120 1121 1122
        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 已提交
1123

1124
    Returns:
Y
Yibing Liu 已提交
1125
        Variable: The auto-increased Variable with data type int64.
Y
yi.wu 已提交
1126 1127 1128 1129

    Examples:
        .. code-block:: python

1130
           import paddle.fluid as fluid
1131 1132
           import paddle
           paddle.enable_static()
Y
yi.wu 已提交
1133
           global_step = fluid.layers.autoincreased_step_counter(
Y
Yibing Liu 已提交
1134
               counter_name='@LR_DECAY_COUNTER@', begin=0, step=1)
Y
Yu Yang 已提交
1135 1136
    """
    helper = LayerHelper('global_step_counter')
Y
Yu Yang 已提交
1137 1138
    if counter_name is None:
        counter_name = '@STEP_COUNTER@'
Y
Yu Yang 已提交
1139
    counter, is_new_var = helper.create_or_get_global_variable(
H
hong 已提交
1140 1141 1142 1143
        name=counter_name,
        dtype='int64',
        shape=[1],
        persistable=True,
1144 1145
        belong_to_optimizer=True,
    )
Y
Yu Yang 已提交
1146
    if is_new_var:
1147 1148 1149
        helper.set_variable_initializer(
            counter, initializer=Constant(value=begin - 1, force_cpu=True)
        )
W
Wu Yi 已提交
1150
        helper.main_program.global_block()._prepend_op(
Y
Yu Yang 已提交
1151 1152
            type='increment',
            inputs={'X': [counter]},
Y
Yu Yang 已提交
1153
            outputs={'Out': [counter]},
1154 1155
            attrs={'step': float(step)},
        )
Y
Yu Yang 已提交
1156 1157 1158
        counter.stop_gradient = True

    return counter
Y
yangyaming 已提交
1159 1160


1161
def unsqueeze(input, axes, name=None):
Y
Yibing Liu 已提交
1162
    """
1163
    Insert single-dimensional entries to the shape of a Tensor. Takes one
M
minqiyang 已提交
1164 1165
    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 已提交
1166

M
minqiyang 已提交
1167
    For example:
H
haowang101779990 已提交
1168 1169 1170

    .. code-block:: text

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

Y
Yibing Liu 已提交
1174
    Args:
1175
        input (Variable): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64.
1176
        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 .
1177
        name (str|None): Name for this layer.
Y
Yibing Liu 已提交
1178 1179

    Returns:
1180
        Variable: Unsqueezed Tensor, with the same data type as input.
Y
Yibing Liu 已提交
1181 1182 1183 1184

    Examples:
        .. code-block:: python

1185 1186 1187
            import paddle.fluid as fluid
            x = fluid.layers.data(name='x', shape=[5, 10])
            y = fluid.layers.unsqueeze(input=x, axes=[1])
1188

Y
Yibing Liu 已提交
1189
    """
J
Jiabin Yang 已提交
1190
    if _non_static_mode():
L
Leo Chen 已提交
1191 1192 1193
        if isinstance(axes, int):
            axes = [axes]
        elif isinstance(axes, Variable):
1194
            axes = axes.numpy().tolist()
L
Leo Chen 已提交
1195 1196 1197 1198 1199
        elif isinstance(axes, (list, tuple)):
            axes = [
                item.numpy().item(0) if isinstance(item, Variable) else item
                for item in axes
            ]
1200
        if _in_legacy_dygraph():
1201
            out, _ = _legacy_C_ops.unsqueeze2(input, 'axes', axes)
1202
            return out
1203
        return _C_ops.unsqueeze(input, axes)
1204 1205

    check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze')
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    check_variable_and_dtype(
        input,
        'input',
        [
            'float16',
            'float32',
            'float64',
            'bool',
            'int8',
            'int16',
            'int32',
            'int64',
            'complex64',
            'complex128',
        ],
        'unsqueeze',
    )
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    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 已提交
1233
        if utils._contain_var(axes):
1234
            inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes)
1235 1236 1237
        else:
            attrs["axes"] = axes

X
Xin Pan 已提交
1238 1239
    out = helper.create_variable_for_type_inference(dtype=input.dtype)
    x_shape = helper.create_variable_for_type_inference(dtype=input.dtype)
1240 1241 1242 1243 1244 1245
    helper.append_op(
        type="unsqueeze2",
        inputs=inputs,
        attrs=attrs,
        outputs={"Out": out, "XShape": x_shape},
    )
Y
Yibing Liu 已提交
1246

1247 1248
    return out

1249

1250
def _logical_op(op_name, x, y, out=None, name=None, binary_op=True):
J
Jiabin Yang 已提交
1251
    if _non_static_mode():
1252
        op = getattr(_legacy_C_ops, op_name)
1253 1254 1255 1256
        if binary_op:
            return op(x, y)
        else:
            return op(x)
1257
    check_variable_and_dtype(
1258 1259
        x,
        "x",
1260
        ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
1261 1262
        op_name,
    )
1263
    if y is not None:
1264
        check_variable_and_dtype(
1265 1266
            y,
            "y",
1267
            ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
1268 1269
            op_name,
        )
1270
    if out is not None:
1271
        check_type(out, "out", Variable, op_name)
1272

M
minqiyang 已提交
1273 1274
    helper = LayerHelper(op_name, **locals())

1275 1276 1277
    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."
1278 1279
            % (op_name, x.dtype, y.dtype)
        )
M
minqiyang 已提交
1280 1281

    if out is None:
1282
        out = helper.create_variable_for_type_inference(dtype=x.dtype)
M
minqiyang 已提交
1283 1284

    if binary_op:
1285 1286 1287
        helper.append_op(
            type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}
        )
M
minqiyang 已提交
1288 1289 1290 1291 1292 1293
    else:
        helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out})

    return out


1294 1295 1296
@templatedoc()
def clip(x, min, max, name=None):
    """
1297
        :old_api: paddle.fluid.layers.clip
1298

1299 1300 1301 1302
    ${comment}

    Args:
        x(${x_type}): ${x_comment}
S
SunGaofeng 已提交
1303 1304
        min(float): ${min_comment}
        max(float): ${max_comment}
1305 1306
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
S
SunGaofeng 已提交
1307
                             For more information, please refer to :ref:`api_guide_Name`
1308 1309

    Returns:
S
SunGaofeng 已提交
1310 1311 1312 1313
        ${out_comment}

    Return Type:
        ${out_type}
1314 1315 1316 1317

    Examples:
        .. code-block:: python

S
SunGaofeng 已提交
1318
            import paddle.fluid as fluid
S
SunGaofeng 已提交
1319
            input = fluid.data(
1320 1321
                name='data', shape=[1], dtype='float32')
            reward = fluid.layers.clip(x=input, min=-1.0, max=1.0)
1322 1323 1324
    """

    helper = LayerHelper("clip", **locals())
1325
    check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'clip')
1326 1327

    if name is None:
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
        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},
    )
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

    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}
1354 1355 1356
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
1357 1358

    Returns:
1359
        Tensor:
W
wangguanzhong 已提交
1360

1361
        out(${out_type}): ${out_comment}
1362

W
wangguanzhong 已提交
1363

1364 1365 1366
    Examples:
        .. code-block:: python

1367
            import paddle
1368
            import paddle.fluid as fluid
1369

1370 1371 1372
            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]]
1373 1374
    """

L
lyq 已提交
1375
    if in_dygraph_mode():
1376
        return _C_ops.clip_by_norm(x, max_norm)
J
Jiabin Yang 已提交
1377
    if _non_static_mode():
1378
        return _legacy_C_ops.clip_by_norm(x, 'max_norm', max_norm)
1379

1380
    helper = LayerHelper("clip_by_norm", **locals())
1381
    check_variable_and_dtype(x, 'X', ['float32', 'float16'], 'clip_by_norm')
1382
    check_type(max_norm, 'max_norm', (float), 'clip_by_norm')
1383 1384

    if name is None:
1385 1386 1387
        name = unique_name.generate_with_ignorable_key(
            ".".join([helper.name, 'tmp'])
        )
S
sneaxiy 已提交
1388

1389 1390 1391
    out = helper.create_variable(
        type=x.type, name=name, dtype=x.dtype, persistable=False
    )
1392

1393 1394 1395 1396 1397 1398
    helper.append_op(
        type="clip_by_norm",
        inputs={"X": x},
        attrs={"max_norm": max_norm},
        outputs={"Out": out},
    )
1399 1400

    return out
X
Xin Pan 已提交
1401 1402


C
chengduo 已提交
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
@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}
1414 1415 1416 1417

    Examples:
        .. code-block:: python

1418
            import paddle.fluid as fluid
1419 1420 1421 1422 1423
            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 已提交
1424
    """
1425 1426 1427
    if in_dygraph_mode():
        return _C_ops.merge_selected_rows(x)

1428
    if _non_static_mode():
1429
        return _legacy_C_ops.merge_selected_rows(x)
C
chengduo 已提交
1430 1431 1432

    helper = LayerHelper("merge_selected_rows", **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
1433 1434 1435 1436 1437 1438
    helper.append_op(
        type="merge_selected_rows",
        inputs={"X": x},
        attrs={},
        outputs={"Out": out},
    )
C
chengduo 已提交
1439 1440 1441 1442 1443 1444
    return out


@templatedoc()
def get_tensor_from_selected_rows(x, name=None):
    """
1445 1446 1447 1448 1449 1450 1451 1452 1453
    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]]

1454
        Output is LoDTensor:
1455 1456 1457 1458 1459 1460
           out.shape = [5, 2]
           out.data = [[1, 1],
                       [2, 2],
                       [2, 2],
                       [3, 3],
                       [6, 6]]
C
chengduo 已提交
1461 1462

    Args:
1463 1464 1465
        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 已提交
1466 1467

    Returns:
1468
        Variable: LoDTensor transformed from SelectedRows. The data type is same with input.
B
bdzhuxiaoning 已提交
1469 1470 1471

    Examples:
        .. code-block:: python
1472

B
bdzhuxiaoning 已提交
1473 1474 1475 1476
            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 已提交
1477 1478
    """

1479 1480 1481 1482 1483
    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 已提交
1484 1485
    helper = LayerHelper('get_tensor_from_selected_rows', **locals())
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
1486 1487 1488 1489 1490 1491
    helper.append_op(
        type='get_tensor_from_selected_rows',
        inputs={'X': x},
        outputs={'Out': out},
        attrs={},
    )
C
chengduo 已提交
1492
    return out