nn.py 35.6 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 ..initializer import Normal, Constant
26 27 28 29 30 31 32 33 34 35 36
from ..framework import (
    Variable,
    OpProtoHolder,
    dygraph_only,
    _dygraph_tracer,
    default_main_program,
    _varbase_creator,
    static_only,
    _global_flags,
    in_dygraph_mode,
)
37
from ..framework import _current_expected_place
38
from .. import dygraph_utils
Y
yangyaming 已提交
39
from ..param_attr import ParamAttr
40 41 42 43 44
from .layer_function_generator import (
    autodoc,
    templatedoc,
    _generate_doc_string_,
)
45
from .tensor import concat, assign, fill_constant, zeros
46
from . import utils
F
fengjiayi 已提交
47
from .. import unique_name
48
from functools import reduce
49
from .. import core
50
from ...utils import deprecated
51 52 53 54 55 56
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
57
from paddle.utils import deprecated
58
from paddle import _C_ops, _legacy_C_ops
59 60
from collections.abc import Iterable

Y
Yu Yang 已提交
61 62

__all__ = [
X
Xin Pan 已提交
63 64 65
    'fc',
    'embedding',
    'autoincreased_step_counter',
Y
Yu Yang 已提交
66 67
]

68
OP_NAMEMAPPING = {
69 70 71 72 73 74 75 76
    '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 已提交
77
    'elementwise_mod': 'remainder',
78 79
}

Y
Yu Yang 已提交
80

81 82
def _get_reduce_dim(dim, input):
    """
83
    Internal function for reduce_sum, reduce_mean, reduce_prod.
84 85 86 87 88 89 90 91 92
    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(
93
                "The type of dim must be int, list, tuple or range, but received {}".format(
94
                    type(dim)
95 96
                )
            )
97 98 99 100 101 102 103 104 105 106
    if dim is None:
        dim = []
    if dim == [] or len(dim) == len(input.shape):
        reduce_all = True
    else:
        reduce_all = False

    return reduce_all, dim


107
@dygraph_only
108 109 110
def _elementwise_op_in_dygraph(
    x, y, axis=-1, act=None, use_mkldnn=False, op_name=None
):
111 112 113 114
    def is_inplace(op_name):
        return op_name[-1] == "_"

    if op_name not in OP_NAMEMAPPING.keys() or axis != -1:
115
        op = getattr(_legacy_C_ops, op_name)
116 117 118
        out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn)
    else:
        if in_dygraph_mode():
119 120
            op = getattr(
                _C_ops,
121 122
                OP_NAMEMAPPING[op_name] if not is_inplace(op_name) else op_name,
            )
123
            out = op(x, y)
124 125 126 127 128 129 130 131 132 133 134 135 136 137
    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,
):
138
    r"""
139 140
    :api_attr: Static Graph

141
    **Fully Connected Layer**
Y
Yu Yang 已提交
142

143 144 145
    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,
146
    which represents a fully connected weight matrix from each input unit to
