common.py 94.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
import numpy

17
import paddle
18
from paddle import _C_ops
19
from paddle.common_ops_import import Variable, default_main_program
X
xiaoting 已提交
20
from paddle.fluid.layer_helper import LayerHelper
21 22
from paddle.framework import core, in_dynamic_mode
from paddle.tensor.creation import full
23 24 25 26

from ...fluid.data_feeder import (
    check_dtype,
    check_type,
27
    check_variable_and_dtype,
28
)
29 30
from ...tensor import clip, concat, sqrt, sum
from ...tensor.creation import zeros
Z
zhiboniu 已提交
31

32 33
# TODO: define the common functions to build a neural network
from ...tensor.manipulation import squeeze, unsqueeze
34

35 36
__all__ = []

X
xiaoting 已提交
37

38 39 40
def unfold(x, kernel_sizes, strides=1, paddings=0, dilations=1, name=None):
    r"""

41
    Return a col buffer of sliding local blocks of input x, also known
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    as im2col for batched 2D image tensors. For each block under the convolution filter,
    all element will be rearranged as a column. While the convolution filter sliding over
    the input feature map, a series of such columns will be formed.

    For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout]
    can be calculated as following.

    .. math::

        dkernel[0] &= dilations[0] \times (kernel\_sizes[0] - 1) + 1

        dkernel[1] &= dilations[1] \times (kernel\_sizes[1] - 1) + 1

        hout &= \frac{H + paddings[0] + paddings[2] - dkernel[0]}{strides[0]} + 1

        wout &= \frac{W + paddings[1] + paddings[3] - dkernel[1]}{strides[1]} + 1

        Cout &= C \times kernel\_sizes[0] \times kernel\_sizes[1]

        Lout &= hout \times wout


    Parameters:
        x(Tensor):              4-D Tensor, input tensor of format [N, C, H, W],
                                  data type can be float32 or float64
        kernel_sizes(int|list):   The size of convolution kernel, should be [k_h, k_w]
                                  or an integer k treated as [k, k].
69
        strides(int|list, optional):        The strides, should be [stride_h, stride_w]
70 71
                                  or an integer stride treated as [sride, stride].
                                  For default, strides will be [1, 1].
72
        paddings(int|list, optional):       The paddings of each dimension, should be
73 74 75 76 77 78
                                  [padding_top, padding_left, padding_bottom, padding_right]
                                  or [padding_h, padding_w] or an integer padding.
                                  If [padding_h, padding_w] was given, it will expanded to
                                  [padding_h, padding_w, padding_h, padding_w]. If an integer
                                  padding was given, [padding, padding, padding, padding] will
                                  be used. For default, paddings will be [0, 0, 0, 0]
79
        dilations(int|list, optional):      the dilations of convolution kernel, should be
80 81 82 83 84 85 86 87
                                  [dilation_h, dilation_w], or an integer dilation treated as
                                  [dilation, dilation]. For default, it will be [1, 1].
        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:
88
        Tensor, The tensor corresponding to the sliding local blocks.
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        The output shape is [N, Cout, Lout] as decriabled above.
        Cout is the  total number of values within each block,
        and Lout is the total number of such blocks.
        The data type of output is the same as the input :math:`x`

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn.functional as F

            x = paddle.randn((100,3,224,224))
            y = F.unfold(x, [3, 3], 1, 1, 1)
    """

105 106 107 108
    helper = LayerHelper("unfold", **locals())

    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'unfold')

109
    assert len(x.shape) == 4, "input should be the format of [N, C, H, W]"
110 111 112 113

    if isinstance(kernel_sizes, int):
        kernel_sizes = [kernel_sizes, kernel_sizes]
    else:
114 115 116
        assert isinstance(kernel_sizes, list) and (
            len(kernel_sizes) == 2
        ), "kernel_sizes should either be an integer or a list of two integers"
117 118 119 120

    if isinstance(strides, int):
        strides = [strides, strides]
    else:
121 122 123
        assert isinstance(strides, list) and (
            len(strides) == 2
        ), "strides should either be an integer or a list of two integers"
124 125 126 127

    if isinstance(dilations, int):
        dilations = [dilations, dilations]
    else:
128 129 130
        assert isinstance(dilations, list) and (
            len(dilations) == 2
        ), "dilations should either be an integer or a list of two integers"
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

    if isinstance(paddings, int):
        paddings = [paddings] * 4
    elif isinstance(paddings, list):
        if len(paddings) == 2:
            paddings = paddings * 2
        elif len(paddings) == 4:
            pass
        else:
            raise ValueError(
                "paddings should either be an integer or a list of 2 or 4 integers"
            )
    else:
        raise ValueError(
            "Unexpected type of paddings, it should be either an integer or a list"
146 147
            "of 2 or 4 integers"
        )
148

149
    if in_dynamic_mode():
150
        return _C_ops.unfold(x, kernel_sizes, strides, paddings, dilations)
151 152

    out = helper.create_variable_for_type_inference(dtype=x.dtype)
153 154 155 156 157 158 159 160 161 162 163
    helper.append_op(
        type="unfold",
        inputs={"X": x},
        outputs={"Y": out},
        attrs={
            "kernel_sizes": kernel_sizes,
            "strides": strides,
            "paddings": paddings,
            "dilations": dilations,
        },
    )
164 165 166
    return out


167 168 169 170 171 172 173 174 175 176
def interpolate(
    x,
    size=None,
    scale_factor=None,
    mode='nearest',
    align_corners=False,
    align_mode=0,
    data_format='NCHW',
    name=None,
):
X
xiaoting 已提交
177
    """
S
swtkiwi 已提交
178

179
    This API resizes a batch of images.
180

181 182
    The input must be a 3-D Tensor of the shape (num_batches, channels, in_w)
    or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape
X
xiaoting 已提交
183
    (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels),
184 185
    Where in_w is width of the input tensor, in_h is the height of the input tensor,
    in_d is the depth of the intput tensor.
X
xiaoting 已提交
186
    and the resizing only applies on the three dimensions(depth, height and width).
X
xiaoting 已提交
187

X
xiaoting 已提交
188
    Supporting resample methods:
189 190 191 192 193 194 195

    - 'linear' : Linear interpolation
    - 'bilinear' : Bilinear interpolation
    - 'trilinear' : Trilinear interpolation
    - 'nearest' : Nearest neighbor interpolation
    - 'bicubic' : Bicubic interpolation
    - 'area': Area interpolation
196

197 198 199
    Linear interpolation is the method of using a line connecting two known quantities
    to determine the value of an unknown quantity between the two known quantities.

X
xiaoting 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213
    Nearest neighbor interpolation is to perform nearest neighbor interpolation
    in both the 3rd dimension(in height direction) and the 4th dimension(in width
    direction) on input tensor.

    Bilinear interpolation is an extension of linear interpolation for
    interpolating functions of two variables (e.g. H-direction and
    W-direction in this op) on a rectilinear 2D grid. The key idea is
    to perform linear interpolation first in one direction, and then
    again in the other direction.

    Trilinear interpolation is an extension of linear interpolation for
    interpolating functions of three variables (e.g. D-direction,
    H-direction and W-direction in this op) on a rectilinear 3D grid.
    The linear interpolation is performed on three directions.
X
xiaoting 已提交
214
    align_corners and align_mode are optional parameters,the calculation method
X
xiaoting 已提交
215 216 217 218 219 220 221
    of interpolation can be selected by them.

    Bicubic interpolation is an extension of cubic interpolation for interpolating
    data points on a two-dimensional regular grid. The interpolated surface is
    smoother than corresponding surfaces obtained by bilinear interpolation or
    nearest-neighbor interpolation.

222 223
    Area interpolation is to perform area interpolation
    in both the 3rd dimension(in height direction) , the 4th dimension(in width
224 225
    direction) and the 5th dimension(in depth direction) on input tensor. Set to
    area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or
226 227
    `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`.

X
xiaoting 已提交
228 229 230 231
    Example:

    .. code-block:: text

232
        # For scale_factor:
X
xiaoting 已提交
233 234 235 236 237
            if align_corners = True && out_size > 1 :
              scale_factor = (in_size-1.0)/(out_size-1.0)
            else:
              scale_factor = float(in_size/out_size)

238
        # Linear interpolation:
239 240 241 242 243 244 245 246 247
            if:
                align_corners = False , align_mode = 0
                input : (N,C,W_in)
                output: (N,C,W_out) where:
                W_out = (W_{in}+0.5) * scale_{factor} - 0.5
            else:
                input : (N,C,W_in)
                output: (N,C,W_out) where:
                W_out = W_{in} * scale_{factor}
248

249
        # Nearest neighbor interpolation:
X
xiaoting 已提交
250

X
xiaoting 已提交
251 252 253 254 255
              align_corners = False
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = floor (H_{in} * scale_{factor})
              W_out = floor (W_{in} * scale_{factor})
256

257
        # Bilinear interpolation:
X
xiaoting 已提交
258 259 260 261 262 263 264 265 266 267 268 269
          if:
              align_corners = False , align_mode = 0
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
          else:
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

270
        # Bicubic interpolation:
X
xiaoting 已提交
271 272 273 274 275 276 277 278 279 280 281 282
          if:
              align_corners = False
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
          else:
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

283
        # Trilinear interpolation:
X
xiaoting 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297
          if:
              align_corners = False , align_mode = 0
              input : (N,C,D_in,H_in,W_in)
              output: (N,C,D_out,H_out,W_out) where:
              D_out = (D_{in}+0.5) * scale_{factor} - 0.5
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
          else:
              input : (N,C,D_in,H_in,W_in)
              output: (N,C,D_out,H_out,W_out) where:
              D_out = D_{in} * scale_{factor}
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

298 299
    For details of linear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Linear_interpolation.
300

X
xiaoting 已提交
301 302
    For details of nearest neighbor interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.
303

X
xiaoting 已提交
304 305
    For details of bilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bilinear_interpolation.
306

X
xiaoting 已提交
307 308
    For details of trilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Trilinear_interpolation.
309

X
xiaoting 已提交
310 311
    For details of bicubic interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bicubic_interpolation
312

X
xiaoting 已提交
313
    Parameters:
X
xiaoting 已提交
314
        x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8,
X
xiaoting 已提交
315
                          its data format is specified by :attr:`data_format`.
X
xiaoting 已提交
316
        size (list|tuple|Tensor|None): Output shape of image resize
317 318
             layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w)
             when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor.
319
             Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
X
xiaoting 已提交
320
             If a Tensor, its dimensions size should be a 1.
321 322
        scale_factor (float|Tensor|list|tuple|None): The multiplier for the input height or width. At
             least one of :attr:`size` or :attr:`scale_factor` must be set.
323
             And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if it is either a list or a tuple or a Tensor.If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
X
xiaoting 已提交
324
             Default: None.
325
        mode (str): The resample method. It supports 'linear', 'area', 'nearest', 'bilinear',
326
                       'bicubic' and 'trilinear' currently. Default: 'nearest'
X
xiaoting 已提交
327 328
        align_corners(bool) :  An optional bool, If True, the centers of the 4 corner pixels of the
                               input and output tensors are aligned, preserving the values at the
X
xiaoting 已提交
329
                               corner pixels.This only has an effect when 'linear', 'bilinear', 'bicubic' or 'trilinear'.
330 331 332 333
                               Default: False
        align_mode(int)  :  An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above,
                            it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for
                            src_idx = scale_factor*dst_index.
X
xiaoting 已提交
334
        data_format (str, optional): Specify the data format of the input, and the data format of the output
335
            will be consistent with that of the input. An optional string from:`NCW`, `NWC`,  `"NCHW"`, `"NHWC"`, `"NCDHW"`,
X
xiaoting 已提交
336 337 338
            `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored
            in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
339 340 341
        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`
X
xiaoting 已提交
342
    Returns:
343
        A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels),
X
xiaoting 已提交
344 345
        A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels),
        or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels).
346

347

X
xiaoting 已提交
348 349 350
    Examples:
        .. code-block:: python

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            import paddle
            import paddle.nn.functional as F

            input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32)
            output_1 = F.interpolate(x=input_data, size=[12,12])
            print(output_1.shape)
            # [2L, 3L, 12L, 12L]

            # given scale
            output_2 = F.interpolate(x=input_data, scale_factor=[2,1])
            print(output_2.shape)
            # [2L, 3L, 12L, 10L]

            # bilinear interp
            output_3 = F.interpolate(x=input_data, scale_factor=[2,1], mode="bilinear")
            print(output_2.shape)
            # [2L, 3L, 12L, 10L]
X
xiaoting 已提交
368
    """
