nn.py 67.0 KB
Newer Older
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# 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.
"""
Contrib layers just related to the neural network.
"""

import os
19
import warnings
20
import inspect
21 22

import numpy as np
23
import paddle
24
from paddle.fluid.layer_helper import LayerHelper
25
from paddle.fluid.layers import utils
Z
zhoushiyu 已提交
26
from ... import unique_name
C
Chengmo 已提交
27
from paddle.fluid.initializer import Normal, Constant, NumpyArrayInitializer
28 29 30 31 32 33
from paddle.fluid.data_feeder import (
    check_variable_and_dtype,
    check_type,
    check_dtype,
    convert_dtype,
)
34 35

from paddle.fluid import core
Z
Zhang Ting 已提交
36
from paddle.fluid.param_attr import ParamAttr
37

C
Chengmo 已提交
38
from paddle.fluid.framework import Variable, convert_np_dtype_to_dtype_
39
import paddle
40
import warnings
41
from paddle import _C_ops, _legacy_C_ops
42

43
__all__ = [
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    'fused_embedding_seq_pool',
    'multiclass_nms2',
    'search_pyramid_hash',
    'shuffle_batch',
    'partial_concat',
    'sparse_embedding',
    'partial_sum',
    'tdm_child',
    'rank_attention',
    'tdm_sampler',
    'batch_fc',
    '_pull_box_extended_sparse',
    'bilateral_slice',
    'correlation',
    'fused_bn_add_act',
    'fused_seqpool_cvm',
60
]
61 62


63 64 65 66 67 68 69 70 71
def fused_embedding_seq_pool(
    input,
    size,
    is_sparse=False,
    padding_idx=None,
    combiner='sum',
    param_attr=None,
    dtype='float32',
):
72
    r"""
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    **Embedding Sequence pool**

    This layer is the fusion of lookup table and sequence_pool.

    Args:
        input (Variable): Input is a Tensor<int64> Variable, which contains the IDs' information.
            The value of the input IDs should satisfy :math:`0<= id < size[0]`.
        size (tuple|list): The shape of the lookup_table parameter. It should
            have two elements which indicate the size of the dictionary of
            embedding and the size of each embedding vector respectively.
        is_sparse (bool): The flag indicating whether to use sparse update.
            Default: False.
        padding_idx (int|long|None): It will output all-zero padding data whenever
            lookup encounters :math:`padding\_idx` in Ids. If set :attr:`None`, it makes
            no effect to output. If :math:`padding\_idx < 0`, the :math:`padding\_idx`
            will automatically be converted to :math:`size[0] + padding\_idx` to use.
            Default: None.
        combiner (str): The pooling type of sequence_pool, and only support `sum`.
            Default: sum.
        param_attr (ParamAttr): Parameters for this layer.
        dtype (np.dtype|core.VarDesc.VarType|str): The dtype refers to the data type of output
            tensor. It can be float32, float_16, int etc.
    Returns:
        The sequence pooling variable which is a Tensor.
    Examples:
        .. code-block:: python
            import numpy as np
            import paddle.fluid as fluid
G
GGBond8488 已提交
101 102
            import paddle
            paddle.enable_static()
103 104

            dict_size = 20
G
GGBond8488 已提交
105 106
            data_t = paddle.static.data(
                name='word', shape=[-1, 1], dtype='int64', lod_level=1)
107 108 109 110 111 112 113 114 115
            padding_idx = np.random.randint(1, 10)
            out = fluid.contrib.fused_embedding_seq_pool(
                input=data_t,
                size=[dict_size, 32],
                param_attr='w',
                padding_idx=padding_idx,
                is_sparse=False)
    """
    helper = LayerHelper('fused_embedding_seq_pool', **locals())
116 117 118
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
    )
119
    out = helper.create_variable_for_type_inference(dtype)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    padding_idx = (
        -1
        if padding_idx is None
        else padding_idx
        if padding_idx >= 0
        else (size[0] + padding_idx)
    )
    helper.append_op(
        type='fused_embedding_seq_pool',
        inputs={'Ids': input, 'W': w},
        outputs={'Out': out},
        attrs={
            'is_sparse': is_sparse,
            'combiner': combiner,
            'padding_idx': padding_idx,
        },
    )
137
    return out
138 139


140 141 142
def fused_seqpool_cvm(
    input, pool_type, cvm, pad_value=0.0, use_cvm=True, cvm_offset=2
):
D
danleifeng 已提交
143
    """
144
    :api_attr: Static Graph
D
danleifeng 已提交
145

146
    This OP is the fusion of sequence_pool and continuous_value_model op.
D
danleifeng 已提交
147

148
    **Note:** The Op only receives List of LoDTensor as input, only support SUM pooling now.
D
danleifeng 已提交
149 150 151 152 153

    Args:
        input(Variable|list of Variable): Input is List of LoDTensor.
        pool_type(str): pooling type, only support SUM pooling now.
        cvm(Variable): cvm Variable.
154 155 156 157
        pad_value(float, optional): padding value of sequence pool. Default: 0.0.
        use_cvm(bool, optional): use cvm or not. Default: True.
        cvm_offset(int, optional): cvm offset. Default: 2, which means cvm contains show, click.

D
danleifeng 已提交
158 159 160
    Returns:
        Variable|list of Variable: The tensor variable storing sequence pool and cvm
        of input.
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

    Examples:
        .. code-block:: python

            import paddle
            import paddle.fluid as fluid
            paddle.enable_static()

            data = paddle.static.data(name='x', shape=[-1, 1], dtype='int64', lod_level=1)
            data2 = paddle.static.data(name='y', shape=[-1, 1], dtype='int64', lod_level=1)
            inputs = [data, data2]
            embs = fluid.layers.nn._pull_box_sparse(input=inputs, size=11, is_distributed=True, is_sparse=True)

            label = paddle.static.data(name="label", shape=[-1, 1], dtype="int64", lod_level=1)
            ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype="int64", value=1)
            show_clk = paddle.cast(paddle.concat([ones, label], axis=1), dtype='float32')
            show_clk.stop_gradient = True

            cvms = fluid.contrib.layers.fused_seqpool_cvm(embs, 'sum', show_clk)


D
danleifeng 已提交
182 183 184 185 186 187
    """
    helper = LayerHelper('fused_seqpool_cvm', **locals())

    if pool_type.upper() != 'SUM':
        raise ValueError(
            "fused_seqpool_cvm only support SUM pooling now, and your type is: "
188 189
            + pool_type
        )
D
danleifeng 已提交
190 191 192 193

    check_type(input, 'input', list, 'fused_seqpool_cvm')
    if isinstance(input, list):
        for _input in input:
194 195 196
            check_variable_and_dtype(
                _input, 'input', ['float32'], 'fused_seqpool_cvm'
            )
D
danleifeng 已提交
197 198 199 200 201 202 203 204

    dtype = helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]

205 206 207 208 209 210 211 212 213 214 215
    helper.append_op(
        type="fused_seqpool_cvm",
        inputs={"X": inputs, "CVM": cvm},
        outputs={"Out": outs},
        attrs={
            "pooltype": pool_type.upper(),
            "pad_value": pad_value,
            "use_cvm": use_cvm,
            "cvm_offset": cvm_offset,
        },
    )
D
danleifeng 已提交
216 217 218 219

    return outs