147 148 149 150
    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`
151
    is not None, a bias variable will be created and added to the output.
152
    Finally, if :attr:`act` is not None, it will be applied to the output as well.
C
caoying03 已提交
153

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

156 157 158 159
    .. math::

        Out = Act({XW + b})

160
    When the input is a list of Tensor(or LoDTensor):
161 162 163

    .. math::

164
        Out = Act({\sum_{i=0}^{N-1}X_iW_i + b})
165 166 167

    In the above equation:

168 169 170
    * :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 已提交
171
    * :math:`b`: The bias parameter created by this layer (if needed).
172
    * :math:`Act`: The activation function.
173
    * :math:`Out`: The output Tensor.
174 175 176

    .. code-block:: text

177 178 179 180 181 182 183 184 185 186 187 188 189 190
        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:
191 192 193 194 195 196 197 198 199 200 201 202 203
            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 已提交
204
    Args:
205 206 207
        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 已提交
208
        size(int): The number of output units in this layer, which also means the feature size of output
209 210
            Tensor(or LoDTensor).
        num_flatten_dims (int): The fc layer can accept an input Tensor with more than
R
ranqiu 已提交
211
            two dimensions. If this happens, the multidimensional tensor will first be flattened
212 213
            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 已提交
214
            dimensions will be flatten to form the first dimension of the final matrix (height of
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            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.
230 231

    Raises:
232
        ValueError: If dimensions of the input Tensor is less than 2.
233 234 235 236

    Examples:
        .. code-block:: python

237
          import paddle.fluid as fluid
238 239
          import paddle
          paddle.enable_static()
240
          # when input is single tensor
241
          data = fluid.data(name="data", shape=[-1, 32], dtype="float32")
242
          fc = fluid.layers.fc(input=data, size=1000, act="tanh")
243 244

          # when input are multiple tensors
245 246
          data_1 = fluid.data(name="data_1", shape=[-1, 32], dtype="float32")
          data_2 = fluid.data(name="data_2", shape=[-1, 36], dtype="float32")
247
          fc = fluid.layers.fc(input=[data_1, data_2], size=1000, act="tanh")
Y
Yu Yang 已提交
248
    """
C
caoying03 已提交
249
    helper = LayerHelper("fc", **locals())
250
    check_type(input, 'input', (list, tuple, Variable), 'fc')
251 252
    if isinstance(input, (list, tuple)):
        for i, input_x in enumerate(input):
253
            check_type(input_x, 'input[' + str(i) + ']', Variable, 'fc')
Y
Yu Yang 已提交
254
    dtype = helper.input_dtype()
255 256 257
    check_dtype(
        dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc'
    )
Y
Yu Yang 已提交
258
    mul_results = []
259 260
    for input_var, param_attr in helper.iter_inputs_and_params():
        input_shape = input_var.shape
261 262
        if num_flatten_dims == -1:
            num_flatten_dims = len(input_shape) - 1
Y
Yu Yang 已提交
263 264 265
        param_shape = [
            reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
        ] + [size]
Y
ying 已提交
266

267 268 269
        w = helper.create_parameter(
            attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False
        )
X
Xin Pan 已提交
270
        tmp = helper.create_variable_for_type_inference(dtype)
271 272 273 274 275 276
        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},
        )
277 278 279 280
        mul_results.append(tmp)

    if len(mul_results) == 1:
        pre_bias = mul_results[0]
281
    else:
X
Xin Pan 已提交
282
        pre_bias = helper.create_variable_for_type_inference(dtype)
283 284 285 286 287 288
        helper.append_op(
            type="sum",
            inputs={"X": mul_results},
            outputs={"Out": pre_bias},
            attrs={"use_mkldnn": False},
        )
289 290 291 292
    # 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 已提交
293 294


T
tangwei12 已提交
295
@deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding")
296 297 298 299 300 301 302 303 304
def embedding(
    input,
    size,
    is_sparse=False,
    is_distributed=False,
    padding_idx=None,
    param_attr=None,
    dtype='float32',
):
305
    r"""
306
    :api_attr: Static Graph
307

308 309 310 311 312 313 314 315 316 317 318 319
    **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.

320
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    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]],
338

339 340 341 342
                        [[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.
343

344
        Case 2:
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359
        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 已提交
360 361

    Args:
362 363 364 365 366 367
        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
368
            affects the performance of the backwards gradient update. It is recommended to set
369
            True because sparse update is faster. But some optimizer does not support sparse update,
370
            such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` ,
371 372 373 374 375
            :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.
376
        padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
377 378 379 380 381 382
            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,