369 370 371 372 373 374 375 376 377 378
    data_format = data_format.upper()
    resample = mode.upper()
    resample_type = mode.lower()

    resample_methods = [
        'LINEAR',
        'BILINEAR',
        'TRILINEAR',
        'NEAREST',
        'BICUBIC',
379
        'AREA',
380
    ]
X
xiaoting 已提交
381 382
    if resample not in resample_methods:
        raise ValueError(
383
            "The 'resample' of image_resize can only be 'area', 'linear', 'bilinear', 'trilinear', "
384 385
            " 'bicubic' or 'nearest' currently."
        )
X
xiaoting 已提交
386

X
xiaoting 已提交
387
    if resample in ['LINEAR'] and len(x.shape) != 3:
388
        raise ValueError("'linear' only support 3-D tensor.")
389

390 391 392 393 394
    if resample in ['NEAREST'] and len(x.shape) != 4 and len(x.shape) != 5:
        raise ValueError("'NEAREST' only support 4-D  or 5-D tensor.")

    if resample in ['BILINEAR', 'BICUBIC'] and len(x.shape) != 4:
        raise ValueError("'bilinear' and 'bicubic' only support 4-D tensor.")
X
xiaoting 已提交
395
    if resample == 'TRILINEAR' and len(x.shape) != 5:
396 397 398 399
        raise ValueError("'trilinear'only support 5-D tensor.")

    if size is None and scale_factor is None:
        raise ValueError("One of size and scale_factor must not be None.")
X
xiaoting 已提交
400

401
    if isinstance(size, (tuple, list)) and (len(size) != x.ndim - 2):
402 403 404 405 406 407 408 409 410 411 412 413 414 415
        raise ValueError(
            'The x and size should satisfy rank(x) - 2 == len(size).'
        )

    if isinstance(size, Variable):
        if size.ndim != 1:
            raise ValueError(
                f"If size is a tensor, it's rank must be 1, but received {size.ndim}."
            )
        if size.shape[0] != x.ndim - 2:
            raise ValueError(
                'The x and size should satisfy rank(x) - 2 == size.shape[0].'
            )

X
xiaoting 已提交
416 417
    if not isinstance(align_corners, bool):
        raise TypeError("Attr align_corners should be a bool value")
418

X
xiaoting 已提交
419 420
    if align_mode != 0 and align_mode != 1:
        raise ValueError("align_mode can only be 0 or 1")
X
xiaoting 已提交
421 422 423 424
    if align_corners != 0 and resample == 'NEAREST':
        raise ValueError(
            "align_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinear"
        )
425

X
xiaoting 已提交
426
    if resample == 'AREA':
427
        if isinstance(size, (list, tuple, Variable)):
X
xiaoting 已提交
428 429
            if len(size) == 0:
                raise ValueError("output size can not be empty")
430 431
        if size is None:
            raise ValueError("output size can not be None in AREA mode")
X
xiaoting 已提交
432 433 434
        if len(x.shape) == 3:
            return paddle.nn.functional.adaptive_avg_pool1d(x, size)
        elif len(x.shape) == 4:
435
            print("size :", size)
X
xiaoting 已提交
436 437 438
            return paddle.nn.functional.adaptive_avg_pool2d(x, size)
        elif len(x.shape) == 5:
            return paddle.nn.functional.adaptive_avg_pool3d(x, size)
439
    helper = LayerHelper(f'{resample_type}_interp_v2', **locals())
X
xiaoting 已提交
440
    if len(x.shape) == 3 and data_format not in ['NCW', 'NWC']:
441
        raise ValueError(
442 443 444 445
            "Got wrong value for param `data_format`: "
            + data_format
            + " received but only `NCW` or `NWC` supported for 3-D input."
        )
X
xiaoting 已提交
446
    elif len(x.shape) == 4 and data_format not in ['NCHW', 'NHWC']:
X
xiaoting 已提交
447
        raise ValueError(
448 449 450 451
            "Got wrong value for param `data_format`: "
            + data_format
            + " received but only `NCHW` or `NHWC` supported for 4-D input."
        )
X
xiaoting 已提交
452
    elif len(x.shape) == 5 and data_format not in ['NCDHW', 'NDHWC']:
X
xiaoting 已提交
453
        raise ValueError(
454 455 456 457
            "Got wrong value for param `data_format`: "
            + data_format
            + " received but only `NCDHW` or `NDHWC` supported for 5-D input."
        )
X
xiaoting 已提交
458 459

    def _is_list_or_turple_(data):
460
        return isinstance(data, (list, tuple))
X
xiaoting 已提交
461

462
    if data_format == 'NCHW' or data_format == 'NCDHW' or data_format == 'NCW':
X
xiaoting 已提交
463
        data_layout = 'NCHW'
464
    if data_format == 'NHWC' or data_format == 'NDHWC' or data_format == 'NWC':
X
xiaoting 已提交
465 466
        data_layout = 'NHWC'

X
xiaoting 已提交
467 468 469 470
    if resample == 'NEAREST':
        align_corners = False

    inputs = {"X": x}
X
xiaoting 已提交
471 472 473 474 475 476 477
    attrs = {
        "out_d": -1,
        "out_h": -1,
        "out_w": -1,
        "interp_method": resample_type,
        "align_corners": align_corners,
        "align_mode": align_mode,
478
        "data_layout": data_layout,
X
xiaoting 已提交
479 480
    }

481 482
    out_shape = size
    scale = scale_factor
483 484
    if out_shape is not None and scale is not None:
        raise ValueError("Only one of size or scale_factor should be defined.")
X
xiaoting 已提交
485
    if out_shape is not None:
Z
zhiboniu 已提交
486
        if isinstance(out_shape, Variable) and not in_dynamic_mode():
X
xiaoting 已提交
487 488 489
            out_shape.stop_gradient = True
            inputs['OutSize'] = out_shape
        else:
Z
zhiboniu 已提交
490
            if in_dynamic_mode():
491
                if isinstance(out_shape, Variable):
492
                    out_shape = list(out_shape.numpy(False))
X
xiaoting 已提交
493 494
                else:
                    out_shape = list(out_shape)
495

496 497
                for i, dim in enumerate(out_shape):
                    if isinstance(dim, Variable):
498
                        out_shape[i] = dim.item()
X
xiaoting 已提交
499
            if not (_is_list_or_turple_(out_shape)):
500
                raise TypeError("size should be a list or tuple or Variable.")
X
xiaoting 已提交
501 502 503 504 505 506
            # Validate the shape
            contain_var = False
            for dim_idx, dim_size in enumerate(out_shape):
                if isinstance(dim_size, Variable):
                    contain_var = True
                    continue
507 508 509
                assert (
                    dim_size > 0
                ), "Each dimension size given in out_shape must be greater than 0."
X
xiaoting 已提交
510 511 512 513 514 515 516 517 518 519

            if contain_var:
                new_size_tensor = []
                size_list = []
                for dim in out_shape:
                    if isinstance(dim, Variable):
                        dim.stop_gradient = True
                        new_size_tensor.append(dim)
                        size_list.append(-1)
                    else:
520
                        assert isinstance(dim, int)
X
xiaoting 已提交
521
                        temp_out = helper.create_variable_for_type_inference(
522 523
                            'int32'
                        )
524
                        paddle.tensor.fill_constant(
525 526
                            [1], 'int32', dim, force_cpu=True, out=temp_out
                        )
X
xiaoting 已提交
527 528 529 530
                        new_size_tensor.append(temp_out)
                        size_list.append(dim)
                inputs['SizeTensor'] = new_size_tensor

X
xiaoting 已提交
531
            if len(x.shape) == 3:
532 533
                if len(out_shape) != 1:
                    raise ValueError(
534 535
                        "size length should be 2 for input 3-D tensor"
                    )
536 537 538 539 540
                if contain_var:
                    attrs['out_w'] = size_list[0]
                else:
                    out_shape = list(map(int, out_shape))
                    attrs['out_w'] = out_shape[0]
X
xiaoting 已提交
541
            if len(x.shape) == 4:
X
xiaoting 已提交
542
                if len(out_shape) != 2:
543 544 545
                    raise ValueError(
                        "size length should be 2 for " "input 4-D tensor."
                    )
X
xiaoting 已提交
546 547 548 549 550 551 552
                if contain_var:
                    attrs['out_h'] = size_list[0]
                    attrs['out_w'] = size_list[1]
                else:
                    out_shape = list(map(int, out_shape))
                    attrs['out_h'] = out_shape[0]
                    attrs['out_w'] = out_shape[1]
X
xiaoting 已提交
553
            if len(x.shape) == 5:
X
xiaoting 已提交
554
                if len(out_shape) != 3:
555 556 557
                    raise ValueError(
                        "size length should be 3 for " "input 5-D tensor."
                    )
X
xiaoting 已提交
558 559 560 561 562 563 564 565 566 567 568
                if contain_var:
                    attrs['out_d'] = size_list[0]
                    attrs['out_h'] = size_list[1]
                    attrs['out_w'] = size_list[2]
                else:
                    out_shape = list(map(int, out_shape))
                    attrs['out_d'] = out_shape[0]
                    attrs['out_h'] = out_shape[1]
                    attrs['out_w'] = out_shape[2]

    else:
Z
zhiboniu 已提交
569
        if in_dynamic_mode() and isinstance(scale, Variable):
570 571 572 573
            if scale.shape == []:
                scale = float(scale)
            else:
                scale = list(scale.numpy())
X
xiaoting 已提交
574 575 576
        if isinstance(scale, Variable):
            scale.stop_gradient = True
            inputs["Scale"] = scale
577
        elif isinstance(scale, (float, int, numpy.ndarray)):
X
xiaoting 已提交
578 579
            if scale <= 0:
                raise ValueError("Attr(scale) should be greater than zero.")
X
xiaoting 已提交
580 581 582 583
            scale_list = []
            for i in range(len(x.shape) - 2):
                scale_list.append(scale)
            attrs['scale'] = list(map(float, scale_list))
584
        elif isinstance(scale, (list, tuple)):
X
xiaoting 已提交
585
            if len(scale) != len(x.shape) - 2:
586 587 588 589
                raise ValueError(
                    "scale_shape length should be {} for "
                    "input {}-D tensor.".format(len(x.shape) - 2, len(x.shape))
                )
X
xiaoting 已提交
590 591 592 593
            for value in scale:
                if value <= 0:
                    raise ValueError("Attr(scale) should be greater than zero.")
            attrs['scale'] = list(map(float, scale))
X
xiaoting 已提交
594 595
        else:
            raise TypeError(
596 597
                "Attr(scale)'s type should be float, int, list, tuple, or Tensor."
            )
X
xiaoting 已提交
598

Z
zhiboniu 已提交
599
    if in_dynamic_mode():
X
xiaoting 已提交
600 601 602 603 604 605 606
        attr_list = []
        for k, v in attrs.items():
            attr_list.append(k)
            attr_list.append(v)
        dy_attr = tuple(attr_list)

        if resample_type == "linear":