220 221 222 223 224 225 226 227 228 229 230 231 232
def multiclass_nms2(
    bboxes,
    scores,
    score_threshold,
    nms_top_k,
    keep_top_k,
    nms_threshold=0.3,
    normalized=True,
    nms_eta=1.0,
    background_label=0,
    return_index=False,
    name=None,
):
233 234
    """
    **Multiclass NMS2**
C
Chengmo 已提交
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    This operator is to do multi-class non maximum suppression (NMS) on
    boxes and scores.
    In the NMS step, this operator greedily selects a subset of detection bounding
    boxes that have high scores larger than score_threshold, if providing this
    threshold, then selects the largest nms_top_k confidences scores if nms_top_k
    is larger than -1. Then this operator pruns away boxes that have high IOU
    (intersection over union) overlap with already selected boxes by adaptive
    threshold NMS based on parameters of nms_threshold and nms_eta.
    Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
    per image if keep_top_k is larger than -1.

    Args:
        bboxes (Variable): Two types of bboxes are supported:
                           1. (Tensor) A 3-D Tensor with shape
                           [N, M, 4 or 8 16 24 32] represents the
                           predicted locations of M bounding bboxes,
                           N is the batch size. Each bounding box has four
C
Chengmo 已提交
253
                           coordinate values and the layout is
254 255
                           [xmin, ymin, xmax, ymax], when box size equals to 4.
                           2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
C
Chengmo 已提交
256 257
                           M is the number of bounding boxes, C is the
                           class number
258 259 260
        scores (Variable): Two types of scores are supported:
                           1. (Tensor) A 3-D Tensor with shape [N, C, M]
                           represents the predicted confidence predictions.
C
Chengmo 已提交
261 262
                           N is the batch size, C is the class number, M is
                           number of bounding boxes. For each category there
263 264 265 266 267 268 269
                           are total M scores which corresponding M bounding
                           boxes. Please note, M is equal to the 2nd dimension
                           of BBoxes.
                           2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
                           M is the number of bbox, C is the class number.
                           In this case, input BBoxes should be the second
                           case with shape [M, C, 4].
C
Chengmo 已提交
270
        background_label (int): The index of background label, the background
271 272 273
                                label will be ignored. If set to -1, then all
                                categories will be considered. Default: 0
        score_threshold (float): Threshold to filter out bounding boxes with
C
Chengmo 已提交
274
                                 low confidence score. If not provided,
275 276
                                 consider all boxes.
        nms_top_k (int): Maximum number of detections to be kept according to
T
tianshuo78520a 已提交
277
                         the confidences after the filtering detections based
278 279 280 281 282 283 284 285 286 287 288
                         on score_threshold.
        nms_threshold (float): The threshold to be used in NMS. Default: 0.3
        nms_eta (float): The threshold to be used in NMS. Default: 1.0
        keep_top_k (int): Number of total bboxes to be kept per image after NMS
                          step. -1 means keeping all bboxes after NMS step.
        normalized (bool): Whether detections are normalized. Default: True
        return_index(bool): Whether return selected index. Default: False
        name(str): Name of the multiclass nms op. Default: None.

    Returns:
        A tuple with two Variables: (Out, Index) if return_index is True,
C
Chengmo 已提交
289 290 291 292 293 294
        otherwise, a tuple with one Variable(Out) is returned.
        Out: A 2-D LoDTensor with shape [No, 6] represents the detections.
        Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
        or A 2-D LoDTensor with shape [No, 10] represents the detections.
        Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3,
        x4, y4]. No is the total number of detections.
295 296
        If all images have not detected results, all elements in LoD will be
        0, and output tensor is empty (None).
C
Chengmo 已提交
297 298 299 300 301
        Index: Only return when return_index is True. A 2-D LoDTensor with
        shape [No, 1] represents the selected index which type is Integer.
        The index is the absolute value cross batches. No is the same number
        as Out. If the index is used to gather other attribute such as age,
        one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
302 303 304 305 306 307 308 309
        N is the batch size and M is the number of boxes.


    Examples:
        .. code-block:: python


            import paddle.fluid as fluid
G
GGBond8488 已提交
310 311 312
            import paddle
            paddle.enable_static()
            boxes = paddle.static.data(name='bboxes', shape=[-1, 81, 4],
313
                                      dtype='float32', lod_level=1)
G
GGBond8488 已提交
314
            scores = paddle.static.data(name='scores', shape=[-1, 81],
315
                                      dtype='float32', lod_level=1)
G
GGBond8488 已提交
316
            out, index = fluid.contrib.layers.multiclass_nms2(bboxes=boxes,
317 318 319 320 321 322 323 324 325 326 327 328 329
                                              scores=scores,
                                              background_label=0,
                                              score_threshold=0.5,
                                              nms_top_k=400,
                                              nms_threshold=0.3,
                                              keep_top_k=200,
                                              normalized=False,
                                              return_index=True)
    """
    helper = LayerHelper('multiclass_nms2', **locals())

    output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
    index = helper.create_variable_for_type_inference(dtype='int')
330 331 332 333 334 335 336 337 338 339 340 341 342 343
    helper.append_op(
        type="multiclass_nms2",
        inputs={'BBoxes': bboxes, 'Scores': scores},
        attrs={
            'background_label': background_label,
            'score_threshold': score_threshold,
            'nms_top_k': nms_top_k,
            'nms_threshold': nms_threshold,
            'keep_top_k': keep_top_k,
            'nms_eta': nms_eta,
            'normalized': normalized,
        },
        outputs={'Out': output, 'Index': index},
    )
344 345 346 347 348 349
    output.stop_gradient = True
    index.stop_gradient = True

    if return_index:
        return output, index
    return output
A
Aurelius84 已提交
350 351


352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
def search_pyramid_hash(
    input,
    num_emb,
    space_len,
    pyramid_layer,
    rand_len,
    drop_out_percent,
    is_training,
    use_filter,
    white_list_len,
    black_list_len,
    seed,
    lr,
    param_attr=None,
    param_attr_wl=None,
    param_attr_bl=None,
    name=None,
    distribute_update_vars=None,
    dtype='float32',
):
A
Aurelius84 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    """
    **Pyramid hash embedding**

    Args:
        input (Variable): LoDTensor<int32> Variable contained the IDs' information.
        num_emb (int): The embedding size of output.
        space_len (int): The length of pyramid hash embedding space.
        pyramid_layer (int): The number of pyramid layers. It should be greater than 2.
        rand_len (int): The minimum length of pyramid hash cell.
        drop_out_percent (float): The probability of dropping out the input token randomly.
            It should satisfy: [0., 1.]
        is_training (bool): Whether in training or testing phrase.
        use_filter(bool): If set True, the white filter and black filter should be given by
            :attr:`param_attr_wl` and :attr:`param_attr_bl` .
        white_list_len(int): If set :math:`white_list_len>0` , white filter with shape [white_list_len, 1]
            should be provided by param_attr_wl.
        black_list_len(int): If set :math:`black_list_len>0` , black filter with shape [black_list_len, 1]
            should be provided by param_attr_bl.
        seed(int): The number of random seed.
        lr(float): The learning rate of weight created by :attr:`param_attr` with shape [space_len+rand_len, 1]
            in this layer.
        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` .
        param_attr_wl(ParamAttr): Specified parameters of white filter.
        param_attr_bl(ParamAttr): Specified parameters of black filter.
C
Chengmo 已提交
397
        distribute_update_vars(list[ParamAttr.name]): Decided which params should be updated in distribute training.
C
Chengmo 已提交
398
            Used in Distribute Transpiler to create a trainer/server program.
A
Aurelius84 已提交
399 400 401 402 403 404 405 406 407
        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` .
        dtype(str): The data type of output variable, float32.
    Returns:
        Variable: LoDTensor of pyramid hash embedding.
    """
    helper = LayerHelper('search_pyramid_hash', **locals())

    w_shape = [space_len + rand_len, 1]
408 409 410
    w = helper.create_parameter(
        attr=param_attr, shape=w_shape, dtype=dtype, is_bias=False
    )
A
Aurelius84 已提交
411 412 413 414 415
    w.stop_gradient = True

    input_vars = {'X': input, 'W': w}
    if white_list_len > 0:
        wl_shape = [white_list_len, 1]
416 417 418
        white_list = helper.create_parameter(
            attr=param_attr_wl, shape=wl_shape, dtype=dtype, is_bias=False
        )
A
Aurelius84 已提交
419 420 421 422 423
        white_list.stop_gradient = True
        input_vars['WhiteList'] = white_list

    if black_list_len >= 0:
        bl_shape = [black_list_len, 1]
424 425 426
        black_list = helper.create_parameter(
            attr=param_attr_bl, shape=bl_shape, dtype=dtype, is_bias=False
        )
A
Aurelius84 已提交
427 428 429
        black_list.stop_gradient = True
        input_vars['BlackList'] = black_list

C
Chengmo 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442
    distribute_update_vars_str = ""
    if distribute_update_vars:
        assert isinstance(distribute_update_vars, list)
        special_name_list = []
        if param_attr:
            special_name_list.append(param_attr.name)
        if param_attr_wl:
            special_name_list.append(param_attr_wl.name)
        if param_attr_bl:
            special_name_list.append(param_attr_bl.name)
        for param in distribute_update_vars:
            if param not in special_name_list:
                raise ValueError(
443 444
                    "Pyramid Hash layer didn't have parameter {}".format(param)
                )