383
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
384
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tianshuo78520a 已提交
385
            vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer`
386 387 388
            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 已提交
389

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

393 394
    Examples:
        .. code-block:: python
Y
Yu Yang 已提交
395

B
bdzhuxiaoning 已提交
396
          import paddle.fluid as fluid
397
          import numpy as np
398 399
          import paddle
          paddle.enable_static()
400

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

T
tianshuo78520a 已提交
403
          # example 1
404 405 406 407 408 409 410 411 412
          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)
413
          emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32')
Y
Yu Yang 已提交
414 415 416
    """

    helper = LayerHelper('embedding', **locals())
417 418 419 420 421 422 423 424 425
    check_variable_and_dtype(
        input, 'input', ['int64'], 'fluid.layers.embedding'
    )
    check_dtype(
        dtype,
        'dtype',
        ['uint16', 'float16', 'float32', 'float64'],
        'fluid.layers.embedding',
    )
426 427 428 429 430 431 432 433 434

    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

435 436 437
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
    )
X
Xin Pan 已提交
438
    tmp = helper.create_variable_for_type_inference(dtype)
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    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 已提交
457 458 459
    return tmp


460 461 462 463 464 465 466 467 468 469 470
def _pull_sparse(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
471
    r"""
472 473 474 475 476 477 478 479 480 481 482 483 484 485 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
    **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
517
        'is_distributed': True,
518 519
    }
    # this is only for compatible with embedding op
520 521 522 523 524 525 526 527 528
    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,
    )
529 530 531 532 533
    if len(outs) == 1:
        return outs[0]
    return outs


534 535 536 537 538 539 540 541 542 543 544
def _pull_sparse_v2(
    input,
    size,
    table_id,
    accessor_class,
    name="embedding",
    ctr_label_name="",
    padding_id=0,
    dtype='float32',
    scale_sparse_grad=True,
):
545
    r"""
546 547 548 549 550 551 552 553 554 555 556 557 558 559 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
    **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
591
        'is_distributed': True,
592 593
    }
    # this is only for compatible with embedding op
594 595 596 597 598 599 600 601 602
    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,
    )
603
    if len(outs) == 1:
Y
yaoxuefeng 已提交
604 605 606 607
        return outs[0]
    return outs


608 609 610
def _pull_gpups_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
Y
yaoxuefeng 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623
    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
624
        float32 now.
Y
yaoxuefeng 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

    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(
644 645 646
            "GpuPS only support float type embedding now, and your type is: "
            + dtype
        )
Y
yaoxuefeng 已提交
647 648 649 650 651 652
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
653 654 655 656 657 658 659 660 661 662 663 664 665
    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 已提交
666
    if len(outs) == 1:
667 668 669 670
        return outs[0]
    return outs


671 672 673
def _pull_box_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
674
    r"""
H
hutuxian 已提交
675 676 677 678 679 680 681
    **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:
682
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
H
hutuxian 已提交
683
            contains the IDs information.
684
        size(int): The embedding size parameter, which indicates the size of
H
hutuxian 已提交
685
            each embedding vector respectively.
686
        dtype(str): The dtype refers to the data type of output tensor. Only supports
687
        float32 now.
H
hutuxian 已提交
688 689 690 691 692 693 694 695 696 697

    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)
698
          emb = fluid.layers.pull_box_sparse(input=data, size=[11])
H
hutuxian 已提交
699 700 701 702
    """
    helper = LayerHelper('pull_box_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
703 704 705
            "BoxPS only support float type embedding now, and your type is: "
            + dtype
        )
H
hutuxian 已提交
706 707 708 709 710 711
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
712 713 714 715 716 717 718 719 720 721 722 723 724
    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 已提交
725 726 727 728 729
    if len(outs) == 1:
        return outs[0]
    return outs


C
caoying03 已提交
730
def reduce_sum(input, dim=None, keep_dim=False, name=None):
G
guosheng 已提交
731
    """
732

Y
yangyaming 已提交
733
    Computes the sum of tensor elements over the given dimension.
G
guosheng 已提交
734 735

    Args:
736 737 738
        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 已提交
739 740
            :attr:`None`, sum all elements of :attr:`input` and return a
            Tensor variable with a single element, otherwise must be in the
W
whs 已提交
741 742
            range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`,
            the dimension to reduce is :math:`rank + dim[i]`.
743
        keep_dim (bool, optional): Whether to reserve the reduced dimension in the
Y
yangyaming 已提交
744
            output Tensor. The result tensor will have one fewer dimension
745 746 747 748
            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 已提交
749 750

    Returns:
751 752
        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 已提交
753

754 755
    Raises:
        TypeError, if out data type is different with the input data type.
756

G
guosheng 已提交
757 758 759
    Examples:
        .. code-block:: python

760
            import paddle.fluid as fluid