607 608 609 610 611 612 613 614 615 616 617 618 619 620
            out = _C_ops.linear_interp(
                x,
                inputs['OutSize'] if 'OutSize' in inputs else None,
                inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
                inputs['Scale'] if 'Scale' in inputs else None,
                attrs['data_layout'],
                attrs['out_d'],
                attrs['out_h'],
                attrs['out_w'],
                attrs['scale'] if 'scale' in attrs else [],
                attrs['interp_method'],
                attrs['align_corners'],
                attrs['align_mode'],
            )
621
        elif resample_type == "bilinear":
622 623 624 625 626 627 628 629 630 631 632 633 634 635
            out = _C_ops.bilinear_interp(
                x,
                inputs['OutSize'] if 'OutSize' in inputs else None,
                inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
                inputs['Scale'] if 'Scale' in inputs else None,
                attrs['data_layout'],
                attrs['out_d'],
                attrs['out_h'],
                attrs['out_w'],
                attrs['scale'] if 'scale' in attrs else [],
                attrs['interp_method'],
                attrs['align_corners'],
                attrs['align_mode'],
            )
636
        elif resample_type == "trilinear":
637 638 639 640 641 642 643 644 645 646 647 648 649 650
            out = _C_ops.trilinear_interp(
                x,
                inputs['OutSize'] if 'OutSize' in inputs else None,
                inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
                inputs['Scale'] if 'Scale' in inputs else None,
                attrs['data_layout'],
                attrs['out_d'],
                attrs['out_h'],
                attrs['out_w'],
                attrs['scale'] if 'scale' in attrs else [],
                attrs['interp_method'],
                attrs['align_corners'],
                attrs['align_mode'],
            )
651
        elif resample_type == "nearest":
652 653 654 655 656 657 658 659 660 661 662 663 664 665
            out = _C_ops.nearest_interp(
                x,
                inputs['OutSize'] if 'OutSize' in inputs else None,
                inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
                inputs['Scale'] if 'Scale' in inputs else None,
                attrs['data_layout'],
                attrs['out_d'],
                attrs['out_h'],
                attrs['out_w'],
                attrs['scale'] if 'scale' in attrs else [],
                attrs['interp_method'],
                attrs['align_corners'],
                attrs['align_mode'],
            )
666
        elif resample_type == "bicubic":
667 668 669 670 671 672 673 674 675 676 677 678 679 680
            out = _C_ops.bicubic_interp(
                x,
                inputs['OutSize'] if 'OutSize' in inputs else None,
                inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
                inputs['Scale'] if 'Scale' in inputs else None,
                attrs['data_layout'],
                attrs['out_d'],
                attrs['out_h'],
                attrs['out_w'],
                attrs['scale'] if 'scale' in attrs else [],
                attrs['interp_method'],
                attrs['align_corners'],
                attrs['align_mode'],
            )
X
xiaoting 已提交
681
        return out
W
Weilong Wu 已提交
682 683 684

    dtype = helper.input_dtype(input_param_name='x')

X
xiaoting 已提交
685
    out = helper.create_variable_for_type_inference(dtype)
686
    helper.append_op(
687
        type=f'{resample_type}_interp_v2',
688 689 690 691
        inputs=inputs,
        outputs={"Out": out},
        attrs=attrs,
    )
X
xiaoting 已提交
692
    return out
L
littletomatodonkey 已提交
693 694


695 696 697 698 699 700 701 702 703 704
def upsample(
    x,
    size=None,
    scale_factor=None,
    mode='nearest',
    align_corners=False,
    align_mode=0,
    data_format='NCHW',
    name=None,
):
X
xiaoting 已提交
705
    """
706

707
    This API resizes a batch of images.
708

X
xiaoting 已提交
709 710 711
    The input must be a 3-D Tensor of the shape (num_batches, channels, in_w)
    or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape
    (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels),
712 713
    Where in_w is width of the input tensor, in_h is the height of the input tensor,
    in_d is the depth of the intput tensor.
X
xiaoting 已提交
714 715 716
    and the resizing only applies on the three dimensions(depth, height and width).

    Supporting resample methods:
717 718 719 720 721 722
    - 'linear' : Linear interpolation
    - 'bilinear' : Bilinear interpolation
    - 'trilinear' : Trilinear interpolation
    - 'nearest' : Nearest neighbor interpolation
    - 'bicubic' : Bicubic interpolation

723 724 725
    Linear interpolation is the method of using a line connecting two known quantities
    to determine the value of an unknown quantity between the two known quantities.

X
xiaoting 已提交
726 727 728 729 730 731 732 733
    Nearest neighbor interpolation is to perform nearest neighbor interpolation
    in both the 3rd dimension(in height direction) and the 4th dimension(in width
    direction) on input tensor.
    Bilinear interpolation is an extension of linear interpolation for
    interpolating functions of two variables (e.g. H-direction and
    W-direction in this op) on a rectilinear 2D grid. The key idea is
    to perform linear interpolation first in one direction, and then
    again in the other direction.
734

X
xiaoting 已提交
735 736 737 738
    Bicubic interpolation is an extension of cubic interpolation for interpolating
    data points on a two-dimensional regular grid. The interpolated surface is
    smoother than corresponding surfaces obtained by bilinear interpolation or
    nearest-neighbor interpolation.
739

X
xiaoting 已提交
740 741 742
    Trilinear interpolation is an extension of linear interpolation for
    interpolating functions of three variables (e.g. D-direction,
    H-direction and W-direction in this op) on a rectilinear 3D grid.
743

X
xiaoting 已提交
744 745 746
    The linear interpolation is performed on three directions.
    align_corners and align_mode are optional parameters,the calculation method
    of interpolation can be selected by them.
747 748 749 750 751 752 753

    Area interpolation is to perform area interpolation
    in both the 3rd dimension(in height direction) , the 4th dimension(in width
    direction) and the 5th dimension(in depth direction) on input tensor. Set to
    area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or
    `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`.

X
xiaoting 已提交
754
    Example:
755
        .. code-block:: text
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
            For scale_factor:
                if align_corners = True && out_size > 1 :
                scale_factor = (in_size-1.0)/(out_size-1.0)
                else:
                scale_factor = float(in_size/out_size)
            Linear interpolation:
                if:
                    align_corners = False , align_mode = 0
                    input : (N,C,W_in)
                    output: (N,C,W_out) where:
                    W_out = (W_{in}+0.5) * scale_{factor} - 0.5
                else:
                    input : (N,C,W_in)
                    output: (N,C,W_out) where:
                    W_out = W_{in} * scale_{factor}
            Nearest neighbor interpolation:
            if:
                align_corners = False
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = floor (H_{in} * scale_{factor})
                W_out = floor (W_{in} * scale_{factor})
X
xiaoting 已提交
779
            else:
780 781 782 783 784 785 786
                align_corners = True
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = round(H_{in} * scale_{factor})
                W_out = round(W_{in} * scale_{factor})

            Bilinear interpolation:
X
xiaoting 已提交
787 788
            if:
                align_corners = False , align_mode = 0
789 790 791
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = (H_{in}+0.5) * scale_{factor} - 0.5
X
xiaoting 已提交
792 793
                W_out = (W_{in}+0.5) * scale_{factor} - 0.5
            else:
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = H_{in} * scale_{factor}
                W_out = W_{in} * scale_{factor}
            Bicubic interpolation:
            if:
                align_corners = False
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = (H_{in}+0.5) * scale_{factor} - 0.5
                W_out = (W_{in}+0.5) * scale_{factor} - 0.5
            else:
                input : (N,C,H_in,W_in)
                output: (N,C,H_out,W_out) where:
                H_out = H_{in} * scale_{factor}
                W_out = W_{in} * scale_{factor}
            Trilinear interpolation:
            if:
                align_corners = False , align_mode = 0
                input : (N,C,D_in,H_in,W_in)
                output: (N,C,D_out,H_out,W_out) where:
                D_out = (D_{in}+0.5) * scale_{factor} - 0.5
                H_out = (H_{in}+0.5) * scale_{factor} - 0.5
                W_out = (W_{in}+0.5) * scale_{factor} - 0.5
            else:
                input : (N,C,D_in,H_in,W_in)
                output: (N,C,D_out,H_out,W_out) where:
                D_out = D_{in} * scale_{factor}
                H_out = H_{in} * scale_{factor}
X
xiaoting 已提交
823
                W_out = W_{in} * scale_{factor}
824

X
xiaoting 已提交
825
    For details of linear interpolation, please refer to Wikipedia:
826
    https://en.wikipedia.org/wiki/Linear_interpolation.
827

X
xiaoting 已提交
828 829
    For details of nearest neighbor interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.
830

X
xiaoting 已提交
831 832
    For details of bilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bilinear_interpolation.
833

X
xiaoting 已提交
834 835
    For details of bicubic interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bicubic_interpolation
836

X
xiaoting 已提交
837 838
    For details of trilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Trilinear_interpolation.
839

X
xiaoting 已提交
840 841 842
    Parameters:
        x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8,
                          its data format is specified by :attr:`data_format`.
843
        size (list|tuple|Tensor|None, optional): Output shape of image resize
844 845
             layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w)
             when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor.
846
             Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
X
xiaoting 已提交
847
             If a Tensor , its dimensions size should be a 1.
848
        scale_factor (float|Tensor|list|tuple|None, optional): The multiplier for the input height or width. At
849
             least one of :attr:`size` or :attr:`scale_factor` must be set.
850
             And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if
851
             it is either a list or a tuple or a Tensor. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
X
xiaoting 已提交
852
             Default: None.
853
        mode (str, optional): The resample method. It supports 'linear', 'nearest', 'bilinear',
X
xiaoting 已提交
854
                       'bicubic' and 'trilinear' currently. Default: 'nearest'
855
        align_corners(bool, optional) :  An optional bool, If True, the centers of the 4 corner pixels of the
X
xiaoting 已提交
856 857 858
                               input and output tensors are aligned, preserving the values at the
                               corner pixels.
                               Default: False
859
        align_mode(int, optional)  :  An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above,
X
xiaoting 已提交
860 861 862 863 864 865 866 867 868 869
                            it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for
                            src_idx = scale_factor*dst_index.
        data_format (str, optional): Specify the data format of the input, and the data format of the output
            will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`,
            `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored
            in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
        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`
870

X
xiaoting 已提交
871 872 873 874
    Returns:
        A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels),
        A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels),
        or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels).
875

876 877
    Examples:
        .. code-block:: python
878

879 880
            import paddle
            import paddle.nn as nn
X
xiaoting 已提交
881

882 883
            input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32)
            upsample_out = paddle.nn.Upsample(size=[12,12])
884

885 886 887
            output = upsample_out(x=input_data)
            print(output.shape)
            # [2L, 3L, 12L, 12L]
X
xiaoting 已提交
888 889

    """
890 891 892
    return interpolate(
        x, size, scale_factor, mode, align_corners, align_mode, data_format
    )
X
xiaoting 已提交
893 894


895 896 897 898
def bilinear(x1, x2, weight, bias=None, name=None):
    """

    This layer performs bilinear on two inputs.
899
    See :ref:`api_nn_Bilinear` for details and output shape.
900 901

    Parameters:
902 903 904 905 906 907
        x1 (Tensor): the first input tensor, it's data type should be float32, float64.
        x2 (Tensor): the second input tensor, it's data type should be float32, float64.
        weight (Parameter): The learnable weights of this layer, shape is [out_features, in1_features, in2_features].
        bias (Parameter, optional): The learnable bias(Bias) of this layer, shape is [1, out_features]. If it is set to None, no bias will be added to the output units. The default value is 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`. Default: None.
908 909

    Returns:
910
        Tensor: A 2-D Tensor of shape [batch_size, out_features].
911 912

    Examples:
913
        .. code-block:: python
914

915 916
            import paddle
            import paddle.nn.functional as F
917

918 919 920 921
            x1 = paddle.randn((5, 5)).astype(paddle.float32)
            x2 = paddle.randn((5, 4)).astype(paddle.float32)
            w = paddle.randn((1000, 5, 4)).astype(paddle.float32)
            b = paddle.randn((1, 1000)).astype(paddle.float32)
922

923 924 925
            result = F.bilinear(x1, x2, w, b)
            print(result.shape)
            # [5, 1000]
926 927
    """