C
Chengmo 已提交
445 446
        distribute_update_vars_str = ",".join(distribute_update_vars)

A
Aurelius84 已提交
447 448 449
    res = helper.create_variable_for_type_inference(dtype)
    drop_pos = helper.create_variable_for_type_inference(dtype)
    x_temp_out = helper.create_variable_for_type_inference(dtype)
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    helper.append_op(
        type='pyramid_hash',
        inputs=input_vars,
        outputs={"Out": res, "X_Temp_Out": x_temp_out, 'DropPos': drop_pos},
        attrs={
            'num_emb': num_emb,
            'space_len': space_len,
            'pyramid_layer': pyramid_layer,
            'rand_len': rand_len,
            'drop_out_percent': drop_out_percent,
            'is_training': is_training,
            'use_filter': use_filter,
            'white_list_len': white_list_len,
            'black_list_len': black_list_len,
            'seed': seed,
            'lr': lr,
            'distribute_update_vars': distribute_update_vars_str,
        },
    )
A
Aurelius84 已提交
469 470

    return res
Z
zhoushiyu 已提交
471 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


def shuffle_batch(x, seed=None):
    """
    This layer shuffle input tensor :attr:`x` . Normally, :attr:`x` is 2-D LoDTensor.

    :attr:`x` is a LoDTensor to be shuffled with shape :math:`[N_1, N_2, ..., N_k, D]` . Note that the last dim of input will not be shuffled.
    :math:`N_1 * N_2 * ... * N_k` numbers of elements with length :math:`D` will be shuffled randomly.

    For Example:

    .. code-block:: text

      Input:
        x.data = [[1, 2], [3, 4], [5, 6], [7, 8]]
        x.dims = [4, 2]

      Attrs:
        seed = 2019

      Output:
        Out.data =[[7, 8], [1, 2], [3, 4], [5, 6]]
        Out.dims = [4, 2]

    Args:
        x (Variable): The input variable. The input variable is a N-D LoDTensor with type int, float32 or float64.
        seed (None|int|Variable): The start up seed. If set, seed will be set as the start up seed of shuffle engine.
                If not set(Default), start up seed of shuffle engine will be generated randomly.

    Returns:
        Variables: The shuffled LoDTensor with the same shape and lod as input.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid
G
GGBond8488 已提交
508 509 510
            import paddle
            paddle.enable_static()
            x = paddle.static.data(name="x", shape=[-1, 4])
Z
zhoushiyu 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
            out = fluid.contrib.layers.shuffle_batch(x)
    """
    helper = LayerHelper('shuffle_batch', **locals())

    out = helper.create_variable_for_type_inference(dtype=x.dtype)
    shuffle_idx = helper.create_variable_for_type_inference(dtype=np.int64)
    if seed is None and helper.main_program.random_seed != 0:
        seed = helper.main_program.random_seed
    if seed is None:
        seed = np.random.randint(-65536, 65535)
    op_attrs = {}
    if isinstance(seed, int):
        op_attrs["startup_seed"] = seed
        seed = helper.create_variable(
            name=unique_name.generate("shuffle_batch_seed"),
            dtype="int64",
527 528 529 530 531 532 533 534
            persistable=False,
        )
    helper.append_op(
        type='shuffle_batch',
        inputs={'X': x, 'Seed': seed},
        outputs={'Out': out, 'ShuffleIdx': shuffle_idx, 'SeedOut': seed},
        attrs=op_attrs,
    )
Z
zhoushiyu 已提交
535
    return out
536 537 538 539 540 541 542


def partial_concat(input, start_index=0, length=-1):
    """
    **Partial Concat**
    This OP concatenates the inputs according to the start index and length. This
    OP exists in contrib, which means that it is not shown to the public.
C
Chengmo 已提交
543
    Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
544 545 546
    performed along the second dimension.

    .. code-block:: text
C
Chengmo 已提交
547

548 549 550 551 552 553 554 555
        Given:
            x = [[0, 1, 2],
                 [3, 4, 5]]
            y = [[6, 7 ,8],
                 [9, 10, 11]]
            output = partial_concat([x, y], start_index=0, length=2)

          we get:
C
Chengmo 已提交
556

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
            output = [[0, 1, 6, 7],
                      [3, 4, 9, 10]]

    Args:
        input(list): List of input Tensors with data type float32, float64, int32,
            int64.
        start_index(int32): The start index of each instance for partial concatenation.
            Default is 0.
        length(int32): The length of each instance for partial concatenation. Default is -1.
            Negative values for all elements after start_index.
    Returns:
        Variable: A Tensor with the same data type as input's.
    Examples:
        .. code-block:: python
            import paddle.fluid as fluid
            x = fluid.data(name="x", shape=[None,3], dtype="float32")
            y = fluid.data(name="y", shape=[None,3], dtype="float32")
C
Chengmo 已提交
574 575
            concat = fluid.contrib.layers.partial_concat(
                [x, y], start_index=0, length=2)
576 577 578 579
    """
    if not isinstance(input, list):
        warnings.warn(
            "The type of input in partial_concat should be list, but received %s."
580 581
            % (type(input))
        )
582 583 584
        input = [input]
    for id, x in enumerate(input):
        check_variable_and_dtype(
585 586
            x,
            'input[' + str(id) + ']',
587
            ['float16', 'float32', 'float64', 'int32', 'int64'],
588 589
            'partial_concat',
        )
590 591 592 593 594 595
    check_type(start_index, 'start_index', (int), 'partial_concat')
    check_type(length, 'length', (int), 'partial_concat')
    inputs = {'X': input}
    attrs = {'start_index': start_index, 'length': length}
    helper = LayerHelper('partial_concat', **locals())
    out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
596 597 598 599 600 601
    helper.append_op(
        type='partial_concat',
        inputs=inputs,
        outputs={'Out': [out]},
        attrs=attrs,
    )
602
    return out
603 604 605 606 607


def partial_sum(input, start_index=0, length=-1):
    """
    **PartialSum**
C
Chengmo 已提交
608
    This Op can sum the vars by specifying the initial position(start_index) and length(length).
609
    This Op exists in contrib, which means that it is not shown to the public.
C
Chengmo 已提交
610
    Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
611 612
    performed along the second dimension.
    .. code-block:: text
C
Chengmo 已提交
613

614 615 616 617 618 619 620
        Given:
            x = [[0, 1, 2],
                 [3, 4, 5]]
            y = [[6, 7 ,8],
                 [9, 10, 11]]
            output = partial_sum([x, y], start_index=0, length=2)
          we get:
C
Chengmo 已提交
621

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
            output = [[6, 8],
                      [12, 14]]
    Args:
        input(list): List of input Tensors with data type float32, float64, int32,
            int64.
    Returns:
        Variable: A Tensor with the same data type as input's.
    Examples:
        .. code-block:: python
        import paddle.fluid.layers as layers
        import paddle.fluid as fluid
        import numpy as np
        x = fluid.data(name="x", shape=[None, 3], dtype="float32")
        y = fluid.data(name="y", shape=[None, 3], dtype="float32")
        sum = layers.partial_sum([x,y], start_index=0, length=2)
        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        xx = np.array([1,2,3,4,5,6]).reshape((2,3)).astype("float32")
        yy = np.array([6,5,4,4,5,6]).reshape((2,3)).astype("float32")
        out = exe.run(feed={"x":xx, "y":yy}, fetch_list=[sum])
    """
    for id, x in enumerate(input):
644 645 646 647 648 649
        check_variable_and_dtype(
            x,
            'input[' + str(id) + ']',
            ['float32', 'float64', 'int32', 'int64'],
            'partial_sum',
        )
650 651 652 653 654 655 656

    inputs = {'X': input}
    attrs = {}
    attrs['start_index'] = start_index
    attrs['length'] = length
    helper = LayerHelper('partial_sum', **locals())
    out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
657 658 659
    helper.append_op(
        type='partial_sum', inputs=inputs, outputs={'Out': [out]}, attrs=attrs
    )
660
    return out
C
Chengmo 已提交
661 662