761 762
            import paddle
            paddle.enable_static()
G
guosheng 已提交
763 764 765
            # 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 已提交
766
            # Each example is followed by the corresponding output tensor.
767
            x = fluid.data(name='x', shape=[2, 4], dtype='float32')
G
guosheng 已提交
768 769 770 771
            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 已提交
772

773
            # y is a Tensor variable with shape [2, 2, 2] and elements as below:
W
whs 已提交
774 775
            #      [[[1, 2], [3, 4]],
            #      [[5, 6], [7, 8]]]
Q
qiaolongfei 已提交
776
            # Each example is followed by the corresponding output tensor.
777
            y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32')
778 779
            fluid.layers.reduce_sum(y, dim=[1, 2]) # [10, 26]
            fluid.layers.reduce_sum(y, dim=[0, 1]) # [16, 20]
W
whs 已提交
780

G
guosheng 已提交
781
    """
782 783
    reduce_all, dim = _get_reduce_dim(dim, input)

784
    if in_dygraph_mode():
785
        return _C_ops.sum(input, dim, None, keep_dim)
姜永久 已提交
786 787 788 789 790 791 792
    else:
        attrs = {'dim': dim, 'keep_dim': keep_dim, 'reduce_all': reduce_all}
        check_variable_and_dtype(
            input,
            'input',
            ['float16', 'float32', 'float64', 'int32', 'int64'],
            'reduce_sum',
793
        )
姜永久 已提交
794 795 796 797 798 799 800 801 802 803 804
        helper = LayerHelper('reduce_sum', **locals())
        out = helper.create_variable_for_type_inference(
            dtype=helper.input_dtype()
        )
        helper.append_op(
            type='reduce_sum',
            inputs={'X': input},
            outputs={'Out': out},
            attrs=attrs,
        )
        return out
G
guosheng 已提交
805 806


Y
Yu Yang 已提交
807
def autoincreased_step_counter(counter_name=None, begin=1, step=1):
Y
Yu Yang 已提交
808
    """
809 810
    :api_attr: Static Graph

811 812
    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 已提交
813
    and the step size is 1.
Y
Yu Yang 已提交
814 815

    Args:
Y
Yibing Liu 已提交
816 817 818
        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 已提交
819

820
    Returns:
Y
Yibing Liu 已提交
821
        Variable: The auto-increased Variable with data type int64.
Y
yi.wu 已提交
822 823 824 825

    Examples:
        .. code-block:: python

826
           import paddle.fluid as fluid
827 828
           import paddle
           paddle.enable_static()
Y
yi.wu 已提交
829
           global_step = fluid.layers.autoincreased_step_counter(
Y
Yibing Liu 已提交
830
               counter_name='@LR_DECAY_COUNTER@', begin=0, step=1)
Y
Yu Yang 已提交
831 832
    """
    helper = LayerHelper('global_step_counter')
Y
Yu Yang 已提交
833 834
    if counter_name is None:
        counter_name = '@STEP_COUNTER@'
Y
Yu Yang 已提交
835
    counter, is_new_var = helper.create_or_get_global_variable(
H
hong 已提交
836 837 838 839
        name=counter_name,
        dtype='int64',
        shape=[1],
        persistable=True,
840 841
        belong_to_optimizer=True,
    )
Y
Yu Yang 已提交
842
    if is_new_var:
843 844 845
        helper.set_variable_initializer(
            counter, initializer=Constant(value=begin - 1, force_cpu=True)
        )
W
Wu Yi 已提交
846
        helper.main_program.global_block()._prepend_op(
Y
Yu Yang 已提交
847 848
            type='increment',
            inputs={'X': [counter]},
Y
Yu Yang 已提交
849
            outputs={'Out': [counter]},
850 851
            attrs={'step': float(step)},
        )
Y
Yu Yang 已提交
852 853 854
        counter.stop_gradient = True

    return counter
Y
yangyaming 已提交
855 856


857
def unsqueeze(input, axes, name=None):
Y
Yibing Liu 已提交
858
    """
859
    Insert single-dimensional entries to the shape of a Tensor. Takes one
M
minqiyang 已提交
860 861
    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 已提交