928
    if in_dynamic_mode():
929
        return _C_ops.bilinear(x1, x2, weight, bias)
930 931 932
    else:
        check_variable_and_dtype(x1, 'x1', ['float32', 'float64'], 'bilinear')
        check_variable_and_dtype(x2, 'x2', ['float32', 'float64'], 'bilinear')
933

934 935 936
        inputs = {"X": x1, "Y": x2, "Weight": weight}
        if bias is not None:
            inputs["Bias"] = bias
937

938 939
        helper = LayerHelper("bilinear", **locals())
        out = helper.create_variable_for_type_inference(dtype=x1.dtype)
940

941 942 943
        helper.append_op(
            type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out}
        )
944

945
        return out
946 947


948 949 950
def dropout(
    x, p=0.5, axis=None, training=True, mode="upscale_in_train", name=None
):
951
    r"""
952 953 954 955 956 957
    Dropout is a regularization technique for reducing overfitting by preventing
    neuron co-adaption during training. The dropout operator randomly sets the
    outputs of some units to zero, while upscale others according to the given
    dropout probability.

    Args:
958
        x (Tensor): The input tensor. The data type is float16, float32 or float64.
959 960 961
        p (float|int, optional): Probability of setting units to zero. Default: 0.5.
        axis (int|list|tuple, optional): The axis along which the dropout is performed. Default: None.
        training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
962
        mode(str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'].
963

964
            1. upscale_in_train (default), upscale the output at training time
965

966 967
                - train: :math:`out = input \times \frac{mask}{(1.0 - dropout\_prob)}`
                - inference: :math:`out = input`
968

969
            2. downscale_in_infer, downscale the output at inference
970

971 972
                - train: :math:`out = input \times mask`
                - inference: :math:`out = input \times (1.0 - dropout\_prob)`
973

974
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
975 976 977 978

    Returns:
        A Tensor representing the dropout, has same shape and data type as `x` .

979

980 981
    Examples:
        We use ``p=0.5`` in the following description for simplicity.
982

983
        1. When ``axis=None`` , this is commonly used dropout, which dropout each element of x randomly.
984 985 986

        ..  code-block:: text

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
            Let's see a simple case when x is a 2d tensor with shape 2*3:
            [[1 2 3]
             [4 5 6]]
            we generate mask with the same shape as x, which is 2*3. The value of mask is
            sampled from a Bernoulli distribution randomly. For example, we may get such mask:
            [[0 1 0]
             [1 0 1]]
            So the output is obtained from elementwise multiply of x and mask:
            [[0 2 0]
             [4 0 6]]
            Using default setting, i.e. ``mode='upscale_in_train'`` ,
            if in training phase, the final upscale output is:
            [[0 4 0 ]
             [8 0 12]]
            if in test phase, the output is the same as input:
            [[1 2 3]
             [4 5 6]]
            we can also set ``mode='downscale_in_infer'`` , then
            if in training phase, the final output is:
            [[0 2 0]
             [4 0 6]]
            if in test phase, the scale output is:
            [[0.5 1.  1.5]
             [2.  2.5 3. ]]

1012 1013


1014
        2. When ``axis!=None`` , this is useful for dropping whole channels from an image or sequence.
1015 1016 1017

        ..  code-block:: text

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
            Let's see the simple case when x is a 2d tensor with shape 2*3 again:
            [[1 2 3]
             [4 5 6]]
            (1) If ``axis=0`` , this means the dropout is only performed in axis `0` .
                we generate mask with the shape 2*1. Only in axis `0` the value is randomly selected.
                For example, we may get such mask:
                [[1]
                 [0]]
                The output is obtained from elementwise multiply of x and mask. Doing that the mask will be
                broadcast from 2*1 to 2*3:
                [[1 1 1]
                 [0 0 0]]
                and the result after elementwise multiply is:
                [[1 2 3]
                 [0 0 0]]
                then we can do upscale or downscale according to the setting of other arguments.
            (2) If ``axis=1`` , this means the dropout is only performed in axis `1` .
                we generate mask with the shape 1*3. Only in axis `1` the value is randomly selected.
                For example, we may get such mask:
                [[1 0 1]]
                Doing elementwise multiply the mask will be broadcast from 1*3 to 2*3:
                [[1 0 1]
                 [1 0 1]]
                and the result after elementwise multiply is:
                [[1 0 3]
                 [4 0 6]]
            (3) What about ``axis=[0, 1]`` ? This means the dropout is performed in all axes of x,
                which is the same case as default setting ``axis=None`` .
1046
            (4) You may note that logically `axis=None` means the dropout is performed in none axis of x,
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
                We generate mask with the shape 1*1. Whole input is randomly selected or dropped.
                For example, we may get such mask:
                [[0]]
                Doing elementwise multiply the mask will be broadcast from 1*1 to 2*3:
                [[0 0 0]
                 [0 0 0]]
                and the result after elementwise multiply is:
                [[0 0 0]
                 [0 0 0]]
                Actually this is not what we want because all elements may set to zero~
1057

1058 1059
        When x is a 4d tensor with shape `NCHW`, where `N` is batch size, `C` is the number of channels, H and W are the height and width of the feature, we can set ``axis=[0,1]`` and the dropout will be performed in channel `N` and `C`, `H` and `W` is tied, i.e. paddle.nn.dropout(x, p, axis=[0,1]) . Please refer to ``paddle.nn.functional.dropout2d`` for more details.
        Similarly, when x is a 5d tensor with shape `NCDHW`, where `D` is the depth of the feature, we can set ``axis=[0,1]`` to perform dropout3d. Please refer to ``paddle.nn.functional.dropout3d`` for more details.
1060 1061

        .. code-block:: python
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
            import paddle

            x = paddle.to_tensor([[1,2,3], [4,5,6]]).astype(paddle.float32)
            y_train = paddle.nn.functional.dropout(x, 0.5)
            y_test = paddle.nn.functional.dropout(x, 0.5, training=False)
            y_0 = paddle.nn.functional.dropout(x, axis=0)
            y_1 = paddle.nn.functional.dropout(x, axis=1)
            y_01 = paddle.nn.functional.dropout(x, axis=[0,1])
            print(x)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[1., 2., 3.],
            #         [4., 5., 6.]])
            print(y_train)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[2. , 0. , 6. ],
            #         [8. , 0. , 12.]])
            print(y_test)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[1., 2., 3.],
            #         [4., 5., 6.]])
            print(y_0)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[0. , 0. , 0. ],
            #         [8. , 10., 12.]])
            print(y_1)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[2. , 0. , 6. ],
            #         [8. , 0. , 12.]])
            print(y_01)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[0. , 0. , 0. ],
            #         [8. , 0. , 12.]])
1095 1096

    """
1097 1098 1099 1100 1101
    if not isinstance(p, (float, int, Variable)):
        raise TypeError("p argument should be a number or Variable")

    if isinstance(p, (int, float)):
        # fast return for p == 0
1102 1103
        if p == 0:
            return x
1104 1105
        elif p < 0 or p > 1:
            raise ValueError("p argument should between 0 and 1")
1106 1107
    if mode not in ('downscale_in_infer', 'upscale_in_train'):
        raise ValueError(
1108 1109
            "mode argument should be 'downscale_in_infer' or 'upscale_in_train'"
        )
1110
    if axis and not isinstance(axis, (int, list, tuple)):
1111 1112
        raise TypeError("datatype of axis argument should be int or list")

1113
    if axis is None:  # commonly used dropout
1114
        seed = None
1115 1116 1117
        mode = (
            'downgrade_in_infer' if mode == 'downscale_in_infer' else mode
        )  # semantic transfer
1118

1119
        if in_dynamic_mode():
1120 1121
            if default_main_program().random_seed != 0:
                seed = default_main_program().random_seed
H
hong 已提交
1122

1123
            out, mask = _C_ops.dropout(
1124
                x,
1125
                None,
1126 1127 1128
                p,
                not training,
                mode,
1129 1130
                seed if seed is not None else 0,
                seed is not None,
1131
            )
1132

1133 1134 1135 1136
            return out
        else:
            helper = LayerHelper('dropout', **locals())
            check_variable_and_dtype(
1137
                x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'dropout'
1138
            )
1139

1140 1141 1142 1143
            out = helper.create_variable_for_type_inference(dtype=x.dtype)
            mask = helper.create_variable_for_type_inference(
                dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
            )
1144

1145 1146 1147
            def get_attrs(prog, dropout_prob, is_test, seed):
                if (seed is None or seed == 0) and prog.random_seed != 0:
                    seed = prog.random_seed
1148

1149 1150 1151 1152 1153 1154 1155
                if isinstance(
                    dropout_prob, Variable
                ) and not dropout_prob.shape != [1]:
                    raise TypeError(
                        "Required p.shape == [1] if type(p) is Variable, but received p.shape = {}".format(
                            p.shape
                        )
1156
                    )
1157 1158 1159 1160 1161 1162 1163 1164
                attrs = {
                    'dropout_prob': dropout_prob,
                    'is_test': is_test,
                    'fix_seed': seed is not None,
                    'seed': seed if seed is not None else 0,
                    'dropout_implementation': mode,
                }
                return attrs
1165

1166
            attrs = get_attrs(helper.main_program, p, not training, seed)
1167

1168 1169 1170 1171 1172 1173 1174
            helper.append_op(
                type='dropout',
                inputs={'X': [x]},
                outputs={'Out': [out], 'Mask': [mask]},
                attrs=attrs,
            )
            return out
1175
    else:  # sometimes called dropout_nd #TODO: optimize with c++
Z
zhiboniu 已提交
1176
        if not in_dynamic_mode():
1177
            check_variable_and_dtype(
1178
                x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'dropout'
1179
            )
1180 1181 1182
        dtype = x.dtype
        keep_prob = 1 - p
        if training:
1183 1184
            if in_dynamic_mode() and p == 1.0:
                return paddle.scale(x, scale=0.0)
1185

1186 1187 1188 1189 1190
            scale_input = (
                paddle.scale(x, scale=1 / keep_prob)
                if mode == 'upscale_in_train'
                else x
            )
1191

1192
            # get mask shape
1193
            input_shape = x.shape
Z
zhiboniu 已提交
1194
            if not in_dynamic_mode():
1195
                input_shape_tensor = paddle.shape(x)
1196
            drop_axes = [axis] if isinstance(axis, int) else list(axis)
1197
            if min(drop_axes) < 0 or max(drop_axes) > len(input_shape) - 1:
1198 1199 1200 1201 1202
                raise ValueError(
                    "axis value should be greater than or equal to 0 and less than dimensions of x:{}, but get axis value:{} ".format(
                        len(input_shape), max(drop_axes)
                    )
                )
1203 1204
            if len(drop_axes) > len(input_shape):
                raise ValueError(
1205 1206 1207 1208
                    "length of axis should not be greater than dimensions of x:{}, but get length of axis: {}".format(
                        len(input_shape), len(drop_axes)
                    )
                )
1209
            mask_shape = [1] * len(input_shape)
Z
zhiboniu 已提交
1210
            if not in_dynamic_mode():
1211 1212 1213 1214 1215
                for i in drop_axes:
                    mask_shape[i] = input_shape_tensor[i]
            else:
                for i in drop_axes:
                    mask_shape[i] = input_shape[i]
1216

1217 1218 1219 1220
            # get mask
            random_tensor = paddle.uniform(
                mask_shape, dtype='float32', min=0.0, max=1.0
            )
Z
zhiboniu 已提交
1221
            p = full(shape=[1], fill_value=p, dtype='float32')