663 664 665 666 667 668 669 670 671 672 673
def sparse_embedding(
    input,
    size,
    padding_idx=None,
    is_test=False,
    entry=None,
    table_class="MemorySparseTable",
    param_attr=None,
    dtype='float32',
    slot=None,
):
Y
Yanxing Shi 已提交
674 675 676
    r"""
    :api_attr: Static Graph

677
    The OP is used as the operator of the Embedding Lookup layer in the large-scale
Y
Yanxing Shi 已提交
678 679
    sparse training of the parameter server mode, instead of using the paddle.nn.functional.embedding.

680 681
    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`
Y
Yanxing Shi 已提交
682 683 684 685 686
    (vocab_size, emb_size) and :attr:`dtype` .

    The shape of output Tensor is generated by appending an emb_size dimension to the
    last dimension of the input Tensor shape.

687
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , otherwise
Y
Yanxing Shi 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    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]
        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]],
705

Y
Yanxing Shi 已提交
706 707 708 709
                        [[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.
710

Y
Yanxing Shi 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        Case 2:

        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, 1, 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.

    Args:
729
        input(Variable): A Tensor or LoDTensor with type int64, which contains the id
Y
Yanxing Shi 已提交
730
            information. The value of the input id should satisfy :math:`0<= id < size[0]` .
731 732 733 734
        size(tuple|list): The shape of lookup table parameter (vocab_size, emb_size). It
            should have two elements which indicates the size of the dictionary of embeddings
            and the size of each embedding vector respectively. The initial parameter size
            is 0 in the large-scale sparse scenario, which will gradually expand with the
Y
Yanxing Shi 已提交
735 736
            training. So if vocab_size is temporarily useless, its value can be any integer.
            The emb_size is the dimensional configuration of the word embedding weight parameter.
737
        padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-vocab_size, vocab_size).
Y
Yanxing Shi 已提交
738
            If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
739 740
            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
Y
Yanxing Shi 已提交
741
            while training. If set None, it makes no efe mfect to output. Default: None.
742
        is_test(bool, optional): Training or prediction mode. In prediction mode (is_test=False),
Y
Yanxing Shi 已提交
743
            the output is not initialized and created, and it is filled with 0 and returned. Default: False.
744
        entry(str, optional): Entry config with parameter server whose value is ProbabilityEntry,
Y
Yanxing Shi 已提交
745
            CountFilterEntry or None. Default: None.
746
        table_class(str, optional): The type of the sparse table. The value can be CommonSparseTable
Y
Yanxing Shi 已提交
747 748
            or SSDSparseTable. The default is CommonSparseTable.
        param_attr(ParamAttr, optional): To specify the weight parameter property. Default: None, which means the
749 750 751
            default weight parameter property is used. In addition, user-defined or pre-trained word
            vectors can be loaded with the :attr:`param_attr` parameter. The local word vector needs
            to be transformed into numpy format, and the shape of local word vector should be consistent
Y
Yanxing Shi 已提交
752
            with :attr:`size` .
753
        dtype(str): It refers to the data type of output Tensor. It must be float32 or
Y
Yanxing Shi 已提交
754
            float64. Default: float32.
755

Y
Yanxing Shi 已提交
756 757
    Returns:
        Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
758

Y
Yanxing Shi 已提交
759 760 761 762
    Examples:
        .. code-block:: python

            import paddle
763

Y
Yanxing Shi 已提交
764 765 766 767 768 769 770 771
            paddle.enable_static()
            sparse_feature_dim = 1024
            embedding_size = 64

            # Only when the feature appear more than 10 times or more will be participated in the training.
            entry = paddle.distributed.CountFilterEntry(10)

            input = paddle.static.data(name='ins', shape=[1], dtype='int64')
772

Y
Yanxing Shi 已提交
773 774 775 776 777 778 779 780 781 782
            emb = paddle.static.nn.sparse_embedding(
                input=input,
                size=[sparse_feature_dim, embedding_size],
                is_test=False,
                entry=entry,
                param_attr=paddle.ParamAttr(name="SparseFeatFactors",
                initializer=paddle.nn.initializer.Uniform()))

    """

783 784
    helper = LayerHelper('sparse_embedding', **locals())

785 786 787
    check_variable_and_dtype(
        input, 'input', ['int64'], 'fluid.contrib.layers.sparse_embedding'
    )
788

789 790 791 792 793 794
    check_dtype(
        dtype,
        'dtype',
        ['float32', 'float64'],
        'paddle.static.nn.sparse_embedding',
    )
795

796 797 798 799 800 801 802
    w = helper.create_parameter(
        attr=helper.param_attr,
        shape=size,
        type=core.VarDesc.VarType.SELECTED_ROWS,
        dtype=dtype,
        is_bias=False,
    )
803 804 805

    tmp = helper.create_variable_for_type_inference(dtype)

806 807 808 809 810 811 812
    padding_idx = (
        -1
        if padding_idx is None
        else padding_idx
        if padding_idx >= 0
        else (size[0] + padding_idx)
    )
813

814
    if table_class not in [
815 816 817
        "CommonSparseTable",
        "SSDSparseTable",
        "MemorySparseTable",
818
    ]:
T
Thunderbrook 已提交
819
        raise ValueError(
820 821
            "table_class must be in [CommonSparseTable, SSDSparseTable, MemorySparseTable]"
        )
T
Thunderbrook 已提交
822

823 824 825
    entry_str = "none"

    if entry is not None:
T
tangwei12 已提交
826
        if entry.__class__.__name__ not in [
827 828 829
            "ProbabilityEntry",
            "CountFilterEntry",
            "ShowClickEntry",
T
tangwei12 已提交
830
        ]:
831
            raise ValueError(
832
                "entry must be instance in [paddle.distributed.ProbabilityEntry, paddle.distributed.CountFilterEntry, paddle.distributed.ShowClickEntry]"
T
tangwei12 已提交
833 834
            )
        entry_str = entry._to_attr()
835

836
    if slot is None:
837 838
        slot = 0

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    helper.append_op(
        type='lookup_table',
        inputs={'Ids': input, 'W': w},
        outputs={'Out': tmp},
        attrs={
            'padding_idx': padding_idx,
            'is_sparse': True,
            'is_distributed': True,
            'remote_prefetch': True,
            'is_test': is_test,
            'entry': entry_str,
            'table_class': table_class,
            'slot': slot,
        },
    )
854 855 856
    return tmp


C
Chengmo 已提交
857 858 859
def tdm_child(x, node_nums, child_nums, param_attr=None, dtype='int32'):
    """
    **Tdm Child**
860
     According to the input node_id on the given tree, return the corresponding child node_id and
C
Chengmo 已提交
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
      whether child is a leaf node by leaf_mask value.
    .. code-block:: text

        Given:
            tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes
            x = [[2], [3]]
            node_nums = 7
            child_nums = 2

          we get:
            child = [[5, 6],
                     [0, 0]]
            leaf_mask = [[1, 1],
                         [0, 0]]
    Args:
        x(Variable): Variable contained the node_id information, dtype support int32/int64.
        node_nums(int): Number of total nodes.
        child_nums(int): Maximum number of child nodes per node.
        param_attr(ParamAttr): To specify the tdm-tree-info parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in: ref: `api_fluid_ParamAttr`, should
881 882
            has shape(node_nums, 3 + child_nums), dtype support int32/int64.
            The dimension[1] of tdm-tree-info contains the following:
C
Chengmo 已提交
883 884 885
            1. Item_id(int, shape(1)), if node is a leaf node, give its item_id corresponding to node_id, else give 0.
            2. Layer_id(int, shape(1)), indicates which layer the node is on.
            3. Parent_id(int, shape(1)), node's parent node.
886
            4. Child_id(int, shape(child_nums)), all child node's node_id of this node should be given.
C
Chengmo 已提交
887 888 889 890
            If the number of child nodes is insufficient, padding 0 until child nums equal to child_nums
        dtype(str): The data type of output child and leaf_mask, support int32/int64.

    Returns:
891
        tuple: A tuple including input node's child(Variable) and leaf_mask(Variable).
C
Chengmo 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
            If child is a leaf node, leaf_mask equal ot 1, otherwise equal to 0.

    Examples:
        .. code-block:: python
        import paddle.fluid as fluid
        import numpy as np
        x = fluid.data(name="x", shape=[None, 1], dtype="int32", lod_level=1)
        tree_info = [[0,0,0,1,2],
                     [0,1,0,3,4],[0,1,0,5,6],
                     [0,2,1,0,0],[1,2,1,0,0],[2,2,2,0,0],[3,2,2,0,0]]
        tree_info_np = np.array(tree_info)
        tree_info_np = np.reshape(tree_info_np, (7,5))
        node_nums = 7
        child_nums = 2
        child, leaf_mask  = fluid.contrib.layers.tdm_child(x, node_nums, child_nums,
                                param_attr=fluid.ParamAttr(
                                    initializer=fluid.initializer.NumpyArrayInitializer(
                                                                            tree_info_np)))
        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())
        xx = np.array([[2],[3]]).reshape((2,1)).astype("int32")
        child_res, leaf_mask_res = exe.run(feed={"x":xx}, fetch_list=[child, leaf_mask])
915
    """