862

M
minqiyang 已提交
863
    For example:
H
haowang101779990 已提交
864 865 866

    .. code-block:: text

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

Y
Yibing Liu 已提交
870
    Args:
871
        input (Variable): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64.
872
        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 .
873
        name (str|None): Name for this layer.
Y
Yibing Liu 已提交
874 875

    Returns:
876
        Variable: Unsqueezed Tensor, with the same data type as input.
Y
Yibing Liu 已提交
877 878 879 880

    Examples:
        .. code-block:: python

881 882 883
            import paddle.fluid as fluid
            x = fluid.layers.data(name='x', shape=[5, 10])
            y = fluid.layers.unsqueeze(input=x, axes=[1])
884

Y
Yibing Liu 已提交
885
    """
姜永久 已提交
886
    if in_dygraph_mode():
L
Leo Chen 已提交
887 888 889
        if isinstance(axes, int):
            axes = [axes]
        elif isinstance(axes, Variable):
890
            axes = axes.numpy().tolist()
L
Leo Chen 已提交
891 892 893 894 895
        elif isinstance(axes, (list, tuple)):
            axes = [
                item.numpy().item(0) if isinstance(item, Variable) else item
                for item in axes
            ]
896
        return _C_ops.unsqueeze(input, axes)
姜永久 已提交
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    else:
        check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze')
        check_variable_and_dtype(
            input,
            'input',
            [
                'float16',
                'float32',
                'float64',
                'bool',
                'int8',
                'int16',
                'int32',
                'int64',
                'complex64',
                'complex128',
            ],
            'unsqueeze',
        )
        helper = LayerHelper("unsqueeze2", **locals())
        inputs = {"X": input}
        attrs = {}
919

姜永久 已提交
920 921 922 923 924 925 926 927 928 929
        if isinstance(axes, int):
            axes = [axes]
        if isinstance(axes, Variable):
            axes.stop_gradient = True
            inputs["AxesTensor"] = axes
        elif isinstance(axes, (list, tuple)):
            if utils._contain_var(axes):
                inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes)
            else:
                attrs["axes"] = axes
930

姜永久 已提交
931 932 933 934 935 936 937 938
        out = helper.create_variable_for_type_inference(dtype=input.dtype)
        x_shape = helper.create_variable_for_type_inference(dtype=input.dtype)
        helper.append_op(
            type="unsqueeze2",
            inputs=inputs,
            attrs=attrs,
            outputs={"Out": out, "XShape": x_shape},
        )
Y
Yibing Liu 已提交
939

姜永久 已提交
940
        return out
941

942

943
def _logical_op(op_name, x, y, out=None, name=None, binary_op=True):
姜永久 已提交
944
    if in_dygraph_mode():
945
        op = getattr(_legacy_C_ops, op_name)
946 947 948 949
        if binary_op:
            return op(x, y)
        else:
            return op(x)
姜永久 已提交
950
    else:
951
        check_variable_and_dtype(
姜永久 已提交
952 953
            x,
            "x",
954
            ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
955 956
            op_name,
        )
姜永久 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
        if y is not None:
            check_variable_and_dtype(
                y,
                "y",
                [
                    "bool",
                    "int8",
                    "int16",
                    "int32",
                    "int64",
                    "float32",
                    "float64",
                ],
                op_name,
            )
        if out is not None:
            check_type(out, "out", Variable, op_name)
974

姜永久 已提交
975
        helper = LayerHelper(op_name, **locals())
M
minqiyang 已提交
976

姜永久 已提交
977 978 979 980 981
        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."
                % (op_name, x.dtype, y.dtype)
            )
M
minqiyang 已提交
982

姜永久 已提交
983 984
        if out is None:
            out = helper.create_variable_for_type_inference(dtype=x.dtype)
M
minqiyang 已提交
985

姜永久 已提交
986 987 988 989 990 991 992 993
        if binary_op:
            helper.append_op(
                type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}
            )
        else:
            helper.append_op(
                type=op_name, inputs={"X": x}, outputs={"Out": out}
            )
M
minqiyang 已提交
994

姜永久 已提交
995
        return out