1222
            keep_mask = paddle.greater_equal(random_tensor, p)
1223

1224 1225
            scale_input = paddle.cast(scale_input, dtype)
            keep_mask = paddle.cast(keep_mask, dtype)
1226 1227 1228
            ret = paddle.multiply(scale_input, keep_mask, name=name)
            return ret
        else:  # test
1229 1230 1231 1232 1233
            ret = (
                paddle.scale(x, scale=keep_prob)
                if mode == 'downscale_in_infer'
                else x
            )
1234 1235 1236 1237 1238 1239 1240 1241 1242
            return ret


def dropout2d(x, p=0.5, training=True, data_format='NCHW', name=None):
    """
    Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
    a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently
    on every forward call with probability `p` using samples from a Bernoulli distribution.

1243
    See :ref:`api_paddle_nn_functional_dropout` for more details.
1244 1245 1246

    Args:
        x (Tensor):  The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C].
1247
                     The data type is float16, float32 or float64.
1248 1249 1250 1251
        p (float, optional): Probability of setting units to zero. Default: 0.5.
        training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
        data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC` . When it is `NCHW` , the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. Default: `NCHW` .
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
1252 1253 1254 1255

    Returns:
        A Tensor representing the dropout2d, has same shape and data type as `x` .

1256

1257 1258
    Examples:
        .. code-block:: python
1259

1260 1261
            import paddle

1262
            x = paddle.randn(shape=(2, 3, 4, 5)).astype(paddle.float32)
1263 1264 1265 1266
            y_train = paddle.nn.functional.dropout2d(x)  #train
            y_test = paddle.nn.functional.dropout2d(x, training=False) #test
            for i in range(2):
                for j in range(3):
1267 1268 1269 1270
                    print(x[i,j,:,:])
                    print(y_train[i,j,:,:]) # may all 0
                    print(y_test[i,j,:,:])

1271 1272 1273
    """
    input_shape = x.shape
    if len(input_shape) != 4:
1274 1275 1276 1277 1278
        raise ValueError(
            "dimensions of x should be 4, but received {} != 4".format(
                len(input_shape)
            )
        )
1279 1280 1281 1282

    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
1283 1284
            "Attr(data_format): %s." % str(data_format)
        )
1285

1286 1287 1288 1289 1290 1291 1292 1293
    return dropout(
        x,
        p=p,
        axis=[0, 1] if data_format == 'NCHW' else [0, 3],
        training=training,
        mode="upscale_in_train",
        name=name,
    )
1294 1295 1296 1297 1298 1299 1300 1301


def dropout3d(x, p=0.5, training=True, data_format='NCDHW', name=None):
    """
    Randomly zero out entire channels (in the batched input 5d tensor with the shape `NCDHW` ,
    a channel is a 3D feature map with the shape `DHW` ). Each channel will be zeroed out independently
    on every forward call with probability `p` using samples from a Bernoulli distribution.

1302
    See :ref:`api_paddle_nn_functional_dropout` for more details.
1303 1304 1305 1306

    Args:
        x (Tensor):  The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C].
                     The data type is float32 or float64.
1307 1308 1309 1310
        p (float, optional): Probability of setting units to zero. Default: 0.5.
        training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
        data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from ``NCDHW`` or ``NDHWC``. When it is ``NCDHW`` , the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. Default: ``NCDHW`` .
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
1311 1312 1313 1314

    Returns:
        A Tensor representing the dropout3d, has same shape and data type with `x` .

1315

1316 1317
    Examples:
        .. code-block:: python
1318

1319
            import paddle
1320

1321 1322 1323 1324 1325 1326
            x = paddle.randn(shape=(2, 3, 4, 5, 6)).astype(paddle.float32)
            y_train = paddle.nn.functional.dropout3d(x)  #train
            y_test = paddle.nn.functional.dropout3d(x, training=False) #test
            print(x[0,0,:,:,:])
            print(y_train[0,0,:,:,:]) # may all 0
            print(y_test[0,0,:,:,:])
1327 1328 1329 1330 1331

    """

    input_shape = x.shape
    if len(input_shape) != 5:
1332 1333 1334 1335 1336
        raise ValueError(
            "dimensions of x should be 5, but received {} != 5".format(
                len(input_shape)
            )
        )
1337 1338 1339 1340

    if data_format not in ["NCDHW", "NDHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
1341 1342
            "Attr(data_format): %s." % str(data_format)
        )
1343

1344 1345 1346 1347 1348 1349 1350 1351
    return dropout(
        x,
        p=p,
        axis=[0, 1] if data_format == 'NCDHW' else [0, 4],
        training=training,
        mode="upscale_in_train",
        name=name,
    )
1352 1353


1354 1355 1356 1357 1358 1359 1360 1361
def alpha_dropout(x, p=0.5, training=True, name=None):
    """
    Alpha Dropout is a type of Dropout that maintains the self-normalizing property.
    For an input with zero mean and unit standard deviation, the output of Alpha Dropout
    maintains the original mean and standard deviation of the input.
    Alpha Dropout fits well to SELU activate function by randomly setting activations to the negative saturation value.

    Args:
1362
        x (Tensor): The input tensor. The data type is float16, float32 or float64.
1363 1364 1365 1366 1367 1368 1369 1370 1371
        p (float | int): Probability of setting units to zero. Default 0.5.
        training (bool): A flag indicating whether it is in train phrase or not. Default True.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        A Tensor representing the dropout, has same shape and data type as `x`.

    Examples:
        .. code-block:: python
1372

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
            import paddle

            x = paddle.to_tensor([[-1, 1], [-1, 1]]).astype(paddle.float32)
            y_train = paddle.nn.functional.alpha_dropout(x, 0.5)
            y_test = paddle.nn.functional.alpha_dropout(x, 0.5, training=False)
            print(y_train)
            # Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[-0.10721093, -0.77919382],
            #         [-0.10721093,  1.66559887]]) (randomly)
            print(y_test)
            # Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[-1.,  1.],
            #         [-1.,  1.]])
1386 1387 1388 1389 1390 1391
    """
    if not isinstance(p, (float, int)):
        raise TypeError("p argument should be a float or int")
    if p < 0 or p > 1:
        raise ValueError("p argument should between 0 and 1")

Z
zhiboniu 已提交
1392
    if not in_dynamic_mode():
1393
        check_variable_and_dtype(
1394
            x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'alpha_dropout'
1395
        )
1396 1397

    if training:
1398
        if p == 1:
1399 1400
            return paddle.scale(x, scale=0.0)
        # get transformation params
1401 1402 1403
        alpha = 1.6732632423543772848170429916717
        scale = 1.0507009873554804934193349852946
        alpha_p = -alpha * scale
1404
        a = ((1 - p) * (1 + p * alpha_p**2)) ** -0.5
1405 1406 1407 1408 1409
        b = -a * alpha_p * p

        dtype = x.dtype
        input_shape = x.shape

1410 1411 1412 1413
        # get mask
        random_tensor = paddle.uniform(
            input_shape, dtype='float32', min=0.0, max=1.0
        )
1414
        p = full(shape=input_shape, fill_value=p, dtype='float32')
1415 1416 1417
        keep_mask = paddle.greater_equal(random_tensor, p)
        keep_mask = paddle.cast(keep_mask, dtype)
        drop_mask = paddle.subtract(
1418 1419
            full(shape=input_shape, fill_value=1.0, dtype=dtype), keep_mask
        )
1420

1421
        # apply mask
1422
        b = full(shape=input_shape, fill_value=b, dtype=dtype)
1423 1424 1425 1426
        y = paddle.add(
            paddle.multiply(x, keep_mask),
            paddle.scale(drop_mask, scale=alpha_p),
        )
1427
        res = paddle.add(paddle.scale(y, scale=a), b, name=name)
1428 1429 1430 1431 1432
        return res
    else:  # test
        return x


1433
def pad(x, pad, mode='constant', value=0.0, data_format="NCHW", name=None):
L
littletomatodonkey 已提交
1434
    """
1435 1436
    Pad tensor according to ``'pad'`` and ``'mode'``.
    If mode is ``'constant'`` and length of pad is twice as length of x dimension,
L
littletomatodonkey 已提交
1437
    then the padding will be started from the first dimension and moved back onto x
1438 1439
    according to ``'pad'`` and ``'value'``.
    If mode is ``'reflect'``, pad[0] and pad[1] must be no greater
L
littletomatodonkey 已提交
1440 1441 1442 1443
    than width-1. The height and depth dimension has the same condition.

    Parameters:
        x (Tensor): The input tensor with data type float32/double/int32/int64_t.
1444
        pad (Tensor|list[int]|tuple[int]): The padding size with data type int.
1445
            If mode is ``'constant'`` and length of pad is twice as length of x dimension, then x will
1446 1447
            be padded from the first  dimension to the last dimension.
            Else: 1. If input dimension is 3, then the pad has the form (pad_left,
1448 1449
            pad_right). 2. If the input dimension is 4, then the pad has the form (pad_left, pad_right,
            pad_top, pad_bottom). 3. If the input dimension is 5, then the pad has the form
L
littletomatodonkey 已提交
1450
            (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back).
1451
        mode (str, optional): Four modes: ``'constant'`` (default), ``'reflect'``, ``'replicate'``, ``'circular'``. Default is ``'constant'``.
1452 1453 1454 1455 1456 1457

           - 'constant' mode, uses a constant value to pad the input tensor.
           - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
           - 'replicate' mode, uses input boundaries to pad the input tensor.
           - 'circular' mode, uses circular input to pad the input tensor.

1458 1459 1460 1461
        value (float, optional): The value to fill the padded areas in 'constant' mode . Default is :math:`0.0`.
        data_format (str, optional): An string from: ``'NCL'``, ``'NLC'``, ``'NHWC'``, ``'NCHW'``, ``'NCDHW'``, ``'NDHWC'``. Specify the data format of
           the input data. Default: ``'NCHW'``.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: ``'None'``.
1462 1463

    Returns:
1464
        Tensor, a Tensor padded according to pad and mode and data type is same as input.
L
littletomatodonkey 已提交
1465

1466
    Example:
1467

L
littletomatodonkey 已提交
1468 1469 1470 1471 1472 1473
        .. code-block:: text

            x = [[[[[1., 2., 3.],
                    [4., 5., 6.]]]]]

            Case 0:
1474 1475 1476 1477 1478 1479 1480 1481 1482
                pad = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
                mode = 'constant'
                value = 0
                Out = [[[[[0., 0., 0.],
                          [1., 2., 3.],
                          [4., 5., 6.],
                          [0., 0., 0.]]]]]

            Case 1:
L
littletomatodonkey 已提交
1483 1484 1485 1486 1487 1488 1489 1490
                pad = [2, 2, 1, 1, 0, 0],
                mode = 'constant'
                value = 0
                Out = [[[[[0. 0. 0. 0. 0. 0. 0.]
                          [0. 0. 1. 2. 3. 0. 0.]
                          [0. 0. 4. 5. 6. 0. 0.]
                          [0. 0. 0. 0. 0. 0. 0.]]]]]

1491
            Case 2:
L
littletomatodonkey 已提交
1492 1493 1494 1495 1496 1497 1498
                pad = [2, 2, 1, 1, 0, 0],
                mode = 'reflect'
                Out = [[[[[6. 5. 4. 5. 6. 5. 4.]
                          [3. 2. 1. 2. 3. 2. 1.]
                          [6. 5. 4. 5. 6. 5. 4.]
                          [3. 2. 1. 2. 3. 2. 1.]]]]]

1499
            Case 3:
L
littletomatodonkey 已提交
1500 1501 1502 1503 1504 1505 1506
                pad = [2, 2, 1, 1, 0, 0],
                mode = 'replicate'
                Out = [[[[[1. 1. 1. 2. 3. 3. 3.]
                          [1. 1. 1. 2. 3. 3. 3.]
                          [4. 4. 4. 5. 6. 6. 6.]
                          [4. 4. 4. 5. 6. 6. 6.]]]]]

1507
            Case 4:
L
littletomatodonkey 已提交
1508 1509 1510 1511 1512 1513 1514
                pad = [2, 2, 1, 1, 0, 0],
                mode = 'circular'
                Out = [[[[[5. 6. 4. 5. 6. 4. 5.]
                          [2. 3. 1. 2. 3. 1. 2.]
                          [5. 6. 4. 5. 6. 4. 5.]
                          [2. 3. 1. 2. 3. 1. 2.]]]]]

1515
    Examples:
L
littletomatodonkey 已提交
1516
        .. code-block:: python
L
littletomatodonkey 已提交
1517

L
littletomatodonkey 已提交
1518 1519
            import paddle
            import paddle.nn.functional as F
1520

L
littletomatodonkey 已提交
1521 1522
            # example 1
            x_shape = (1, 1, 3)
1523
            x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
1524
            y = F.pad(x, [0, 0, 0, 0, 2, 3], value=1, mode='constant', data_format="NCL")
L
littletomatodonkey 已提交
1525
            print(y)
L
littletomatodonkey 已提交
1526
            # [[[1. 1. 1. 2. 3. 1. 1. 1.]]]
1527

L
littletomatodonkey 已提交
1528
            # example 2
1529
            x_shape = (1, 1, 3)
1530
            x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
1531 1532 1533
            y = F.pad(x, [2, 3], value=1, mode='constant', data_format="NCL")
            print(y)
            # [[[1. 1. 1. 2. 3. 1. 1. 1.]]]
1534

1535
            # example 3
L
littletomatodonkey 已提交
1536
            x_shape = (1, 1, 2, 3)
1537
            x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
L
littletomatodonkey 已提交
1538 1539
            y = F.pad(x, [1, 2, 1, 1], value=1, mode='circular')
            print(y)
L
littletomatodonkey 已提交
1540 1541 1542 1543 1544
            # [[[[6. 4. 5. 6. 4. 5.]
            #    [3. 1. 2. 3. 1. 2.]
            #    [6. 4. 5. 6. 4. 5.]
            #    [3. 1. 2. 3. 1. 2.]]]]
    """