C
Chengmo 已提交
916
    helper = LayerHelper("tdm_child", **locals())
917 918 919
    check_dtype(
        dtype, 'dtype', ['int32', 'int64'], 'fluid.contrib.layers.tdm_child'
    )
C
Chengmo 已提交
920
    c_dtype = convert_np_dtype_to_dtype_(dtype)
921 922 923 924 925 926
    tree_info = helper.create_parameter(
        attr=helper.param_attr,
        shape=[node_nums, 3 + child_nums],
        dtype=dtype,
        default_initializer=Constant(0),
    )
C
Chengmo 已提交
927 928 929 930 931
    tree_info.stop_gradient = True

    child = helper.create_variable_for_type_inference(dtype=dtype)
    leaf_mask = helper.create_variable_for_type_inference(dtype=dtype)

932 933 934 935 936 937 938
    helper.append_op(
        type='tdm_child',
        inputs={'X': x, 'TreeInfo': tree_info},
        outputs={'Child': child, 'LeafMask': leaf_mask},
        attrs={'child_nums': child_nums, 'dtype': c_dtype},
        stop_gradient=True,
    )
C
Chengmo 已提交
939
    return (child, leaf_mask)
S
ShenLiang 已提交
940 941


942 943 944 945 946 947 948 949 950 951 952 953 954
def tdm_sampler(
    x,
    neg_samples_num_list,
    layer_node_num_list,
    leaf_node_num,
    tree_travel_attr=None,
    tree_layer_attr=None,
    output_positive=True,
    output_list=True,
    seed=0,
    tree_dtype='int32',
    dtype='int32',
):
C
Chengmo 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    """
    **Tdm Sampler**
    According to the input positive samples at leaf node(x), do negative sampling layer by layer on the given tree.
    .. code-block:: text

        Given:
            tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes
            travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path (exclude root node)
            layer_list = [[1, 2], [3, 4, 5, 6]] # two layer (exclude root node)

            x = [[0], [1], [2], [3]] # Corresponding to leaf node [[3], [4], [5], [6]]
            neg_samples_num_list = [0, 0] # negative sample nums = 0
            layer_node_num_list = [2, 4]
            leaf_node_num = 4
            output_list = False

          we get:
            out = [[1, 3], [1, 4], [2, 5], [2, 6]]
            labels = [[1, 1], [1, 1], [1, 1], [1, 1]]
            mask = [[1, 1], [1, 1], [1, 1], [1, 1]]

    Args:
        x (Variable): Variable contained the item_id(corresponding to leaf node) information, dtype support int32/int64.
        neg_samples_num_list (list(int)): Number of negative samples per layer.
        layer_node_num_list (list(int)): Number of nodes per layer, must has same shape with neg_samples_num_list.
        leaf_node_num (int): Number of leaf nodes.
        tree_travel_attr (ParamAttr): To specify the tdm-travel parameter property. Default: None, which means the
982
            default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr`, should
C
Chengmo 已提交
983 984
            has shape (leaf_node_num, len(layer_node_num_list)), dtype support int32/int64.
        tree_layer_attr (ParamAttr): To specify the tdm-layer parameter property. Default: None, which means the
985
            default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr`, should
C
Chengmo 已提交
986 987 988 989 990
            has shape (node_num, 1), dtype support int32/int64.
        output_positive (bool): Whether to output positive samples (includ label and mask )at the same time.
        output_list (bool): Whether to divide the output into layers and organize it into list format.
        seed (int): The number of random seed.
        tree_dtype(np.dtype|core.VarDesc.VarType|str): The dtype of tdm-travel and tdm-layer, support int32/int64
991
        dtype(np.dtype|core.VarDesc.VarType|str): The dtype of output(sampling results, labels and masks)
C
Chengmo 已提交
992 993 994

    Returns:
        tuple: A tuple including sampling results, corresponding labels and masks. if output_positive = True, sampling
995 996 997
            result  will include both positive and negative samples. If sampling reseult is a positive sample, the label is 1,
            and if it is a negative sample, it is 0. If the tree is unbalanced, in order to ensure the consistency of the
            sampling result shape, the padding sample's mask = 0, the real sample's mask value = 1.
C
Chengmo 已提交
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 1035 1036 1037 1038 1039 1040
            If output_list = True, the result will organize into list format specified by layer information.
            Output variable have same type with tdm-travel and tdm-layer parameter(tree_dtype).

    Examples:
        .. code-block:: python
        import paddle.fluid as fluid
        import numpy as np
        x = fluid.data(name="x", shape=[None, 1], dtype="int32", lod_level=1)
        travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path, shape(leaf_node_num, layer_num)
        layer_list_flat = [[1], [2], [3], [4], [5], [6]] # shape(node_nums, 1)

        neg_samples_num_list = [0, 0] # negative sample nums = 0
        layer_node_num_list = [2, 4] #two layer (exclude root node)
        leaf_node_num = 4

        travel_array = np.array(travel_list)
        layer_array = np.array(layer_list_flat)

        sample, label, mask = fluid.contrib.layers.tdm_sampler(
            x,
            neg_samples_num_list,
            layer_node_num_list,
            leaf_node_num,
            tree_travel_attr=fluid.ParamAttr(
                initializer=fluid.initializer.NumpyArrayInitializer(
                    travel_array)),
            tree_layer_attr=fluid.ParamAttr(
                initializer=fluid.initializer.NumpyArrayInitializer(
                    layer_array)),
            output_positive=True,
            output_list=True,
            seed=0,
            tree_dtype='int32')

        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())
        xx = np.array([[0],[1]]).reshape((2,1)).astype("int32")

        exe.run(feed={"x":xx})

    """
    helper = LayerHelper("tdm_sampler", **locals())
1041 1042 1043 1044 1045 1046 1047 1048 1049
    check_dtype(
        tree_dtype,
        'tree_dtype',
        ['int32', 'int64'],
        'fluid.contrib.layers.tdm_sampler',
    )
    check_dtype(
        dtype, 'dtype', ['int32', 'int64'], 'fluid.contrib.layers.tdm_sampler'
    )
C
Chengmo 已提交
1050 1051 1052 1053 1054 1055
    c_dtype = convert_np_dtype_to_dtype_(dtype)

    if len(neg_samples_num_list) != len(layer_node_num_list):
        raise ValueError(
            "The shape of negative samples list must match the shape of layers. "
            "But received len of neg_samples_num_list: {},"
1056 1057 1058 1059
            "and len of layer_node_num_list: {}, please check your input.".format(
                len(neg_samples_num_list), len(layer_node_num_list)
            )
        )
C
Chengmo 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    assert leaf_node_num is not None, "leaf_node_num should not be None here."

    layer_nums = 0
    node_nums = 0
    tree_layer_offset_lod = [0]
    for layer_idx, layer_node_num in enumerate(layer_node_num_list):
        layer_nums += 1
        node_nums += layer_node_num
        tree_layer_offset_lod.append(node_nums)
        if neg_samples_num_list[layer_idx] >= layer_node_num_list[layer_idx]:
            raise ValueError(
                "The number of negative samples must be less than the number of nodes "
                "in the layer {}, But received negative nums {}, and num of node at layer {} "
                "is {}, please check your input.".format(
1074 1075 1076 1077 1078 1079 1080 1081 1082
                    layer_idx,
                    neg_samples_num_list[layer_idx],
                    layer_idx,
                    layer_node_num_list[layer_idx],
                )
            )
    assert (
        leaf_node_num < node_nums
    ), "leaf_node_num must be less than total node nums."
C
Chengmo 已提交
1083 1084

    travel_shape = [leaf_node_num, layer_nums]