1545 1546 1547 1548 1549 1550 1551 1552
    assert mode in [
        'reflect',
        'replicate',
        'constant',
        'circular',
    ], "mode should be one of constant, reflect, replicate, circular, but got {}.".format(
        mode
    )
L
littletomatodonkey 已提交
1553 1554

    data_format = data_format.upper()
1555 1556
    assert data_format in ["NCL", "NCHW", "NCDHW", "NLC", "NHWC", "NDHWC"], (
        "data_format should be in one of [NCL, NCHW, NCDHW, NLC, NHWC, NDHWC], "
L
littletomatodonkey 已提交
1557
        "but got {}".format(data_format)
1558
    )
L
littletomatodonkey 已提交
1559 1560 1561

    x_dim = len(x.shape)

1562 1563 1564 1565 1566
    if (
        mode == "constant"
        and isinstance(pad, (list, tuple))
        and len(pad) == x_dim * 2
    ):
1567 1568
        paddings = pad
        pad_value = value
1569

1570
        if in_dynamic_mode():
1571
            out = _C_ops.pad(x, paddings, float(pad_value))
1572 1573
            return out

1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
        check_variable_and_dtype(
            x,
            'x',
            [
                'float16',
                'float32',
                'float64',
                'int32',
                'int64',
                'complex64',
                'complex128',
1585
                'uint16',
1586 1587 1588
            ],
            "pad",
        )
1589

1590 1591 1592 1593
        check_type(pad_value, 'pad_value', (float, int, Variable), 'pad')
        if isinstance(pad_value, int):
            pad_value = float(pad_value)