1085 1086 1087 1088 1089 1090
    travel = helper.create_parameter(
        attr=tree_travel_attr,
        shape=travel_shape,
        dtype=tree_dtype,
        default_initializer=Constant(0),
    )
C
Chengmo 已提交
1091 1092

    layer_shape = [node_nums, 1]
1093 1094 1095 1096 1097 1098
    layer = helper.create_parameter(
        attr=tree_layer_attr,
        shape=layer_shape,
        dtype=tree_dtype,
        default_initializer=Constant(0),
    )
C
Chengmo 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

    out = helper.create_variable_for_type_inference(dtype=dtype)
    out.stop_gradient = True

    labels = helper.create_variable_for_type_inference(dtype=dtype)
    labels.stop_gradient = True

    mask = helper.create_variable_for_type_inference(dtype=dtype)
    mask.stop_gradient = True

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    helper.append_op(
        type='tdm_sampler',
        inputs={"X": x, "Travel": travel, "Layer": layer},
        outputs={'Out': out, 'Labels': labels, 'Mask': mask},
        attrs={
            'neg_samples_num_list': neg_samples_num_list,
            'output_positive': output_positive,
            'layer_offset_lod': tree_layer_offset_lod,
            'seed': seed,
            'dtype': c_dtype,
        },
    )
C
Chengmo 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

    if output_list:
        output_list = []
        labels_list = []
        mask_list = []
        start_offset = 0
        positive_flag = 1
        if not output_positive:
            positive_flag = 0

        for layer_sample_num in neg_samples_num_list:
1132
            end_offset = start_offset + layer_sample_num + positive_flag
2
201716010711 已提交
1133
            layer_samples = paddle.slice(
1134 1135
                out, axes=[1], starts=[start_offset], ends=[end_offset]
            )
2
201716010711 已提交
1136
            layer_labels = paddle.slice(
1137 1138
                labels, axes=[1], starts=[start_offset], ends=[end_offset]
            )
2
201716010711 已提交
1139
            layer_mask = paddle.slice(
1140 1141 1142
                mask, axes=[1], starts=[start_offset], ends=[end_offset]
            )

1143
            layer_samples = paddle.reshape(
1144 1145
                layer_samples, [-1, layer_sample_num + positive_flag, 1]
            )
C
Chengmo 已提交
1146 1147
            layer_samples.stop_gradient = True

1148
            layer_labels = paddle.reshape(
1149 1150
                layer_labels, [-1, layer_sample_num + positive_flag, 1]
            )
C
Chengmo 已提交
1151 1152
            layer_labels.stop_gradient = True

1153
            layer_mask = paddle.reshape(
1154 1155
                layer_mask, [-1, layer_sample_num + positive_flag, 1]
            )
C
Chengmo 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
            layer_mask.stop_gradient = True

            output_list.append(layer_samples)
            labels_list.append(layer_labels)
            mask_list.append(layer_mask)
            start_offset = end_offset

        out = output_list
        labels = labels_list
        mask = mask_list

    return (out, labels, mask)


1170 1171 1172 1173 1174 1175 1176 1177
def rank_attention(
    input,
    rank_offset,
    rank_param_shape,
    rank_param_attr,
    max_rank=3,
    max_size=0,
):
S
ShenLiang 已提交
1178 1179
    """
    **Rank Attention layer**
1180
    This Op can calculate rank attention between input and rank_param, and
S
ShenLiang 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    rank_param gives the organization of data. Notice: It currently supports
    GPU device.
    This Op exists in contrib, which means that it is not shown to the public.
    Args:
        input: Tensor with data type float32, float64.
        rank_offset: Tensor with data type int32.
        rank_para_shape: The shape of rank_param.
        rank_param_attr: Attribute initializer of rank_param.
        max_rank: The max rank of input's ranks.
    Returns:
        Variable: A Tensor with the same data type as input's.
    Examples:
        .. code-block:: python
           import paddle.fluid as fluid
           import numpy as np
C
Chengmo 已提交
1196

S
ShenLiang 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
           input = fluid.data(name="input", shape=[None, 2], dtype="float32")
           rank_offset = fluid.data(name="rank_offset", shape=[None, 7], dtype="int32")
           out = fluid.contrib.layers.rank_attention(input=input,
                                                     rank_offset=rank_offset,
                                                     rank_param_shape=[18,3],
                                                     rank_param_attr=
                                                       fluid.ParamAttr(learning_rate=1.0,
                                                                     name="ubm_rank_param.w_0",
                                                                     initializer=
                                                                     fluid.initializer.Xavier(uniform=False)),
1207 1208
                                                      max_rank=3,
                                                      max_size=0)
S
ShenLiang 已提交
1209 1210 1211 1212 1213 1214
    """
    helper = LayerHelper('rank_attention', **locals())
    dtype = helper.input_dtype(input_param_name='input')
    input_shape = input.shape
    assert input_shape[1] * max_rank * max_rank == rank_param_shape[0]

1215 1216 1217
    rank_param = helper.create_parameter(
        attr=rank_param_attr, shape=rank_param_shape, dtype=dtype
    )
S
ShenLiang 已提交
1218 1219 1220
    rank_param.stop_gradient = False

    output = helper.create_variable_for_type_inference(dtype)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    input_help = helper.create_variable_for_type_inference(
        dtype=dtype, stop_gradient=True
    )
    ins_rank = helper.create_variable_for_type_inference(
        dtype=dtype, stop_gradient=True
    )

    helper.append_op(
        type="rank_attention",
        inputs={"X": input, "RankOffset": rank_offset, "RankParam": rank_param},
        outputs={"Out": output, "InputHelp": input_help, "InsRank": ins_rank},
        attrs={"MaxRank": max_rank, "MaxSize": max_size},
    )
S
ShenLiang 已提交
1234
    return output
S
ShenLiang 已提交
1235 1236 1237 1238 1239


def batch_fc(input, param_size, param_attr, bias_size, bias_attr, act=None):
    """
    **Batch FC layer**
1240 1241
    This Op can calculate BatchFC. This is similar to matmul op,
    except that the bias and relu activation layers are added.
S
ShenLiang 已提交
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    Notice: It currently supports GPU device.
    This Op exists in contrib, which means that it is not shown to the public.
    Args:
        input: Tensor with data type float32, float64.
        param_size: The size of w.
        param_attr: Attribute initializer of w.
        bias_size: The size of bias.
        bias_attr: Attribute initializer of bias.
        act: Activation to be applied to the output of this layer.

    Returns:
        Variable: A Tensor with the same data type as input's.
    Examples:
        .. code-block:: python
           import paddle.fluid as fluid
1257

S
ShenLiang 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
           input = fluid.data(name="input", shape=[16, 2, 3], dtype="float32")
           out = fluid.contrib.layers.batch_fc(input=input,
                                               param_size=[16, 3, 10],
                                               param_attr=
                                                 fluid.ParamAttr(learning_rate=1.0,
                                                               name="w_0",
                                                               initializer=
                                                               fluid.initializer.Xavier(uniform=False)),
                                               bias_size=[16, 10],
                                               bias_attr=
                                                 fluid.ParamAttr(learning_rate=1.0,
                                                               name="b_0",
                                                               initializer=
                                                               fluid.initializer.Xavier(uniform=False)),
                                                   act="relu")
    """

    helper = LayerHelper("batch_fc", **locals())
    check_type(input, 'input', (Variable), 'batch_fc')
    input_shape = input.shape
    assert input_shape[0] == param_size[0]
    assert input_shape[2] == param_size[1]
    assert param_size[2] == bias_size[1]
    assert input_shape[0] == bias_size[0]

    dtype = helper.input_dtype()
    check_dtype(dtype, 'input', ['float32', 'float64'], 'batch_fc')

1286 1287 1288 1289 1290 1291
    w = helper.create_parameter(
        attr=param_attr, shape=param_size, dtype=dtype, is_bias=False
    )
    b = helper.create_parameter(
        attr=bias_attr, shape=bias_size, dtype=dtype, is_bias=False
    )
S
ShenLiang 已提交
1292
    pre_act = helper.create_variable_for_type_inference(dtype)
1293 1294 1295 1296 1297
    helper.append_op(
        type="batch_fc",
        inputs={"Input": input, "W": w, "Bias": b},
        outputs={"Out": pre_act},
    )