1594 1595 1596
        helper = LayerHelper('pad', **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(dtype)
1597 1598 1599 1600 1601 1602
        helper.append_op(
            type='pad',
            inputs={'X': x},
            outputs={'Out': out},
            attrs={'paddings': paddings, 'pad_value': pad_value},
        )
1603
        return out
L
littletomatodonkey 已提交
1604

1605
    assert x_dim in [
1606 1607 1608
        3,
        4,
        5,
1609
    ], f"input tesor dimension must be in [3, 4, 5] but got {x_dim}"
1610 1611 1612 1613 1614 1615

    supported_format_map = {
        3: ["NCL", "NLC"],
        4: ["NCHW", "NHWC"],
        5: ["NCDHW", "NDHWC"],
    }
1616 1617 1618 1619 1620
    assert (
        data_format in supported_format_map[x_dim]
    ), "input tensor dimension is {}, it's data format should be in {} but got {}".format(
        x_dim, supported_format_map[x_dim], data_format
    )
1621

L
littletomatodonkey 已提交
1622 1623 1624 1625 1626 1627
    unsqueezed_dim = []

    if isinstance(pad, Variable):
        if data_format in ["NCL", "NCHW", "NCDHW"]:
            data_format = "NCDHW"
            if x_dim == 3:
1628
                pad = concat([zeros((4,), dtype="int32"), pad], axis=0)
L
littletomatodonkey 已提交
1629
                unsqueezed_dim = [3, 4]
1630
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1631
            elif x_dim == 4:
1632
                pad = concat([pad, zeros((2,), dtype="int32")], axis=0)
L
littletomatodonkey 已提交
1633
                unsqueezed_dim = [2]
1634
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1635 1636 1637
        elif data_format in ["NLC", "NHWC", "NDHWC"]:
            data_format = "NDHWC"
            if x_dim == 3:
1638
                pad = concat([zeros((4,), dtype="int32"), pad], axis=0)
L
littletomatodonkey 已提交
1639
                unsqueezed_dim = [2, 3]
1640
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1641
            elif x_dim == 4:
1642
                pad = concat([pad, zeros((2,), dtype="int32")], axis=0)
L
littletomatodonkey 已提交
1643
                unsqueezed_dim = [1]
1644
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1645
    else:
1646
        pad = list(pad)
L
littletomatodonkey 已提交
1647 1648 1649 1650 1651
        if data_format in ["NCL", "NCHW", "NCDHW"]:
            data_format = "NCDHW"
            if x_dim == 3:
                pad = [0, 0, 0, 0] + pad
                unsqueezed_dim = [3, 4]
1652
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1653 1654 1655
            elif x_dim == 4:
                pad = pad + [0, 0]
                unsqueezed_dim = [2]
1656
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1657 1658 1659 1660 1661
        elif data_format in ["NLC", "NHWC", "NDHWC"]:
            data_format = "NDHWC"
            if x_dim == 3:
                pad = [0, 0, 0, 0] + pad
                unsqueezed_dim = [2, 3]
1662
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1663 1664 1665
            elif x_dim == 4:
                pad = pad + [0, 0]
                unsqueezed_dim = [1]
1666
                x = unsqueeze(x, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1667

1668
    if in_dynamic_mode():
L
littletomatodonkey 已提交
1669
        if isinstance(pad, Variable):
1670
            pad = pad.tolist()
1671
        out = _C_ops.pad3d(x, pad, mode, value, data_format)
J
Jiabin Yang 已提交
1672
    else:
1673 1674 1675 1676 1677
        attrs = {'mode': mode, 'value': value, 'data_format': data_format}
        inputs = {'X': [x]}
        if isinstance(pad, Variable):
            inputs['Paddings'] = [pad]
            attrs['paddings'] = []
1678
        else:
1679
            attrs['paddings'] = pad
L
littletomatodonkey 已提交
1680

1681
        helper = LayerHelper('pad3d', **locals())
L
littletomatodonkey 已提交
1682

1683 1684 1685 1686 1687
        dtype = helper.input_dtype(input_param_name='input')
        out = helper.create_variable_for_type_inference(dtype)
        helper.append_op(
            type='pad3d', inputs=inputs, outputs={"Out": out}, attrs=attrs
        )
L
littletomatodonkey 已提交
1688 1689

    if len(unsqueezed_dim) != 0:
1690
        out = squeeze(out, axis=unsqueezed_dim)
L
littletomatodonkey 已提交
1691 1692 1693 1694

    return out


1695 1696 1697 1698 1699 1700 1701 1702 1703
def zeropad2d(x, padding, data_format="NCHW", name=None):
    """
    Pads the input tensor boundaries with zero according to 'pad'.

    Args:
        x(Tensor): The input tensor with data type float16/float32/float64/int32/int64.
        padding(int | Tensor | List[int] | Tuple[int]): The padding size with data type int.
            The input dimension should be 4 and pad has the form (pad_left, pad_right,
            pad_top, pad_bottom).
1704
        data_format(str, optional): An string from: "NHWC", "NCHW". Specify the data format of
1705 1706
            the input data. Default: "NCHW".
        name(str, optional): The default value is None. Normally there is no need for user
1707
            to set this property. For more information, please refer to :ref:`api_guide_Name`.
1708

1709
    Returns:
1710
        Tensor, padded with 0 according to pad and data type is same as input.
1711 1712 1713 1714 1715 1716

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
1717 1718
            x_shape = paddle.to_tensor([1, 1, 2, 3])
            x = paddle.arange(paddle.prod(x_shape), dtype="float32").reshape(x_shape) + 1
1719
            y = F.zeropad2d(x, [1, 2, 1, 1])
1720
            print(y)
1721 1722 1723 1724 1725 1726
            # [[[[0. 0. 0. 0. 0. 0.]
            #    [0. 1. 2. 3. 0. 0.]
            #    [0. 4. 5. 6. 0. 0.]
            #    [0. 0. 0. 0. 0. 0.]]]]
    """

1727 1728 1729 1730 1731 1732 1733 1734
    return pad(
        x,
        pad=padding,
        mode='constant',
        value=0,
        data_format=data_format,
        name=name,
    )
1735 1736


Y
Yang Zhang 已提交
1737
def cosine_similarity(x1, x2, axis=1, eps=1e-8):
L
littletomatodonkey 已提交
1738
    """
Y
Yang Zhang 已提交
1739
    Compute cosine similarity between x1 and x2 along axis.
L
littletomatodonkey 已提交
1740 1741 1742 1743

    Parameters:
        x1 (Tensor): First input. float32/double.
        x2 (Tensor): Second input. float32/double.
1744 1745
        axis (int, optional): Dimension of vectors to compute cosine similarity. Default is 1.
        eps(float, optional): Small value to avoid division by zero. Default is 1e-8.
1746 1747

    Returns:
1748
        Tensor, a Tensor representing cosine similarity between x1 and x2 along axis.
L
littletomatodonkey 已提交
1749 1750 1751

    Examples:
        .. code-block:: text
1752

L
littletomatodonkey 已提交
1753 1754 1755 1756 1757 1758 1759 1760 1761
            Case 0:
                x1 = [[0.8024077  0.9927354  0.27238318 0.8344984 ]
                     [0.48949873 0.5797396  0.65444374 0.66510963]
                     [0.1031398  0.9614342  0.08365563 0.6796464 ]
                     [0.10760343 0.7461209  0.7726148  0.5801006 ]]
                x2 = [[0.62913156 0.1536727  0.9847992  0.04591406]
                     [0.9098952  0.15715368 0.8671125  0.3156102 ]
                     [0.4427798  0.54136837 0.5276275  0.32394758]
                     [0.3769419  0.8535014  0.48041078 0.9256797 ]]
Y
Yang Zhang 已提交
1762
                axis = 1
L
littletomatodonkey 已提交
1763 1764 1765 1766 1767
                eps = 1e-8
                Out: [0.5275037  0.8368967  0.75037485 0.9245899]

    Code Examples:
        .. code-block:: python
1768

L
littletomatodonkey 已提交
1769 1770 1771
            import paddle
            import paddle.nn as nn

1772 1773 1774 1775
            paddle.seed(1)
            x1 = paddle.randn(shape=[2, 3])
            x2 = paddle.randn(shape=[2, 3])

Y
Yang Zhang 已提交
1776
            result = paddle.nn.functional.cosine_similarity(x1, x2, axis=0)
L
littletomatodonkey 已提交
1777
            print(result)
1778
            # [0.97689527,  0.99996042, -0.55138415]
1779

L
littletomatodonkey 已提交
1780
    """
1781 1782 1783
    w12 = sum(paddle.multiply(x1, x2), axis=axis)
    w1 = sum(paddle.multiply(x1, x1), axis=axis)
    w2 = sum(paddle.multiply(x2, x2), axis=axis)
Y
Yang Zhang 已提交
1784
    n12 = sqrt(clip(w1 * w2, min=eps * eps))
L
littletomatodonkey 已提交
1785 1786
    cos_sim = w12 / n12
    return cos_sim
1787 1788 1789


def linear(x, weight, bias=None, name=None):
1790
    r"""
1791

1792 1793
    Fully-connected linear transformation operator. For each input :math:`X` ,
    the equation is:
1794 1795 1796

    .. math::

1797
        Out = XW + b
1798

1799
    where :math:`W` is the weight and :math:`b` is the bias.
1800

1801 1802 1803 1804
    If the weight is a 2-D tensor of shape :math:`[in\_features, out\_features]` ,
    input should be a multi-dimensional tensor of shape
    :math:`[batch\_size, *, in\_features]` , where :math:`*` means any number of
    additional dimensions. The linear operator multiplies input tensor with
1805
    weight and produces an output tensor of shape :math:`[batch\_size, *, out\_features]` ,
1806 1807
    If :math:`bias` is not None, the bias should be a 1-D tensor of shape
    :math:`[out\_features]` and will be added to the output.
1808

1809
    Parameters:
1810
        x (Tensor): Input tensor. The data type should be bfloat16, float16, float32 or float64.
1811 1812 1813 1814 1815
        weight (Tensor): Weight tensor. The data type should be float16, float32 or float64.
        bias (Tensor, optional): Bias tensor. The data type should be float16, float32 or float64.
                                 If it is set to None, no bias will be added to the output units.
        name (str, optional): Normally there is no need for user to set this parameter.
                              For detailed information, please refer to :ref:`api_guide_Name` .
1816 1817

    Returns:
1818 1819
        Tensor, the shape is :math:`[batch\_size, *, out\_features]` and the
        data type is the same with input :math:`x` .
1820 1821 1822

    Examples:
        .. code-block:: python
1823

1824
          import paddle
1825

1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
          x = paddle.randn((3, 2), dtype="float32")
          # x: [[-0.32342386 -1.200079  ]
          #     [ 0.7979031  -0.90978354]
          #     [ 0.40597573  1.8095392 ]]
          weight = paddle.full(shape=[2, 4], fill_value="0.5", dtype="float32", name="weight")
          # weight: [[0.5 0.5 0.5 0.5]
          #          [0.5 0.5 0.5 0.5]]
          bias = paddle.ones(shape=[4], dtype="float32", name="bias")
          # bias: [1. 1. 1. 1.]
          y = paddle.nn.functional.linear(x, weight, bias)
          # y: [[0.23824859 0.23824859 0.23824859 0.23824859]
          #     [0.9440598  0.9440598  0.9440598  0.9440598 ]
          #     [2.1077576  2.1077576  2.1077576  2.1077576 ]]
1839
    """
1840
    if in_dynamic_mode():
1841
        # TODO(jiabin): using addmm for fast forward route
1842
        return _C_ops.linear(x, weight, bias)
1843
    else:
1844 1845
        helper = LayerHelper('linear', **locals())
        dtype = x.dtype
J
Jiabin Yang 已提交
1846

1847
        check_variable_and_dtype(
1848 1849 1850 1851 1852 1853 1854
            x, 'x', ["uint16", 'float16', 'float32', 'float64'], 'linear'
        )
        check_dtype(
            dtype,
            'dtype',
            ["uint16", 'float16', 'float32', 'float64'],
            'linear',
1855
        )
J
Jiabin Yang 已提交
1856

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
        inputs = {'X': [x], 'Y': [weight]}
        attrs = {'trans_x': False, 'trans_y': False}
        tmp = helper.create_variable_for_type_inference(dtype)
        helper.append_op(
            type='matmul_v2',
            inputs=inputs,
            outputs={'Out': tmp},
            attrs=attrs,
        )
        if bias is not None:
            res = helper.create_variable_for_type_inference(dtype)
1868
            helper.append_op(
1869 1870 1871
                type='elementwise_add',
                inputs={'X': [tmp], 'Y': [bias]},
                outputs={'Out': [res]},
J
Jiabin Yang 已提交
1872
                attrs={'axis': -1},
1873
            )
1874 1875 1876
        else:
            res = tmp
        return res
1877 1878


FormlessUnit's avatar
FormlessUnit 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
def quant_for_compress(x, bits=8, layout="weight_only"):
    return _C_ops.quant_for_compress(x, bits, layout)


def linear_compress(
    x,
    weight,
    weight_scale,
    bias=None,
    bits=8,
    algo="llm.int8",
    name=None,
    config=None,
):
    if in_dynamic_mode():
        if algo == "llm.int8":
FormlessUnit's avatar
FormlessUnit 已提交
1895
            y = _C_ops.llm_int8_matmul(
FormlessUnit's avatar
FormlessUnit 已提交
1896 1897 1898
                x, weight, weight_scale, config['threshold']
            )
        elif algo == "weight_only":
FormlessUnit's avatar
FormlessUnit 已提交
1899
            y = _C_ops.weight_only_matmul(x, weight, weight_scale)
FormlessUnit's avatar
FormlessUnit 已提交
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
        else:
            raise ValueError(
                "Unknown algo: '{}'. It can only be 'llm.int8' or 'weight_only'.".format(
                    algo
                )
            )
        if bias is not None:
            y = paddle.add(y, bias)
        return y
    else:
        helper = LayerHelper('linear_compress', **locals())
        dtype = x.dtype

        check_variable_and_dtype(x, 'x', ['float16'], 'linear_compress')
        check_dtype(dtype, 'dtype', ['float16'], 'linear_compress')

        if algo == "llm.int8":
            type = "llm_int8_matmul"
FormlessUnit's avatar
FormlessUnit 已提交
1918 1919 1920 1921 1922
            inputs = {
                'x': [x],
                'weight': [weight],
                'weight_scale': [weight_scale],
            }
FormlessUnit's avatar
FormlessUnit 已提交
1923 1924 1925
            attrs = {'algo': algo, 'threshold': config['threshold']}
        elif algo == "weight_only":
            type = "weight_only_matmul"
FormlessUnit's avatar
FormlessUnit 已提交
1926 1927 1928 1929 1930
            inputs = {
                'x': [x],
                'weight': [weight],
                'weight_scale': [weight_scale],
            }
FormlessUnit's avatar
FormlessUnit 已提交
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
            attrs = {}
        else:
            raise ValueError(
                "Unknown algo: '{}'. It can only be 'llm.int8' or 'weight_only'.".format(
                    algo
                )
            )
        tmp = helper.create_variable_for_type_inference(dtype)

        helper.append_op(
            type=type,
            inputs=inputs,
            outputs={'Out': tmp},
            attrs=attrs,
        )
        if bias is not None:
            res = helper.create_variable_for_type_inference(dtype)
            helper.append_op(
                type='elementwise_add',
                inputs={'X': [tmp], 'Y': [bias]},
                outputs={'Out': [res]},
                attrs={'axis': -1},
            )
        else:
            res = tmp
        return res


1959
def label_smooth(label, prior_dist=None, epsilon=0.1, name=None):
1960
    r"""
1961
    Label smoothing is a mechanism to regularize the classifier layer and is called
1962 1963 1964 1965
    label-smoothing regularization (LSR).Label smoothing is proposed to encourage
    the model to be less confident, since optimizing the log-likelihood of the
    correct label directly may cause overfitting and reduce the ability of the
    model to adapt.
1966

1967
    Label smoothing replaces the ground-truth label :math:`y` with the weighted sum
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    of itself and some fixed distribution :math:`\mu`. For class :math:`k`,
    i.e.

    .. math::

        \\tilde{y_k} = (1 - \epsilon) * y_k + \epsilon * \mu_k,

    where :math:`1 - \epsilon` and :math:`\epsilon` are the weights
    respectively, and :math:`\\tilde{y}_k` is the smoothed label. Usually
    uniform distribution is used for :math:`\mu`.

    See more details about label smoothing in https://arxiv.org/abs/1512.00567.

    Parameters:
        label(Tensor): The input variable containing the label data. The
                        label data should use one-hot representation. It's
                        a multidimensional tensor with a shape of
1985
                        :math:`[N_1, ..., Depth]`, where Depth is class number. The dtype can be "float16" "float32" and "float64".
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
        prior_dist(Tensor, optional): The prior distribution to be used to smooth
                        labels. If not provided, an uniform distribution
                        is used. It's a multidimensional tensor with a shape of
                        :math:`[1, class\_num]` . The default value is None.
        epsilon(float, optional): The weight used to mix up the original ground-truth
                        distribution and the fixed distribution. The default value is
                        0.1.
        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:
        Tensor: The tensor containing the smoothed labels.

    Examples:
        .. code-block:: python

            import paddle
            paddle.disable_static()
2005 2006 2007 2008

            x = paddle.to_tensor([[[0, 1, 0],
                                [ 1,  0, 1]]], dtype="float32", stop_gradient=False)

2009
            output = paddle.nn.functional.label_smooth(x)
2010
            print(output)
2011 2012 2013
            # Tensor(shape=[1, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False,
            #        [[[0.03333334, 0.93333334, 0.03333334],
            #          [0.93333334, 0.03333334, 0.93333334]]])
2014
    """
2015
    if epsilon > 1.0 or epsilon < 0.0:
2016 2017
        raise ValueError("The value of epsilon must be between 0 and 1.")

2018
    if in_dynamic_mode():
2019
        return _C_ops.label_smooth(label, prior_dist, float(epsilon))
2020

2021
    check_variable_and_dtype(
2022 2023 2024 2025
        label,
        'label',
        ['uint16', 'float16', 'float32', 'float64'],
        'label_smooth',
2026
    )
2027 2028 2029 2030

    helper = LayerHelper("label_smooth", **locals())
    label.stop_gradient = True
    smooth_label = helper.create_variable_for_type_inference(label.dtype)
2031 2032 2033 2034 2035 2036 2037 2038
    helper.append_op(
        type="label_smooth",
        inputs={"X": label, "PriorDist": prior_dist}
        if prior_dist
        else {"X": label},
        outputs={"Out": smooth_label},
        attrs={"epsilon": float(epsilon)},
    )
2039
    return smooth_label
2040 2041


G
Guoxia Wang 已提交
2042
def class_center_sample(label, num_classes, num_samples, group=None):
2043 2044
    """
    Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers.
2045
    The process of sampling subset class centers is straightforward:
2046 2047 2048 2049

    1. First select the positive class centers;
    2. Then randomly sample negative class centers.

2050
    Specifically, given a label tensor, shape [batch_size], select all the positive class centers and randomly
2051 2052 2053 2054
    sample negative class centers, then remap the input label tensor using the sampled class centers.

    For more information, Partial FC: Training 10 Million Identities on a Single Machine
    arxiv: https://arxiv.org/abs/2010.05222
2055

V
Vegetable dog 已提交
2056
    Note:
2057
        If the number of the positive class centers is greater than the input num_samples, it keeps all the positive
2058
        class centers and the shape of sampled_class_center will be [num_positive_class_centers].
2059

2060 2061
        The API supports CPU, single GPU and multi GPU.

2062 2063 2064 2065
        For data parallel mode, set ``group=False``.

        For model parallel mode, set ``group=None`` or the group instance return by paddle.distributed.new_group.

2066
    Args:
G
Guoxia Wang 已提交
2067 2068
        label (Tensor): 1-D tensor with shape [N], each label in [0, num_classes)
        num_classes (int): A positive integer to specify the number of classes at local rank.
2069
            Note that num_classes of each GPU can be different.
G
Guoxia Wang 已提交
2070
        num_samples (int): A positive integer to specify the number of class center to sample.
2071
        group (Group, optional): The group instance return by paddle.distributed.new_group
2072 2073
            or ``None`` for global default group or ``False`` for data parallel (do not communication cross ranks).
            Default is ``None``.
2074 2075 2076 2077 2078 2079 2080 2081

    Returns:
        Tuple of two ``Tensor`` : (remapped_label, sampled_class_center), remapped label using sampled class center,
        sampled class center from [0, num_classes).

    Examples:

    .. code-block:: python
G
Guoxia Wang 已提交
2082
        :name: code-example1
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104

        # CPU or single GPU
        import paddle
        num_classes = 20
        batch_size = 10
        num_samples = 6
        label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64')
        remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes, num_samples)

        print(label)
        print(remapped_label)
        print(sampled_class_index)

        # the output is
        #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True,
        #       [11, 5 , 1 , 3 , 12, 2 , 15, 19, 18, 19])
        #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True,
        #       [4, 3, 0, 2, 5, 1, 6, 8, 7, 8])
        #Tensor(shape=[9], dtype=int64, place=CPUPlace, stop_gradient=True,
        #       [1 , 2 , 3 , 5 , 11, 12, 15, 18, 19])

    .. code-block:: python
G
Guoxia Wang 已提交
2105
        :name: code-example2
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136

        # required: distributed
        # Multi GPU, test_class_center_sample.py
        import paddle
        import paddle.distributed as dist
        strategy = dist.fleet.DistributedStrategy()
        dist.fleet.init(is_collective=True, strategy=strategy)
        batch_size = 10
        num_samples = 6
        rank_id = dist.get_rank()
        # num_classes of each GPU can be different, e.g num_classes_list = [10, 8]
        num_classes_list = [10, 10]
        num_classes = paddle.sum(paddle.to_tensor(num_classes_list))
        label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64')
        label_list = []
        dist.all_gather(label_list, label)
        label = paddle.concat(label_list, axis=0)
        remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes_list[rank_id], num_samples)

        print(label)
        print(remapped_label)
        print(sampled_class_index)

        #python -m paddle.distributed.launch --gpus=0,1 test_class_center_sample.py
        # rank 0 output:
        #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
        #       [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ])
        #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
        #       [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ])
        #Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
        #       [0, 2, 4, 8, 9, 3])
2137

2138 2139 2140 2141 2142 2143 2144 2145
        # rank 1 output:
        #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
        #       [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ])
        #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
        #       [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ])
        #Tensor(shape=[7], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
        #       [0, 1, 2, 3, 5, 7, 8])
    """
2146
    if not (group is False or group is None or hasattr(group, 'is_member')):
2147 2148
        raise ValueError(
            'Expected group is False, None or instance of paddle.distributed.collective.Group \
2149 2150 2151 2152
             (got group: {})'.format(
                group
            )
        )
2153 2154 2155
        return

    if hasattr(group, 'is_member') and not group.is_member():
2156 2157
        return

2158
    ring_id = 0
2159 2160
    rank = 0
    nranks = 1
2161
    if group is not False:
2162 2163 2164
        if core.is_compiled_with_dist():
            parallel_env = paddle.distributed.ParallelEnv()
            global_rank = parallel_env.rank
2165 2166 2167 2168 2169
            rank = (
                global_rank
                if group is None
                else group.get_group_rank(global_rank)
            )
2170
            nranks = parallel_env.world_size if group is None else group.nranks
2171 2172 2173

    if num_samples > num_classes:
        raise ValueError(
2174 2175 2176 2177
            'Expected num_samples less than or equal to {}, got num_samples {}'.format(
                num_classes, num_samples
            )
        )
2178

G
Guoxia Wang 已提交
2179 2180 2181
    label_size = 1
    for dim in list(label.shape):
        label_size *= dim
2182
    if label_size != -1 and label_size < 1:
2183 2184 2185 2186 2187 2188
        raise ValueError(
            'Expected label_size > 0 \
             (got label_size: {})'.format(
                label_size
            )
        )
G
Guoxia Wang 已提交
2189 2190 2191

    label_dims = len(list(label.shape))
    if label_dims != 1:
2192 2193 2194 2195 2196 2197
        raise ValueError(
            'Expected label_dims == 1 \
             (got label_dims: {})'.format(
                label_dims
            )
        )
G
Guoxia Wang 已提交
2198 2199

    seed = None
2200 2201 2202
    if (seed is None or seed == 0) and default_main_program().random_seed != 0:
        seed = default_main_program().random_seed

2203
    if in_dynamic_mode():
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
        return _C_ops.class_center_sample(
            label,
            num_classes,
            num_samples,
            ring_id,
            rank,
            nranks,
            seed is not None,
            seed if seed is not None else 0,
        )
2214

2215 2216 2217
    check_variable_and_dtype(
        label, 'label', ['int64', 'int32'], 'class_center_sample'
    )
2218 2219 2220
    op_type = 'class_center_sample'
    helper = LayerHelper(op_type, **locals())
    remapped_label = helper.create_variable_for_type_inference(
2221 2222
        dtype=label.dtype
    )
2223
    sampled_class_center = helper.create_variable_for_type_inference(
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
        dtype=label.dtype
    )
    helper.append_op(
        type=op_type,
        inputs={'Label': label},
        outputs={
            'RemappedLabel': remapped_label,
            'SampledLocalClassCenter': sampled_class_center,
        },
        attrs={
            'num_classes': num_classes,
            'num_samples': num_samples,
            'ring_id': ring_id,
            'nranks': nranks,
            'rank': rank,
            'fix_seed': seed is not None,
            'seed': seed if seed is not None else 0,
        },
    )
2243
    return remapped_label, sampled_class_center
X
xiaoting 已提交
2244 2245


2246 2247 2248
def fold(
    x, output_sizes, kernel_sizes, strides=1, paddings=0, dilations=1, name=None
):
X
xiaoting 已提交
2249
    r"""
2250

2251
    Combines an array of sliding local blocks into a large containing
2252 2253
    tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each
    combined value in the resulting large tensor by summing all values from all containing blocks.
X
xiaoting 已提交
2254 2255 2256 2257 2258 2259


    For each input :math:`x` with shape [N, C_in , L], the output shape [N, C_out, H_out, W_out]
    can be calculated as following.

    .. math::
2260

2261 2262 2263
        H_{out} &= output\_size[0] \\
        W_{out} &= output\_size[1] \\
        C_{out} &= \frac{C_{in}}{kernel\_sizes[0]\times kernel\_sizes[1]} \\
X
xiaoting 已提交
2264 2265 2266 2267

    Parameters:
        x(Tensor):                3-D Tensor, input tensor of format [N, C, L],
                                  data type can be float32 or float64
X
xiaoting 已提交
2268
        output_sizes(int|list|tuple):       The size of output size, should be [output_size_h, output_size_w]
X
xiaoting 已提交
2269
                                  or an interger o treated as [o, o].
X
xiaoting 已提交
2270
        kernel_sizes(int|list|tuple):   The size of convolution kernel, should be [k_h, k_w]
X
xiaoting 已提交
2271
                                  or an integer k treated as [k, k].
2272
        strides(int|list|tuple, optional):        The strides, should be [stride_h, stride_w]
X
xiaoting 已提交
2273 2274
                                  or an integer stride treated as [sride, stride].
                                  For default, strides will be [1, 1].
2275
        paddings(int|list|tuple, optional):       The paddings of each dimension, should be
X
xiaoting 已提交
2276 2277 2278 2279 2280 2281
                                  [padding_top, padding_left, padding_bottom, padding_right]
                                  or [padding_h, padding_w] or an integer padding.
                                  If [padding_h, padding_w] was given, it will expanded to
                                  [padding_h, padding_w, padding_h, padding_w]. If an integer
                                  padding was given, [padding, padding, padding, padding] will
                                  be used. For default, paddings will be [0, 0, 0, 0]
2282
        dilations(int|list|tuple, optional):      the dilations of convolution kernel, should be
X
xiaoting 已提交
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
                                  [dilation_h, dilation_w], or an integer dilation treated as
                                  [dilation, dilation]. For default, it will be [1, 1].
        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:
        The tensor formed by combining a group of sliding local blocks
        The output shape is [N, Cout, H, W] as decriabled above.

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn.functional as F

X
xiaoting 已提交
2301 2302 2303
            x = paddle.randn([2,3*2*2,12])
            y = F.fold(x, output_sizes=[4, 5], kernel_sizes=2)
            # y.shape = [2,3,4,5]
X
xiaoting 已提交
2304 2305

    """
2306 2307 2308 2309 2310

    helper = LayerHelper("fold", **locals())

    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'fold')