S
ShenLiang 已提交
1298
    return helper.append_activation(pre_act)
S
ShenLiang 已提交
1299 1300 1301


def _pull_box_extended_sparse(input, size, extend_size=64, dtype='float32'):
1302
    r"""
S
ShenLiang 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311
    **Pull Box Extended 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:
        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.
1312
        extend_size(int): The embedding size parameter in extended dim,
S
ShenLiang 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321
            which indicates the size of each embedding vector respectively.
        dtype(str): The dtype refers to the data type of output tensor. Only supports
      float32 now.
    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs.
    Examples:
        .. code-block:: python
          import paddle.fluid as fluid
G
GGBond8488 已提交
1322
          data = paddle.static.data(name='sequence', shape=[-1, 1], dtype='int64', lod_level=1)
S
ShenLiang 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
          emb, emb_ex = fluid.contrib.layers._pull_box_extended_sparse(input=data, size=8, extend_size=128)
    """
    helper = LayerHelper('pull_box_extended_sparse', **locals())
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
    outs_extend = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
1336 1337 1338 1339 1340 1341
    helper.append_op(
        type='pull_box_extended_sparse',
        inputs={'Ids': inputs},
        outputs={'Out': outs, 'OutExtend': outs_extend},
        attrs={'emb_size': size, 'emb_extended_size': extend_size},
    )
S
ShenLiang 已提交
1342 1343 1344
    if len(outs) == 1:
        return outs[0], outs_extend[0]
    return outs, outs_extend
L
LielinJiang 已提交
1345 1346 1347 1348 1349


def bilateral_slice(x, guide, grid, has_offset, name=None):
    """
    :alias_main: paddle.nn.functional.bilateral_slice
1350 1351
        :alias: paddle.nn.functional.bilateral_slice,paddle.nn.functional.vision.bilateral_slice
        :old_api: paddle.fluid.layers.bilateral_slice
L
LielinJiang 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383

    This operation implements bilateral slicing on the input according to the guide map.
    For more information of bilateral slicing, please refer to Deep Bilateral Learning for Real-Time Image Enhancement <https://groups.csail.mit.edu/graphics/hdrnet/data/hdrnet.pdf>_

    Args:
        x(Variable): The input tensor, which is a 4-D tensor with shape
                     [N, C, H, W], N is the batch size, C is the channel
                     number, H and W is the feature height and width.
                     The data type is float32 and float64.
        guide(Variable): Input grid tensor of shape [N, H, W]. The
                        data type is float32 and float64.
        grid(Variable): Input grid tensor of shape [N, C, D, H, W]. The
                        data type is float32 and float64.
        has_offset(bool): Whether to slice with affine offset.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.

    Returns:
        Variable: Output of shape [N, C, H, W]. The data type is same as input tensor.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid

            x = fluid.data(name='x', shape=[None, 3, 101, 60], dtype='float32')
            guide = fluid.data(name='guide', shape=[None, 101, 60], dtype='float32')
            grid = fluid.data(name='grid', shape=[None, 12, 8, 10, 6], dtype='float32')

            # without offset
1384
            output = fluid.contrib.bilateral_slice(x, guide, grid, has_offset=False)
1385

L
LielinJiang 已提交
1386
            # has offset
1387
            output = fluid.contrib.bilateral_slice(x, guide, grid, has_offset=True)
L
LielinJiang 已提交
1388 1389

    """
J
Jiabin Yang 已提交
1390
    if paddle.fluid._non_static_mode():
1391
        attrs = ('has_offset', has_offset)
1392
        return getattr(_legacy_C_ops, "bilateral_slice")(x, grid, guide, *attrs)
L
LielinJiang 已提交
1393 1394

    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'bilateral_slice')
1395 1396 1397 1398 1399 1400
    check_variable_and_dtype(
        guide, 'guide', ['float32', 'float64'], 'bilateral_slice'
    )
    check_variable_and_dtype(
        grid, 'grid', ['float32', 'float64'], 'bilateral_slice'
    )
1401
    helper = LayerHelper("bilateral_slice", **locals())
L
LielinJiang 已提交
1402 1403
    out = helper.create_variable_for_type_inference(x.dtype)
    inputs = {'X': x, 'Guide': guide, 'Grid': grid}
1404 1405 1406 1407 1408 1409
    helper.append_op(
        type='bilateral_slice',
        inputs=inputs,
        attrs={'has_offset': has_offset},
        outputs={'Out': out},
    )
L
LielinJiang 已提交
1410
    return out
1411 1412


1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
def correlation(
    x,
    y,
    pad_size,
    kernel_size,
    max_displacement,
    stride1,
    stride2,
    corr_type_multiply=1,
):
1423 1424 1425
    """

    This operation compute correlation of two tensor.
1426 1427
    For more information of correlation, please refer to PWC-Net:
    CNNs for Optical Flow Using Pyramid, Warping, and Cost Volume
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    <https://arxiv.org/pdf/1709.02371.pdf>_

    Args:
        x(Tensor): The input x is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64.
        y(Tensor): The input y is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64.
        pad_size(int): Pad size. The data type is int.
        max_displacement(int): Max displacement. The data type is int.
        stride1(int): stride size of x. The data type is int.
        stride2(int): stride size of y. The data type is int.
        corr_type_multiply(int, optional): The type of multiply. The data type is int. Default: 1.

    Returns:
        Tensor: The data type is same as input tensor.

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid
G
GGBond8488 已提交
1447 1448 1449 1450 1451 1452 1453 1454
            import paddle
            paddle.enable_static()
            x1 = paddle.static.data(name='x1',
                               shape=[2,3,4,5],
                               dtype="float32")
            x2 = paddle.static.data(name='x2',
                                shape=[2,3,4,5],
                                dtype="float32")
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467


            out = fluid.contrib.correlation(
                            x1,
                            x2,
                            pad_size=4,
                            kernel_size=1,
                            max_displacement=4,
                            stride1=1,
                            stride2=1)

    """

J
Jiabin Yang 已提交
1468
    if paddle.fluid._non_static_mode():
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
        attrs = (
            "pad_size",
            pad_size,
            "kernel_size",
            kernel_size,
            "max_displacement",
            max_displacement,
            "stride1",
            stride1,
            "stride2",
            stride2,
            "corr_type_multiply",
            corr_type_multiply,
        )
1483
        output = getattr(_legacy_C_ops, "correlation")(x, y, *attrs)
1484
    else:
1485 1486
        helper = LayerHelper("correlation", **locals())
        output = helper.create_variable_for_type_inference(dtype=x.dtype)
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
        helper.append_op(
            type="correlation",
            inputs={"Input1": x, "Input2": y},
            attrs={
                "pad_size": pad_size,
                "kernel_size": kernel_size,
                "max_displacement": max_displacement,
                "stride1": stride1,
                "stride2": stride2,
                "corr_type_multiply": corr_type_multiply,
            },
            outputs={"Output": output},
        )
1500
    return output
Z
Zhang Ting 已提交
1501 1502


1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
def fused_bn_add_act(
    x,
    y,
    momentum=0.9,
    epsilon=1e-05,
    param_attr=None,
    bias_attr=None,
    moving_mean_name=None,
    moving_variance_name=None,
    act=None,
    name=None,
):
1515
    r"""
Z
Zhang Ting 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
    This Op performs batch norm on input x, and adds the result to input y. Then
    it performs activation on the sum. The data format of inputs must be NHWC
    `[batch, in_height, in_width, in_channels]`.

    Args:
        x(Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type
            is float16.
        y(Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type
            is float16.
        momentum(float|Tensor, optional): The value used for the moving_mean and
            moving_var computation. This should be a float number or a tensor with
            shape [1] and data type as float32. The updated formula is:
            :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)`
            :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)`
            Default is 0.9.
        epsilon(float, optional): A value added to the denominator for
            numerical stability. Default is 1e-5.
        param_attr(ParamAttr, optional): The parameter attribute for Parameter `scale`
            of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
1535 1536 1537
                will create ParamAttr as param_attr, the name of scale can be set in ParamAttr.
                If the Initializer of the param_attr is not set, the parameter is initialized
                with Xavier. Default: None.
Z
Zhang Ting 已提交
1538 1539
        bias_attr(ParamAttr, optional): The parameter attribute for the bias of batch_norm.
            If it is set to None or one attribute of ParamAttr, batch_norm
1540 1541 1542
                will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr.
                If the Initializer of the bias_attr is not set, the bias is initialized zero.
                Default: None.
Z
Zhang Ting 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
        moving_mean_name(str, optional): The name of moving_mean which store the global Mean. If it
            is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm
            will save global mean with the string.
        moving_variance_name(str, optional): The name of the moving_variance which store the global Variance.
            If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm
            will save global variance with the string.
        act(string, optional): Activation type, linear|relu|prelu|...
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.

    Examples:
            .. code-block:: python

1556
            import paddle
Z
Zhang Ting 已提交
1557 1558
            import paddle.fluid as fluid

1559 1560
            paddle.enable_static()
            # required: gpu
Z
Zhang Ting 已提交
1561 1562
            def build_program(main_program, startup_program):
                with fluid.program_guard(main_program, startup_program):
G
GGBond8488 已提交
1563 1564
                    x = paddle.static.data(name='x', shape=[-1, 1, 28, 28], dtype='float32')
                    y = paddle.static.data(name="y", shape=[-1, 1], dtype='int64')
1565
                    conv1_1 = paddle.static.nn.conv2d(
Z
Zhang Ting 已提交
1566 1567 1568 1569 1570 1571 1572 1573
                        input=x,
                        filter_size=3,
                        num_filters=32,
                        stride=1,
                        padding=1,
                        act=None,
                        bias_attr=False,
                        data_format='NHWC')
1574
                    conv1_2 = paddle.static.nn.conv2d(
Z
Zhang Ting 已提交
1575 1576 1577 1578 1579 1580 1581 1582
                        input=x,
                        filter_size=3,
                        num_filters=32,
                        stride=1,
                        padding=1,
                        act=None,
                        bias_attr=False,
                        data_format='NHWC')
1583
                    bn = paddle.static.nn.batch_norm(
Z
Zhang Ting 已提交
1584 1585 1586 1587
                        input=conv1_1,
                        act=None,
                        data_layout='NHWC')
                    fused_bn_add_act = fluid.contrib.layers.fused_bn_add_act(conv1_2, bn)
C
Charles-hit 已提交
1588
                    prediction = paddle.static.nn.fc(x=fused_bn_add_act, size=10, activation='softmax')
1589 1590 1591 1592
                    loss = paddle.nn.functional.cross_entropy(
                        input=prediction, label=y,
                        reduction='none', use_softmax=False
                    )
2
201716010711 已提交
1593
                    loss = paddle.mean(loss)
Z
Zhang Ting 已提交
1594
                    sgd = fluid.optimizer.SGD(learning_rate=0.001)
1595
                    sgd = paddle.static.amp.decorate(
Z
Zhang Ting 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
                        sgd, use_dynamic_loss_scaling=True, init_loss_scaling=128.0)
                    sgd.minimize(loss)

                return x, y, loss

            iters = 5
            batch_size = 16
            support_gpu = fluid.is_compiled_with_cuda()
            if support_gpu:
                main_program = fluid.Program()
                startup_program = fluid.Program()
                place = fluid.CUDAPlace(0)
                x, y, loss = build_program(main_program, startup_program)
1609

Z
Zhang Ting 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
                feeder = fluid.DataFeeder(feed_list=[x, y], place=place)
                train_reader = paddle.batch(
                    paddle.dataset.mnist.train(), batch_size=batch_size)
                exe = fluid.Executor(place)
                scope = fluid.Scope()
                with fluid.scope_guard(scope):
                    exe.run(startup_program)
                    for _ in range(iters):
                        data = next(train_reader())
                        loss_v = exe.run(main_program, feed=feeder.feed(data), fetch_list=[loss])
    """
    helper = LayerHelper('fused_bn_add_act', **locals())

1623 1624 1625 1626 1627 1628
    check_variable_and_dtype(
        x, 'input', ['float16', 'float32', 'float64'], 'fused_bn_add_act'
    )
    check_variable_and_dtype(
        y, 'input', ['float16', 'float32', 'float64'], 'fused_bn_add_act'
    )
Z
Zhang Ting 已提交
1629 1630 1631 1632 1633 1634 1635
    bn_param_dtype = core.VarDesc.VarType.FP32

    x_shape = x.shape
    channel_num = x_shape[-1]
    param_shape = [channel_num]

    # create parameter
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    scale = helper.create_parameter(
        attr=helper.param_attr,
        shape=param_shape,
        dtype=bn_param_dtype,
        default_initializer=Constant(1.0),
    )
    bias = helper.create_parameter(
        attr=helper.bias_attr,
        shape=param_shape,
        dtype=bn_param_dtype,
        is_bias=True,
    )
    mean = helper.create_parameter(
        attr=ParamAttr(
            name=moving_mean_name, initializer=Constant(0.0), trainable=False
        ),
        shape=param_shape,
        dtype=bn_param_dtype,
    )
Z
Zhang Ting 已提交
1655
    mean.stop_gradient = True
1656 1657 1658 1659 1660 1661 1662 1663 1664
    variance = helper.create_parameter(
        attr=ParamAttr(
            name=moving_variance_name,
            initializer=Constant(1.0),
            trainable=False,
        ),
        shape=param_shape,
        dtype=bn_param_dtype,
    )
Z
Zhang Ting 已提交
1665 1666 1667 1668 1669 1670 1671
    variance.stop_gradient = True

    # create output
    # mean and mean_out share the same memory
    mean_out = mean
    # variance and variance out share the same memory
    variance_out = variance
1672 1673 1674
    saved_mean = helper.create_variable_for_type_inference(
        dtype=bn_param_dtype, stop_gradient=True
    )
Z
Zhang Ting 已提交
1675
    saved_variance = helper.create_variable_for_type_inference(
1676 1677
        dtype=bn_param_dtype, stop_gradient=True
    )
Z
Zhang Ting 已提交
1678
    reserve_space = helper.create_variable_for_type_inference(
1679 1680
        dtype=core.VarDesc.VarType.FP16, stop_gradient=True
    )
Z
Zhang Ting 已提交
1681
    batch_norm_out = helper.create_variable_for_type_inference(
1682 1683
        core.VarDesc.VarType.FP16
    )
Z
Zhang Ting 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698

    inputs = {
        "X": x,
        "Z": y,
        "Scale": scale,
        "Bias": bias,
    }
    attrs = {"epsilon": epsilon, 'momentum': momentum}

    outputs = {
        "Y": batch_norm_out,
        "MeanOut": mean_out,
        "VarianceOut": variance_out,
        "SavedMean": saved_mean,
        "SavedVariance": saved_variance,
1699
        "ReserveSpace": reserve_space,
Z
Zhang Ting 已提交
1700 1701
    }

1702 1703 1704 1705 1706 1707
    helper.append_op(
        type="fused_bn_add_activation",
        inputs=inputs,
        outputs=outputs,
        attrs=attrs,
    )
Z
Zhang Ting 已提交
1708 1709

    return batch_norm_out
1710 1711


1712 1713 1714
def pow2_decay_with_linear_warmup(
    warmup_steps, total_steps, base_lr, end_lr, dtype='float32', name=None
):
J
Jiabin Yang 已提交
1715
    if paddle.fluid._non_static_mode():
1716
        raise NotImplementedError(
1717 1718
            "pow2_decay_with_linear_warmup does not support dygraph mode yet."
        )
1719 1720 1721

    helper = LayerHelper("pow2_decay_with_linear_warmup", **locals())
    lr = helper.create_global_variable(persistable=True, dtype=dtype, shape=[1])
Z
Zeng Jinle 已提交
1722
    helper.set_variable_initializer(
1723 1724
        lr, Constant(value=float(base_lr) / warmup_steps)
    )
1725

1726 1727 1728
    step = helper.create_global_variable(
        persistable=True, dtype='int64', shape=[1]
    )
1729
    helper.set_variable_initializer(step, Constant(value=0))
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
    assert (
        warmup_steps <= total_steps
    ), "warmup_steps cannot be larger than total_steps"

    helper.append_op(
        type="pow2_decay_with_linear_warmup",
        inputs={"LearningRate": lr, "Step": step},
        outputs={"LearningRateOut": lr, "StepOut": step},
        attrs={
            "warmup_steps": warmup_steps,
            "total_steps": total_steps,
            "base_lr": base_lr,
            "end_lr": end_lr,
        },
    )
1745
    return lr