2311
    assert len(x.shape) == 3, "input should be the format of [N, C, L]"
X
xiaoting 已提交
2312

X
xiaoting 已提交
2313
    def _is_list_or_turple_(data):
2314
        return isinstance(data, (list, tuple))
X
xiaoting 已提交
2315

X
xiaoting 已提交
2316 2317 2318
    if isinstance(output_sizes, int):
        output_sizes = [output_sizes, output_sizes]
    else:
2319 2320 2321
        assert _is_list_or_turple_(output_sizes) and (
            len(output_sizes) == 2
        ), "output_sizes should either be an integer or a list/tuple of two integers"
X
xiaoting 已提交
2322 2323 2324 2325

    if isinstance(kernel_sizes, int):
        kernel_sizes = [kernel_sizes, kernel_sizes]
    else:
2326 2327 2328
        assert _is_list_or_turple_(kernel_sizes) and (
            len(kernel_sizes) == 2
        ), "kernel_sizes should either be an integer or a list/tuple of two integers"
X
xiaoting 已提交
2329 2330 2331 2332

    if isinstance(strides, int):
        strides = [strides, strides]
    else:
2333 2334 2335
        assert _is_list_or_turple_(strides) and (
            len(strides) == 2
        ), "strides should either be an integer or a list/tuple of two integers"
X
xiaoting 已提交
2336 2337 2338 2339

    if isinstance(dilations, int):
        dilations = [dilations, dilations]
    else:
2340 2341 2342
        assert _is_list_or_turple_(dilations) and (
            len(dilations) == 2
        ), "dilations should either be an integer or a list/tuple of two integers"
X
xiaoting 已提交
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357

    if isinstance(paddings, int):
        paddings = [paddings] * 4
    elif isinstance(paddings, list):
        if len(paddings) == 2:
            paddings = paddings * 2
        elif len(paddings) == 4:
            pass
        else:
            raise ValueError(
                "paddings should either be an integer or a list of 2 or 4 integers"
            )
    else:
        raise ValueError(
            "Unexpected type of paddings, it should be either an integer or a list"
2358 2359
            "of 2 or 4 integers"
        )
X
xiaoting 已提交
2360

2361
    if in_dynamic_mode():
2362 2363 2364
        out = _C_ops.fold(
            x, output_sizes, kernel_sizes, strides, paddings, dilations
        )
X
xiaoting 已提交
2365 2366
    else:
        out = helper.create_variable_for_type_inference(dtype=x.dtype)
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
        helper.append_op(
            type="fold",
            inputs={"X": x},
            outputs={"Y": out},
            attrs={
                "output_sizes": output_sizes,
                "kernel_sizes": kernel_sizes,
                "strides": strides,
                "paddings": paddings,
                "dilations": dilations,
            },
        )
X
xiaoting 已提交
2379
    return out