pooling.py 85.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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.

# TODO: define pooling functions
16 17
from ...fluid.layers import utils, LayerHelper
from ...tensor.manipulation import unsqueeze, squeeze
18
from ...fluid.data_feeder import check_type, check_variable_and_dtype
19
from paddle import _C_ops, _legacy_C_ops
Z
zhiboniu 已提交
20
from paddle import in_dynamic_mode
21 22 23
from paddle.fluid import core
from paddle.fluid.framework import _in_legacy_dygraph, Variable
from paddle.fluid.framework import in_dygraph_mode, _non_static_mode
24

25 26
__all__ = []

27

28 29 30 31 32
def _is_list_or_tuple(input):
    return isinstance(input, (list, tuple))


def _check_input(x, dimension):
33
    if len(x.shape) != dimension:
34 35
        raise ValueError(
            "Excepted Input X is {}-D tensor, but received {}-D {}".format(
L
Ligoml 已提交
36 37 38
                dimension, len(x.shape), type(x)
            )
        )
39 40


41
def _check_instance(x, x_name, types=(int, float)):
42 43

    if not isinstance(x, types):
44 45
        raise ValueError(
            "Excepted {} type for {} but received type: {}. ".format(
L
Ligoml 已提交
46 47 48
                types, x_name, type(x)
            )
        )
49 50


D
Double_V 已提交
51 52 53 54
def _check_value_limitation(x, x_name, min_limit=1e-3):
    def _check_value(x, x_name, min_limit=1e-3):
        if isinstance(x, int) and min_limit is not None and x < min_limit:
            raise ValueError(
L
Ligoml 已提交
55 56 57 58
                "Excepted the input {} to be greater than {} but received x: {}. ".format(
                    x_name, min_limit, x
                )
            )
D
Double_V 已提交
59 60 61 62 63

    for ele in x:
        _check_value(ele, x_name)


64 65 66
def _zero_padding_in_batch_and_channel(padding, channel_last):
    if channel_last:
        return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0]
67
    else:
68
        return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0]
69 70


71 72 73 74
def _exclude_padding_in_batch_and_channel(padding, channel_last):
    padding_ = padding[1:-1] if channel_last else padding[2:]
    padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim]
    return padding_
75 76


77 78 79 80 81
def _channel_last(data_format, num_dims):
    if num_dims == 1:
        if data_format not in ['NCL', 'NLC']:
            raise ValueError(
                "Attr(data_format) should be 'NCL' or 'NLC'. Received "
L
Ligoml 已提交
82 83
                "Attr(data_format): %s" % str(data_format)
            )
84 85 86 87 88 89
        else:
            return True if data_format == "NLC" else False
    if num_dims == 2:
        if data_format not in ['NCHW', 'NHWC']:
            raise ValueError(
                "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
L
Ligoml 已提交
90 91
                "Attr(data_format): %s" % str(data_format)
            )
92 93 94 95 96 97
        else:
            return True if data_format == "NHWC" else False
    if num_dims == 3:
        if data_format not in ['NCDHW', 'NDHWC']:
            raise ValueError(
                "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
L
Ligoml 已提交
98 99
                "Attr(data_format): %s" % str(data_format)
            )
100 101
        else:
            return True if data_format == "NDHWC" else False
102 103


104 105 106 107 108
def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False):
    if isinstance(padding, str):
        padding = padding.upper()
        if padding not in ["SAME", "VALID"]:
            raise ValueError(
L
Ligoml 已提交
109 110 111 112
                "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.".format(
                    padding
                )
            )
113 114
        if padding == "VALID":
            if ceil_mode != False:
115
                raise ValueError(
116
                    "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. "
L
Ligoml 已提交
117 118
                    "Received ceil_mode: True."
                )
119 120 121 122 123 124 125 126 127 128 129 130

            padding_algorithm = "VALID"
            padding = [0] * num_dims
        else:
            padding_algorithm = "SAME"
            padding = [0] * num_dims
    elif _is_list_or_tuple(padding):
        # for padding like
        # [(pad_before, pad_after), (pad_before, pad_after), ...]
        # padding for batch_dim and channel_dim included
        if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]):
            if not _zero_padding_in_batch_and_channel(padding, channel_last):
131
                raise ValueError(
132
                    "Non-zero padding({}) in the batch or channel dimensions "
L
Ligoml 已提交
133 134
                    "is not supported.".format(padding)
                )
135
            padding_algorithm = "EXPLICIT"
136
            padding = _exclude_padding_in_batch_and_channel(
L
Ligoml 已提交
137 138
                padding, channel_last
            )
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
            if utils._is_symmetric_padding(padding, num_dims):
                padding = padding[0::2]
        # for padding like [pad_before, pad_after, pad_before, pad_after, ...]
        elif len(padding) == 2 * num_dims and isinstance(padding[0], int):
            padding_algorithm = "EXPLICIT"
            padding = utils.convert_to_list(padding, 2 * num_dims, 'padding')
            if utils._is_symmetric_padding(padding, num_dims):
                padding = padding[0::2]
        # for padding like [pad_d1, pad_d2, ...]
        elif len(padding) == num_dims and isinstance(padding[0], int):
            padding_algorithm = "EXPLICIT"
            padding = utils.convert_to_list(padding, num_dims, 'padding')
        else:
            raise ValueError("Invalid padding: {}".format(padding))
    # for integer padding
154
    else:
155 156 157 158
        padding_algorithm = "EXPLICIT"
        padding = utils.convert_to_list(padding, num_dims, 'padding')
    return padding, padding_algorithm

159

160
def _expand_low_nd_padding(padding):
L
Ligoml 已提交
161
    # 1d to 2d fake input
162 163 164 165 166 167
    if len(padding) == 2:
        padding = [0] * 2 + padding
    elif len(padding) == 1:
        padding = [0] + padding
    else:
        raise ValueError(
L
Ligoml 已提交
168 169 170 171
            "The size of padding's dimmention should be 1 or 2. But got padding={}".format(
                padding
            )
        )
172 173 174
    return padding


L
Ligoml 已提交
175 176 177 178 179 180 181 182 183
def avg_pool1d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    exclusive=True,
    ceil_mode=False,
    name=None,
):
D
Double_V 已提交
184
    """
185 186
    This API implements average pooling 1d operation,
    See more details in :ref:`api_nn_pooling_AvgPool1d` .
187 188 189 190

    Args:
        x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
                          shape [N, C, L]. where `N` is batch size, `C` is the number of channels,
191
                          `L` is the length of the feature. The data type is float32 or float64.
192
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
193
            it must contain an integer.
194
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
195 196 197 198 199 200 201 202
            it must contain an integer.
        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
            4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after].
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
203
        exclusive (bool): Whether to exclude padding points in average pooling
204
                          mode, default is `True`.
205
        ceil_mode (bool): ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width.
206
            If it is set to False, the floor function will be used. The default value is False.
207 208 209 210 211 212 213 214
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.

    Examples:
        .. code-block:: python
L
Ligoml 已提交
215

C
Chen Long 已提交
216
            import paddle
217
            import paddle.nn as nn
C
Chen Long 已提交
218

219 220 221 222
            data = paddle.uniform([1, 3, 32], paddle.float32)
            AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0)
            pool_out = AvgPool1D(data)
            # pool_out shape: [1, 3, 16]
223 224 225
    """
    """NCL to NCHW"""
    data_format = "NCHW"
Z
zhiboniu 已提交
226
    if not in_dynamic_mode():
227
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool1d')
228
    _check_input(x, 3)
229
    x = unsqueeze(x, [2])
230
    kernel_size = utils.convert_to_list(kernel_size, 1, 'kernel_size')
231 232 233 234 235 236 237
    kernel_size = [1] + kernel_size
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 1, 'pool_stride')
        stride = [1] + stride

D
Double_V 已提交
238 239 240
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

241
    channel_last = _channel_last("NCL", 1)
L
Ligoml 已提交
242 243 244
    padding, padding_algorithm = _update_padding_nd(
        padding, 1, channel_last=channel_last, ceil_mode=ceil_mode
    )
245

246 247
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)
248

249
    if in_dygraph_mode():
L
Ligoml 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263
        output = _C_ops.pool2d(
            x,
            kernel_size,
            stride,
            padding,
            ceil_mode,
            exclusive,
            data_format,
            'avg',
            False,
            False,
            padding_algorithm,
            True,
        )
264 265 266
        return squeeze(output, [2])

    if _in_legacy_dygraph():
L
Ligoml 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        output = _legacy_C_ops.pool2d(
            x,
            'pooling_type',
            'avg',
            'ksize',
            kernel_size,
            'global_pooling',
            False,
            'strides',
            stride,
            'paddings',
            padding,
            'padding_algorithm',
            padding_algorithm,
            'use_cudnn',
            True,
            'ceil_mode',
            ceil_mode,
            'use_mkldnn',
            False,
            'exclusive',
            exclusive,
            'data_format',
            data_format,
        )
292 293 294 295
        return squeeze(output, [2])

    op_type = 'pool2d'
    helper = LayerHelper(op_type, **locals())
296
    dtype = helper.input_dtype(input_param_name='x')
297 298
    pool_out = helper.create_variable_for_type_inference(dtype)

L
Ligoml 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    helper.append_op(
        type=op_type,
        inputs={"X": x},
        outputs={"Out": pool_out},
        attrs={
            "pooling_type": 'avg',
            "ksize": kernel_size,
            "global_pooling": False,
            "strides": stride,
            "paddings": padding,
            "padding_algorithm": padding_algorithm,
            "use_cudnn": True,
            "ceil_mode": ceil_mode,
            "use_mkldnn": False,
            "exclusive": exclusive,
            "data_format": data_format,
        },
    )
317 318 319 320

    return squeeze(pool_out, [2])


L
Ligoml 已提交
321 322 323 324 325 326 327 328 329 330 331
def avg_pool2d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    ceil_mode=False,
    exclusive=True,
    divisor_override=None,
    data_format="NCHW",
    name=None,
):
332
    """
333 334
    This API implements average pooling 2d operation.
    See more details in :ref:`api_nn_pooling_AvgPool2d` .
D
Double_V 已提交
335

336
    Args:
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        x (Tensor): The input tensor of pooling operator which is a 4-D tensor with
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"` or
                          `"NHWC"`, where `N` is batch size, `C` is the number of channels,
                          `H` is the height of the feature, and `W` is the width of the
                          feature. The data type if float32 or float64.
        kernel_size (int|list|tuple): The pool kernel size. If it is a tuple or list,
            it must contain two integers, (kernel_size_Height, kernel_size_Width).
            Otherwise, the pool kernel size will be a square of an int.
        stride (int|list|tuple): The stride size. If it is a tuple or list,
            it must contain two integers, (stride_Height, stride_Width).
            Otherwise, the stride size will be a square of an int.

        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
        ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape
357
        exclusive (bool): Whether to exclude padding points in average pooling
358 359 360 361 362
                          mode, default is `true`.
        divisor_override (float): if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
        data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`.
                        The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_height, input_width]`.
363 364 365
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
L
Ligoml 已提交
366

367 368
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
L
Ligoml 已提交
369

370 371
    Examples:
        .. code-block:: python
L
Ligoml 已提交
372

C
Chen Long 已提交
373 374
            import paddle
            import paddle.nn.functional as F
L
Ligoml 已提交
375

C
Chen Long 已提交
376
            # avg pool2d
377
            x = paddle.uniform([1, 3, 32, 32], paddle.float32)
C
Chen Long 已提交
378 379 380 381
            out = F.avg_pool2d(x,
                            kernel_size=2,
                            stride=2, padding=0)
            # out.shape [1, 3, 16, 16]
382
    """
383
    kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size')
384 385 386
    if stride is None:
        stride = kernel_size
    else:
387
        stride = utils.convert_to_list(stride, 2, 'pool_stride')
388

D
Double_V 已提交
389 390 391
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

392
    channel_last = _channel_last(data_format, 2)
L
Ligoml 已提交
393 394 395
    padding, padding_algorithm = _update_padding_nd(
        padding, 2, channel_last, ceil_mode=ceil_mode
    )
396

397
    if _non_static_mode():
F
From00 已提交
398
        if in_dygraph_mode():
L
Ligoml 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412
            output = _C_ops.pool2d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                exclusive,
                data_format,
                'avg',
                False,
                False,
                padding_algorithm,
                True,
            )
F
From00 已提交
413
        else:
414
            output = _legacy_C_ops.pool2d(
L
Ligoml 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
                x,
                'pooling_type',
                'avg',
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'padding_algorithm',
                padding_algorithm,
                'strides',
                stride,
                'paddings',
                padding,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                exclusive,
                'data_format',
                data_format,
            )
439 440 441 442 443
        if divisor_override is None:
            return output
        else:
            _check_instance(divisor_override, "divisor_override")
            return output * (kernel_size[0] * kernel_size[1]) / divisor_override
444

445
    op_type = 'pool2d'
446
    helper = LayerHelper(op_type, **locals())
447
    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool2d')
448
    dtype = helper.input_dtype(input_param_name='x')
449 450
    pool_out = helper.create_variable_for_type_inference(dtype)

L
Ligoml 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    helper.append_op(
        type=op_type,
        inputs={"X": x},
        outputs={"Out": pool_out},
        attrs={
            "pooling_type": "avg",
            "ksize": kernel_size,
            "global_pooling": False,
            "strides": stride,
            "paddings": padding,
            "padding_algorithm": padding_algorithm,
            "use_cudnn": True,
            "ceil_mode": ceil_mode,
            "use_mkldnn": False,
            "exclusive": exclusive,
            "data_format": data_format,
        },
    )
469

470 471 472 473 474
    if divisor_override is None:
        return pool_out
    else:
        _check_instance(divisor_override, "divisor_override")
        return pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override
475 476


L
Ligoml 已提交
477 478 479 480 481 482 483 484 485 486 487
def avg_pool3d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    ceil_mode=False,
    exclusive=True,
    divisor_override=None,
    data_format="NCDHW",
    name=None,
):
488
    """
489 490
    This API implements average pooling 3d operation.
    See more details in :ref:`api_nn_pooling_AvgPool3d` .
491 492

    Args:
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
                          shape [N, C, D, H, W], where `N` represents the batch size, `C` represents
                          the number of channels, `D`, `H` and `W` represent the depth, height and width of the feature respectively.
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size
            is a tuple or list, it must contain three integers,
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
            Otherwise, the pool kernel size will be the cube of an int.
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
            it must contain three integers, [stride_Depth, stride_Height, stride_Width).
            Otherwise, the pool stride size will be a cube of an int.
        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
        ceil_mode (bool): ${ceil_mode_comment}
511
        exclusive (bool): Whether to exclude padding points in average pooling
512 513 514 515 516
                          mode, default is True.
        divisor_override (int|float) if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
        data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`.
                        The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_depth, input_height, input_width]`.
517
        name(str, optional): For detailed information, please refer
518 519
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
L
Ligoml 已提交
520

521
    Returns:
522
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
523

524 525
    Examples:
        .. code-block:: python
L
Ligoml 已提交
526

527
          import paddle
C
Chen Long 已提交
528

529
          x = paddle.uniform([1, 3, 32, 32, 32], paddle.float32)
530 531 532 533 534 535 536
          # avg pool3d
          out = paddle.nn.functional.avg_pool3d(
                                            x,
                                            kernel_size = 2,
                                            stride = 2,
                                            padding=0)
          # out.shape: [1, 3, 16, 16, 16]
537
    """
538 539 540 541 542
    kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size')
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 3, 'pool_stride')
543

544
    channel_last = _channel_last(data_format, 3)
L
Ligoml 已提交
545 546 547
    padding, padding_algorithm = _update_padding_nd(
        padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
    )
548

D
Double_V 已提交
549 550 551
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

552
    if in_dygraph_mode():
L
Ligoml 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566
        pool_out = _C_ops.pool3d(
            x,
            kernel_size,
            stride,
            padding,
            ceil_mode,
            exclusive,
            data_format,
            'avg',
            False,
            False,
            padding_algorithm,
            True,
        )
567 568
    elif _in_legacy_dygraph():
        pool_out = _legacy_C_ops.pool3d(
L
Ligoml 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            x,
            'pooling_type',
            'avg',
            'ksize',
            kernel_size,
            'strides',
            stride,
            'paddings',
            padding,
            'global_pooling',
            False,
            'padding_algorithm',
            padding_algorithm,
            'use_cudnn',
            True,
            'ceil_mode',
            ceil_mode,
            'use_mkldnn',
            False,
            'exclusive',
            exclusive,
            'data_format',
            data_format,
        )
593 594 595 596 597 598 599 600
    else:
        op_type = "pool3d"
        helper = LayerHelper(op_type, **locals())
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d')
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
        outputs = {"Out": pool_out}

L
Ligoml 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
        helper.append_op(
            type=op_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
                "pooling_type": 'avg',
                "ksize": kernel_size,
                "global_pooling": False,
                "strides": stride,
                "paddings": padding,
                "padding_algorithm": padding_algorithm,
                "use_cudnn": True,
                "ceil_mode": ceil_mode,
                "use_mkldnn": False,
                "exclusive": exclusive,
                "data_format": data_format,
            },
        )
619

620 621 622 623
    if divisor_override is None:
        return pool_out
    else:
        _check_instance(divisor_override, "divisor_override")
L
Ligoml 已提交
624 625 626 627 628
        return (
            pool_out
            * (kernel_size[0] * kernel_size[1] * kernel_size[2])
            / divisor_override
        )
629 630


L
Ligoml 已提交
631 632 633 634 635 636 637 638 639
def max_pool1d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    name=None,
):
640
    """
641 642
    This API implements max pooling 1d opereation.
    See more details in :ref:`api_nn_pooling_MaxPool1d` .
643 644

    Args:
645 646 647
        x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
                          shape [N, C, L], where `N` is batch size, `C` is the number of channels,
                          `L` is the length of the feature. The data type if float32 or float64.
648
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
649
            it must contain an integer.
650
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
651 652 653 654 655 656 657 658
            it must contain an integer.
        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An integer, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
            4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after].
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
659
        return_mask (bool): Whether return the max indices along with the outputs. default is `False`.
660 661
        ceil_mode (bool): Whether to use the ceil function to calculate output height and width. False is the default.
            If it is set to False, the floor function will be used. Default False.
662 663 664 665 666
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
667

668 669
    Examples:
        .. code-block:: python
670

671 672
          import paddle
          import paddle.nn.functional as F
C
Chen Long 已提交
673

674
          data = paddle.uniform([1, 3, 32], paddle.float32)
675 676
          pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0)
          # pool_out shape: [1, 3, 16]
677
          pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
678
          # pool_out shape: [1, 3, 16],  indices shape: [1, 3, 16]
679
    """
680 681
    """NCL to NCHW"""
    data_format = "NCHW"
Z
zhiboniu 已提交
682
    if not in_dynamic_mode():
683
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d')
684 685 686
    _check_input(x, 3)
    x = unsqueeze(x, [2])
    kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size')
687 688 689
    if stride is None:
        stride = kernel_size
    else:
690
        stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride')
691

L
Ligoml 已提交
692 693 694
    padding, padding_algorithm = _update_padding_nd(
        padding, 1, ceil_mode=ceil_mode
    )
695

696 697
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)
698

F
From00 已提交
699 700
    if in_dygraph_mode():
        if return_mask:
L
Ligoml 已提交
701 702 703 704 705 706 707 708
            pool_out = _C_ops.max_pool2d_with_index(
                x, kernel_size, stride, padding, False, False
            )
            return (
                (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
                if return_mask
                else squeeze(pool_out[0], [2])
            )
F
From00 已提交
709
        else:
L
Ligoml 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722 723
            pool_out = _C_ops.pool2d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
                True,
            )
F
From00 已提交
724 725 726
            return squeeze(pool_out, [2])

    if _in_legacy_dygraph():
727
        if return_mask:
728
            pool_out = _legacy_C_ops.max_pool2d_with_index(
L
Ligoml 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
                x,
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'strides',
                stride,
                'paddings',
                padding,
                'padding_algorithm',
                padding_algorithm,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
            return (
                (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
                if return_mask
                else squeeze(pool_out[0], [2])
            )
D
Double_V 已提交
756
        else:
757
            pool_out = _legacy_C_ops.pool2d(
L
Ligoml 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
                x,
                'pooling_type',
                'max',
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'padding_algorithm',
                padding_algorithm,
                'strides',
                stride,
                'paddings',
                padding,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
D
Double_V 已提交
782 783
            return squeeze(pool_out, [2])

784
    op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
785
    helper = LayerHelper(op_type, **locals())
786
    dtype = helper.input_dtype(input_param_name='x')
787
    pool_out = helper.create_variable_for_type_inference(dtype)
788
    mask = helper.create_variable_for_type_inference('int32')
789 790
    outputs = {"Out": pool_out, "Mask": mask}

L
Ligoml 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    helper.append_op(
        type=op_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": 'max',
            "ksize": kernel_size,
            "global_pooling": False,
            "strides": stride,
            "paddings": padding,
            "padding_algorithm": padding_algorithm,
            "use_cudnn": True,
            "ceil_mode": ceil_mode,
            "use_mkldnn": False,
            "exclusive": True,
            "data_format": data_format,
        },
    )

    return (
        (squeeze(pool_out, [2]), squeeze(mask, [2]))
        if return_mask
        else squeeze(pool_out, [2])
    )
815 816


817
def _unpool_output_size(x, kernel_size, stride, padding, output_size):
L
Ligoml 已提交
818 819 820
    assert output_size is None or isinstance(output_size, (list, tuple)), (
        "Required output_size is None|list|tuple, but received %s" % output_size
    )
821 822 823
    input_size = x.shape
    default_size = []
    for d in range(len(kernel_size)):
L
Ligoml 已提交
824 825 826 827 828
        default_size.append(
            (input_size[-len(kernel_size) + d] - 1) * stride[d]
            + kernel_size[d]
            - 2 * padding[d]
        )
829 830

    has_static_var = False
831
    if output_size is None:
832
        return default_size
833 834 835 836 837 838 839 840
    elif utils._contain_var(output_size):
        if not _non_static_mode():
            has_static_var = True
            output_size = utils._convert_to_tensor_list(output_size)
        else:
            for i, var in enumerate(output_size):
                if isinstance(var, Variable):
                    output_size[i] = var.numpy()[0]
841 842 843 844 845 846 847

    if len(output_size) == len(kernel_size) + 2:
        output_size = output_size[2:]
    if len(output_size) != len(kernel_size):
        raise ValueError(
            "output_size should be a sequence containing "
            "{} or {} elements, but it has a length of '{}'".format(
L
Ligoml 已提交
848 849 850
                len(kernel_size), len(kernel_size) + 2, len(output_size)
            )
        )
851 852 853 854 855 856
    if not has_static_var:
        for d in range(len(kernel_size)):
            min_size = default_size[d] - stride[d]
            max_size = default_size[d] + stride[d]
            if not (min_size < output_size[d] < max_size):
                raise ValueError(
L
Ligoml 已提交
857 858 859 860
                    'invalid output_size "{}" (dim {} must be between {} and {})'.format(
                        output_size, d, min_size, max_size
                    )
                )
861 862

    return output_size
863 864


L
Ligoml 已提交
865 866 867 868 869 870 871 872 873 874
def max_unpool1d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCL",
    output_size=None,
    name=None,
):
875
    r"""
876
    This API implements max unpooling 1d opereation.
L
Ligoml 已提交
877 878
    `max_unpool1d` accepts the output of `max_pool1d` as input,
    including the indices of the maximum value and calculate the partial inverse.
879 880 881 882
    All non-maximum values ​​are set to zero.

    - Input: :math:`(N, C, L_{in})`
    - Output: :math:`(N, C, L_{out})`, where
L
Ligoml 已提交
883

884 885 886 887 888 889 890 891
    .. math::
        L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size

    or as given by :attr:`output_size` in the call operator.


    Args:
        x (Tensor): The input tensor of unpooling operator which is a 3-D tensor with
L
Ligoml 已提交
892
                          shape [N, C, L]. The format of input tensor is `"NCL"`,
893 894 895
                          where `N` is batch size, `C` is the number of channels, `L` is
                          the length of the feature. The data type is float32 or float64.
        indices (Tensor): The indices given out by maxpooling1d which is a 3-D tensor with
L
Ligoml 已提交
896
                          shape [N, C, L]. The format of input tensor is `"NCL"` ,
897 898 899 900 901 902 903
                          where `N` is batch size, `C` is the number of channels, `L` is
                          the length of the featuree. The data type is float32 or float64.
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
904
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
905 906 907 908 909 910 911 912 913 914
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, stride, padding).
        data_format (string): The data format of the input and output data.
                        The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_length]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.

    Returns:
L
Ligoml 已提交
915
        Tensor: The output tensor of unpooling result.
916 917 918

    Examples:
        .. code-block:: python
L
Ligoml 已提交
919

920 921 922 923 924 925 926 927 928 929 930 931
            import paddle
            import paddle.nn.functional as F

            data = paddle.rand(shape=[1, 3, 16])
            pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
            # pool_out shape: [1, 3, 8],  indices shape: [1, 3, 8]
            unpool_out = F.max_unpool1d(pool_out, indices, kernel_size=2, padding=0)
            # unpool_out shape: [1, 3, 16]

    """
    """NCL to NCHW"""
    if data_format not in ["NCL"]:
L
Ligoml 已提交
932 933 934 935
        raise ValueError(
            "Attr(data_format) should be 'NCL'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
936 937 938 939 940 941 942 943 944 945 946 947
    data_format = "NCHW"
    x = unsqueeze(x, [2])
    indices = unsqueeze(indices, [2])
    kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size')
    if stride is None:
        stride = kernel_size
    else:
        stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride')
    padding, padding_algorithm = _update_padding_nd(padding, 1)
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)

L
Ligoml 已提交
948 949 950
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
951

X
xiaoting 已提交
952
    if in_dygraph_mode():
L
Ligoml 已提交
953 954 955
        output = _C_ops.unpool(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
X
xiaoting 已提交
956 957
        return squeeze(output, [2])
    elif in_dynamic_mode():
L
Ligoml 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
        output = _legacy_C_ops.unpool(
            x,
            indices,
            'unpooling_type',
            'max',
            'ksize',
            kernel_size,
            'strides',
            stride,
            'paddings',
            padding,
            "output_size",
            output_size,
            "data_format",
            data_format,
        )
974 975 976 977 978 979 980
        return squeeze(output, [2])

    op_type = "unpool"
    helper = LayerHelper(op_type, **locals())
    dtype = helper.input_dtype(input_param_name="x")
    unpool_out = helper.create_variable_for_type_inference(dtype)

L
Ligoml 已提交
981 982 983 984 985 986 987 988 989 990 991 992
    helper.append_op(
        type=op_type,
        inputs={"X": x, "Indices": indices},
        outputs={"Out": unpool_out},
        attrs={
            "unpooling_type": "max",
            "ksize": kernel_size,
            "strides": stride,
            "paddings": padding,
            "output_size": output_size,
        },
    )
993 994 995
    return squeeze(unpool_out, [2])


L
Ligoml 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005
def max_unpool2d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCHW",
    output_size=None,
    name=None,
):
1006
    r"""
1007
    This API implements max unpooling 2d opereation.
1008
    See more details in :ref:`api_nn_pooling_MaxUnPool2D` .
1009

1010 1011

    Args:
1012
        x (Tensor): The input tensor of unpooling operator which is a 4-D tensor with
L
Ligoml 已提交
1013
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"`,
1014
                          where `N` is batch size, `C` is the number of channels,
1015 1016
                          `H` is the height of the feature, and `W` is the width of the
                          feature. The data type if float32 or float64.
1017
        indices (Tensor): The indices given out by maxpooling2d which is a 4-D tensor with
L
Ligoml 已提交
1018
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"` ,
1019 1020 1021 1022 1023 1024 1025 1026
                          where `N` is batch size, `C` is the number of channels,
                          `H` is the height of the feature, and `W` is the width of the
                          feature. The data type if float32 or float64.
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
1027
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1028 1029
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, padding).
1030 1031 1032
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

        - Input: :math:`(N, C, H_{in}, W_{in})`
        - Output: :math:`(N, C, H_{out}, W_{out})`, where

          .. math::
            H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}

          .. math::
            W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}

          or as given by :attr:`output_size` in the call operator

        Returns:
L
Ligoml 已提交
1047
            Tensor: The output tensor of unpooling result.
1048 1049 1050 1051

        Raises:
            ValueError: If the input is not a 4-D tensor.
            ValueError: If indeces shape is not equal input shape.
L
Ligoml 已提交
1052

1053 1054 1055

        Examples:
            .. code-block:: python
L
Ligoml 已提交
1056

C
Chen Long 已提交
1057 1058
            import paddle
            import paddle.nn.functional as F
1059

1060
            data = paddle.rand(shape=[1,1,6,6])
1061 1062 1063 1064 1065
            pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
            # pool_out shape: [1, 1, 3, 3],  indices shape: [1, 1, 3, 3]
            unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0)
            # unpool_out shape: [1, 1, 6, 6]

L
Ligoml 已提交
1066
            # specify a different output size than input size
1067
            unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0, output_size=[7,7])
L
Ligoml 已提交
1068
            # unpool_out shape: [1, 1, 7, 7]
1069

1070 1071
    """
    kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size')
1072 1073 1074 1075 1076 1077 1078
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 2, 'pool_stride')
    padding = utils.convert_to_list(padding, 2, 'padding')

    if data_format not in ["NCHW"]:
L
Ligoml 已提交
1079 1080 1081 1082
        raise ValueError(
            "Attr(data_format) should be 'NCHW'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
1083

L
Ligoml 已提交
1084 1085 1086
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
1087

X
xiaoting 已提交
1088
    if in_dygraph_mode():
L
Ligoml 已提交
1089 1090 1091
        output = _C_ops.unpool(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
1092
        return output
X
xiaoting 已提交
1093
    elif in_dynamic_mode():
L
Ligoml 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        output = _legacy_C_ops.unpool(
            x,
            indices,
            'unpooling_type',
            'max',
            'ksize',
            kernel_size,
            'strides',
            stride,
            'paddings',
            padding,
            "output_size",
            output_size,
            "data_format",
            data_format,
        )
1110 1111 1112 1113 1114 1115 1116
        return output

    op_type = "unpool"
    helper = LayerHelper(op_type, **locals())
    dtype = helper.input_dtype(input_param_name="x")
    unpool_out = helper.create_variable_for_type_inference(dtype)

L
Ligoml 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    helper.append_op(
        type=op_type,
        inputs={"X": x, "Indices": indices},
        outputs={"Out": unpool_out},
        attrs={
            "unpooling_type": "max",
            "ksize": kernel_size,
            "strides": stride,
            "paddings": padding,
            "output_size": output_size,
        },
    )
1129 1130 1131
    return unpool_out


L
Ligoml 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
def max_unpool3d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCDHW",
    output_size=None,
    name=None,
):
1142
    r"""
1143
    This API implements max unpooling 3d opereation.
L
Ligoml 已提交
1144 1145
    `max_unpool3d` accepts the output of `max_pool3d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1146 1147 1148 1149
    All non-maximum values ​​are set to zero.

    - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`
    - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
L
Ligoml 已提交
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    .. math::
        D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0]

    .. math::
        H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1]

    .. math::
        W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2]

    or as given by :attr:`output_size` in the call operator


    Args:
        x (Tensor): The input tensor of unpooling operator which is a 5-D tensor with
L
Ligoml 已提交
1165
                          shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`,
1166
                          where `N` is batch size, `C` is the number of channels, `D` is
L
Ligoml 已提交
1167
                          the depth of the feature, `H` is the height of the feature,
1168 1169
                          and `W` is the width of the feature. The data type is float32 or float64.
        indices (Tensor): The indices given out by maxpooling3d which is a 5-D tensor with
L
Ligoml 已提交
1170
                          shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` ,
1171
                          where `N` is batch size, `C` is the number of channels, `D` is
L
Ligoml 已提交
1172
                          the depth of the feature, `H` is the height of the feature,
1173 1174 1175 1176 1177 1178
                          and `W` is the width of the feature. The data type is float32 or float64.
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
1179
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, stride, padding).
        data_format (string): The data format of the input and output data.
                        The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.

    Returns:
L
Ligoml 已提交
1190
        Tensor: The output tensor of unpooling result.
1191 1192 1193

    Examples:
        .. code-block:: python
L
Ligoml 已提交
1194

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
            import paddle
            import paddle.nn.functional as F

            data = paddle.rand(shape=[1, 1, 4, 4, 6])
            pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
            # pool_out shape: [1, 1, 2, 2, 3],  indices shape: [1, 1, 2, 2, 3]
            unpool_out = F.max_unpool3d(pool_out, indices, kernel_size=2, padding=0)
            # unpool_out shape: [1, 1, 4, 4, 6]

    """
    kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size')
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 3, 'pool_stride')
    padding = utils.convert_to_list(padding, 3, 'padding')

    if data_format not in ["NCDHW"]:
L
Ligoml 已提交
1213 1214 1215 1216
        raise ValueError(
            "Attr(data_format) should be 'NCDHW'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
1217

L
Ligoml 已提交
1218 1219 1220
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
1221

X
xiaoting 已提交
1222
    if in_dygraph_mode():
L
Ligoml 已提交
1223 1224 1225
        output = _C_ops.unpool3d(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
1226
        return output
X
xiaoting 已提交
1227
    elif in_dynamic_mode():
L
Ligoml 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        output = _legacy_C_ops.unpool3d(
            x,
            indices,
            'unpooling_type',
            'max',
            'ksize',
            kernel_size,
            'strides',
            stride,
            'paddings',
            padding,
            "output_size",
            output_size,
            "data_format",
            data_format,
        )
1244 1245 1246 1247 1248 1249 1250
        return output

    op_type = "unpool3d"
    helper = LayerHelper(op_type, **locals())
    dtype = helper.input_dtype(input_param_name="x")
    unpool_out = helper.create_variable_for_type_inference(dtype)

L
Ligoml 已提交
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    helper.append_op(
        type=op_type,
        inputs={"X": x, "Indices": indices},
        outputs={"Out": unpool_out},
        attrs={
            "unpooling_type": "max",
            "ksize": kernel_size,
            "strides": stride,
            "paddings": padding,
            "output_size": output_size,
        },
    )
1263 1264 1265
    return unpool_out


L
Ligoml 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
def max_pool2d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    data_format="NCHW",
    name=None,
):
W
Wei Shengyu 已提交
1276 1277 1278
    """
    This API implements max pooling 2d operation.
    See more details in :ref:`api_nn_pooling_MaxPool2d` .
W
Wei Shengyu 已提交
1279

W
Wei Shengyu 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    Args:
        x (Tensor): The input tensor of pooling operator which is a 4-D tensor with
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"` or
                          `"NHWC"`, where `N` is batch size, `C` is the number of channels,
                          `H` is the height of the feature, and `W` is the width of the
                          feature. The data type if float32 or float64.
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
            it must contain two integers, (kernel_size_Height, kernel_size_Width).
            Otherwise, the pool kernel size will be a square of an int.
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
            it must contain two integers, (stride_Height, stride_Width).
            Otherwise, the pool stride size will be a square of an int.
        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
        ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape
        return_mask (bool): Whether to return the max indices along with the outputs. Default False, only support `"NCHW"` data format
        data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`.
                        The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_height, input_width]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.

    Examples:
        .. code-block:: python
W
Wei Shengyu 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

          import paddle
          import paddle.nn.functional as F

          # max pool2d
          x = paddle.uniform([1, 3, 32, 32], paddle.float32)
          out = F.max_pool2d(x, kernel_size=2, stride=2, padding=0)
          # output.shape [1, 3, 16, 16]
          # for return_mask=True
          out, max_indices = F.max_pool2d(x, kernel_size=2, stride=2, padding=0, return_mask=True)
          # out.shape [1, 3, 16, 16], max_indices.shape [1, 3, 16, 16],
W
Wei Shengyu 已提交
1323
    """
W
Wei Shengyu 已提交
1324

1325
    kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size')
1326 1327 1328 1329 1330 1331 1332 1333
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 2, 'pool_stride')

    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
L
Ligoml 已提交
1334 1335
            "Attr(data_format): %s." % str(data_format)
        )
1336 1337 1338

    channel_last = True if data_format == "NHWC" else False

L
Ligoml 已提交
1339 1340 1341
    padding, padding_algorithm = _update_padding_nd(
        padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode
    )
1342

1343
    if data_format == "NHWC" and return_mask:
D
Double_V 已提交
1344
        raise ValueError(
1345
            "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d"
D
Double_V 已提交
1346 1347
        )

F
From00 已提交
1348 1349
    if in_dygraph_mode():
        if return_mask:
L
Ligoml 已提交
1350 1351 1352
            output = _C_ops.max_pool2d_with_index(
                x, kernel_size, stride, padding, False, False
            )
F
From00 已提交
1353 1354
            return output if return_mask else output[0]
        else:
L
Ligoml 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
            return _C_ops.pool2d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
                True,
            )
F
From00 已提交
1369 1370

    if _in_legacy_dygraph():
1371
        if return_mask:
1372
            output = _legacy_C_ops.max_pool2d_with_index(
L
Ligoml 已提交
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
                x,
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'strides',
                stride,
                'paddings',
                padding,
                'padding_algorithm',
                padding_algorithm,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
1395
            return output if return_mask else output[0]
D
Double_V 已提交
1396
        else:
1397
            output = _legacy_C_ops.pool2d(
L
Ligoml 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
                x,
                'pooling_type',
                'max',
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'padding_algorithm',
                padding_algorithm,
                'strides',
                stride,
                'paddings',
                padding,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
D
Double_V 已提交
1422
            return output
1423

1424
    op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
1425
    helper = LayerHelper(op_type, **locals())
L
Ligoml 已提交
1426 1427 1428
    check_variable_and_dtype(
        x, 'x', ['float16', 'float32', 'float64'], 'max_pool2d'
    )
1429
    dtype = helper.input_dtype(input_param_name='x')
1430
    pool_out = helper.create_variable_for_type_inference(dtype)
1431
    mask = helper.create_variable_for_type_inference("int32")
1432
    outputs = {"Out": pool_out, "Mask": mask}
1433

L
Ligoml 已提交
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    helper.append_op(
        type=op_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": 'max',
            "ksize": kernel_size,
            "global_pooling": False,
            "strides": stride,
            "paddings": padding,
            "padding_algorithm": padding_algorithm,
            "use_cudnn": True,
            "ceil_mode": ceil_mode,
            "use_mkldnn": False,
            "exclusive": True,
            "data_format": data_format,
        },
    )
1452

1453
    return (pool_out, mask) if return_mask else pool_out
1454 1455


L
Ligoml 已提交
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
def max_pool3d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    data_format="NCDHW",
    name=None,
):
1466
    """
1467 1468
    This API implements max pooling 2d operation.
    See more details in :ref:`api_nn_pooling_MaxPool3d` .
W
Wei Shengyu 已提交
1469

1470 1471
    Args:
        x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
D
Double_V 已提交
1472
                          shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` or `"NDHWC"`, where N represents batch size, C represents the number of channels, D, H and W represent the depth, height and width of the feature respectively.
1473
        kernel_size (int|list|tuple): The pool kernel size. If the kernel size
1474
            is a tuple or list, it must contain three integers,
1475
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
1476
            Otherwise, the pool kernel size will be the cube of an int.
1477 1478
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
            it must contain three integers, [stride_Depth, stride_Height, stride_Width).
1479
            Otherwise, the pool stride size will be a cube of an int.
1480 1481 1482 1483 1484 1485 1486
        padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
1487
        ceil_mode (bool): ${ceil_mode_comment}
1488
        return_mask (bool): Whether to return the max indices along with the outputs. Default False. Only support "NDCHW" data_format.
1489 1490 1491 1492 1493 1494
        data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`.
                        The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
L
Ligoml 已提交
1495

1496 1497
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
W
Wei Shengyu 已提交
1498

1499 1500
    Examples:
        .. code-block:: python
1501

W
Wei Shengyu 已提交
1502 1503
          import paddle
          import paddle.nn.functional as F
1504

W
Wei Shengyu 已提交
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
          # max pool3d
          x = paddle.uniform([1, 3, 32, 32, 32])
          output = F.max_pool3d(x,
                                kernel_size=2,
                                stride=2, padding=0)
          # output.shape [1, 3, 16, 16, 16]
          # for return_mask=True
          x = paddle.uniform([1, 3, 32, 32, 32])
          output, max_indices = paddle.nn.functional.max_pool3d(x,
                                                                kernel_size=2,
                                                                stride=2,
                                                                padding=0,
                                                                return_mask=True)

          # output.shape [1, 3, 16, 16, 16], max_indices.shape [1, 3, 16, 16, 16]
1520
    """
W
Wei Shengyu 已提交
1521

1522 1523 1524 1525 1526 1527
    kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size')
    if stride is None:
        stride = kernel_size
    else:
        stride = utils.convert_to_list(stride, 3, 'pool_stride')

1528
    channel_last = _channel_last(data_format, 3)
1529

L
Ligoml 已提交
1530 1531 1532
    padding, padding_algorithm = _update_padding_nd(
        padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
    )
1533

1534
    if data_format == "NDHWC" and return_mask:
D
Double_V 已提交
1535
        raise ValueError(
1536
            "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d"
D
Double_V 已提交
1537 1538
        )

F
From00 已提交
1539 1540
    if in_dygraph_mode():
        if return_mask:
L
Ligoml 已提交
1541 1542 1543
            output = _C_ops.max_pool3d_with_index(
                x, kernel_size, stride, padding, False, False
            )
F
From00 已提交
1544 1545
            return output if return_mask else output[0]
        else:
L
Ligoml 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
            return _C_ops.pool3d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
                True,
            )
F
From00 已提交
1560 1561

    if _in_legacy_dygraph():
1562
        if return_mask:
1563
            output = _legacy_C_ops.max_pool3d_with_index(
L
Ligoml 已提交
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
                x,
                'pooling_type',
                'max',
                'ksize',
                kernel_size,
                'strides',
                stride,
                'paddings',
                padding,
                'global_pooling',
                False,
                'padding_algorithm',
                padding_algorithm,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
1588
            return output if return_mask else output[0]
D
Double_V 已提交
1589
        else:
1590
            output = _legacy_C_ops.pool3d(
L
Ligoml 已提交
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
                x,
                'pooling_type',
                'max',
                'ksize',
                kernel_size,
                'global_pooling',
                False,
                'padding_algorithm',
                padding_algorithm,
                'strides',
                stride,
                'paddings',
                padding,
                'use_cudnn',
                True,
                'ceil_mode',
                ceil_mode,
                'use_mkldnn',
                False,
                'exclusive',
                True,
                'data_format',
                data_format,
            )
D
Double_V 已提交
1615
            return output
1616

1617
    op_type = "max_pool3d_with_index" if return_mask else "pool3d"
1618
    helper = LayerHelper(op_type, **locals())
1619
    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d')
1620
    dtype = helper.input_dtype(input_param_name='x')
1621
    pool_out = helper.create_variable_for_type_inference(dtype)
1622
    mask = helper.create_variable_for_type_inference('int32')
1623 1624
    outputs = {"Out": pool_out, "Mask": mask}

L
Ligoml 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    helper.append_op(
        type=op_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": 'max',
            "ksize": kernel_size,
            "global_pooling": False,
            "strides": stride,
            "paddings": padding,
            "padding_algorithm": padding_algorithm,
            "use_cudnn": True,
            "ceil_mode": ceil_mode,
            "use_mkldnn": False,
            "exclusive": False,
            "data_format": data_format,
        },
    )
1643

1644
    return (pool_out, mask) if return_mask else pool_out
1645 1646


1647
def adaptive_avg_pool1d(x, output_size, name=None):
1648
    """
L
Ligoml 已提交
1649 1650
    Adaptive average pooling 1d operation on :attr:`x` according to :attr:`output_size`.

1651 1652
    Notes:
        See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` .
D
Double_V 已提交
1653

1654
    Args:
1655 1656 1657
        x (Tensor): The input Tensor of pooling, which is a 3-D tensor with shape :math:`[N, C, L]`, where :math:`N` is batch size, :math:`C` is the number of channels and :math:`L` is the length of the feature. The data type is float32 or float64.
        output_size (int): The target output size. Its data type must be int.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
L
Ligoml 已提交
1658

1659
    Returns:
1660
        Tensor: The result of 1D adaptive average pooling. Its data type is same as input.
L
Ligoml 已提交
1661

1662 1663
    Examples:
        .. code-block:: python
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682

            # average adaptive pool1d
            # suppose input data in shape of [N, C, L], `output_size` is m or [m],
            # output shape is [N, C, m], adaptive pool divide L dimension
            # of input data into m grids averagely and performs poolings in each
            # grid to get output.
            # adaptive max pool performs calculations as follow:
            #
            #     for i in range(m):
            #         lstart = floor(i * L / m)
            #         lend = ceil((i + 1) * L / m)
            #         output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend)
            #
            import paddle
            import paddle.nn.functional as F

            data = paddle.uniform([1, 3, 32])
            pool_out = F.adaptive_avg_pool1d(data, output_size=16)
            # pool_out shape: [1, 3, 16])
1683 1684
    """
    pool_type = 'avg'
Z
zhiboniu 已提交
1685
    if not in_dynamic_mode():
L
Ligoml 已提交
1686 1687 1688
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'adaptive_pool2d'
        )
1689
        check_type(output_size, 'pool_size', (int), 'adaptive_pool1d')
1690 1691
    _check_input(x, 3)
    pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size')
1692

1693
    x = unsqueeze(x, [2])
1694
    if in_dygraph_mode():
L
Ligoml 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
        pool_out = _C_ops.pool2d(
            x,
            pool_size,
            [1, 1],
            [0, 0],
            False,
            True,
            "NCHW",
            pool_type,
            False,
            True,
            "EXPLICIT",
            False,
        )
1709 1710
        return squeeze(pool_out, [2])
    if _in_legacy_dygraph():
L
Ligoml 已提交
1711 1712 1713
        pool_out = _legacy_C_ops.pool2d(
            x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True
        )
1714
        return squeeze(pool_out, [2])
1715

1716 1717
    l_type = "pool2d"

1718
    helper = LayerHelper(l_type, **locals())
1719
    dtype = helper.input_dtype(input_param_name='x')
1720 1721
    pool_out = helper.create_variable_for_type_inference(dtype)

1722
    outputs = {"Out": pool_out}
L
Ligoml 已提交
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": pool_type,
            "ksize": pool_size,
            "adaptive": True,
        },
    )
1733

1734
    return squeeze(pool_out, [2])
1735 1736


1737
def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None):
1738 1739
    r"""

1740 1741
    Applies 2D adaptive avg pooling on input tensor. The h and w dimensions
    of the output tensor are determined by the parameter output_size.
L
Ligoml 已提交
1742

1743
    For avg adaptive pool2d:
1744

1745
    ..  math::
1746 1747 1748 1749
        hstart &= floor(i * H_{in} / H_{out}) \\
        hend &= ceil((i + 1) * H_{in} / H_{out}) \\
        wstart &= floor(j * W_{in} / W_{out}) \\
        wend &= ceil((j + 1) * W_{in} / W_{out}) \\
1750
        Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
1751 1752 1753

    Args:
        x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
1754
                          The data type can be float32 or float64.
1755 1756 1757
        output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
            it must contain two element, (H, W). H and W can be either a int, or None which means
            the size will be the same as that of the input.
1758
        data_format (str, optional): The data format of the input and output data. An optional string
1759 1760 1761 1762 1763
            from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in
            the order of: [batch_size, input_channels, input_height, input_width].
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
1764

1765
    Returns:
1766
        Tensor, The output tensor of avg adaptive pool2d result. The data type is same as input tensor.
1767

1768 1769
    Examples:
        .. code-block:: python
B
Bai Yifan 已提交
1770

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
            # adaptive avg pool2d
            # suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
            # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
            # of input data into m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive avg pool performs calculations as follow:
            #
            #     for i in range(m):
            #         for j in range(n):
            #             hstart = floor(i * H / m)
            #             hend = ceil((i + 1) * H / m)
            #             wstart = floor(i * W / n)
            #             wend = ceil((i + 1) * W / n)
            #             output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend])
            #
            import paddle
1787

1788
            x = paddle.rand([2, 3, 32, 32])
1789
            # x.shape is [2, 3, 32, 32]
1790
            out = paddle.nn.functional.adaptive_avg_pool2d(
1791 1792
                            x = x,
                            output_size=[3, 3])
1793
            # out.shape is [2, 3, 3, 3]
1794

1795
    """
Z
zhiboniu 已提交
1796
    if not in_dynamic_mode():
L
Ligoml 已提交
1797 1798 1799
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d'
        )
1800
        check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')
1801 1802 1803 1804

    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
L
Ligoml 已提交
1805 1806
            "Attr(data_format): %s." % str(data_format)
        )
1807 1808 1809 1810 1811 1812 1813 1814 1815

    if data_format == "NCHW":
        in_h, in_w = x.shape[2:4]
    else:
        in_h, in_w = x.shape[1:3]

    if isinstance(output_size, int):
        output_size = utils.convert_to_list(output_size, 2, 'output_size')
    else:
1816
        output_size = list(output_size)
1817
        if output_size[0] is None:
1818
            output_size[0] = in_h
1819
        if output_size[1] is None:
1820 1821
            output_size[1] = in_w

1822 1823 1824 1825 1826 1827 1828 1829 1830
    if _non_static_mode():
        output_size = [
            item.numpy().item(0) if isinstance(item, Variable) else item
            for item in output_size
        ]
    # output_size support Variable in static mode
    elif utils._contain_var(output_size):
        output_size = utils._convert_to_tensor_list(output_size)

F
From00 已提交
1831
    if in_dygraph_mode():
L
Ligoml 已提交
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
        return _C_ops.pool2d(
            x,
            output_size,
            [1, 1],
            [0, 0],
            False,
            True,
            data_format,
            'avg',
            False,
            True,
            "EXPLICIT",
            False,
        )
F
From00 已提交
1846 1847

    if _in_legacy_dygraph():
L
Ligoml 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
        return _legacy_C_ops.pool2d(
            x,
            'pooling_type',
            'avg',
            'ksize',
            output_size,
            'global_pooling',
            False,
            'adaptive',
            True,
            'data_format',
            data_format,
        )
1861 1862 1863 1864

    l_type = 'pool2d'

    helper = LayerHelper(l_type, **locals())
1865
    dtype = helper.input_dtype(input_param_name='x')
1866 1867 1868 1869
    pool_out = helper.create_variable_for_type_inference(dtype)

    outputs = {"Out": pool_out}

L
Ligoml 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": "avg",
            "ksize": output_size,
            "adaptive": True,
            "data_format": data_format,
        },
    )
1881 1882 1883 1884 1885

    return pool_out


def adaptive_avg_pool3d(x, output_size, data_format='NCDHW', name=None):
1886 1887
    r"""

1888 1889
    This operation applies 3D adaptive avg pooling on input tensor. The h and w dimensions
    of the output tensor are determined by the parameter output_size.
L
Ligoml 已提交
1890

1891
    For avg adaptive pool3d:
1892

1893
    ..  math::
1894 1895 1896 1897 1898 1899
        dstart &= floor(i * D_{in} / D_{out}) \\
        dend &= ceil((i + 1) * D_{in} / D_{out}) \\
        hstart &= floor(j * H_{in} / H_{out}) \\
        hend &= ceil((j + 1) * H_{in} / H_{out}) \\
        wstart &= floor(k * W_{in} / W_{out}) \\
        wend &= ceil((k + 1) * W_{in} / W_{out}) \\
1900 1901
        Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
            {(dend - dstart) * (hend - hstart) * (wend - wstart)}
1902 1903 1904

    Args:
        x (Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor.
1905 1906 1907 1908 1909
            The data type can be float32, float64.
        output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or
            list, it must contain three elements, (D, H, W). D, H and W can be either a int,
            or None which means the size will be the same as that of the input.
        data_format (str, optional): The data format of the input and output data. An optional string
1910 1911
            from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in
            the order of: [batch_size, input_channels, input_depth, input_height, input_width].
1912 1913 1914
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.

1915
    Returns:
1916
        Tensor, The output tensor of avg adaptive pool3d result. The data type is same as input tensor.
1917

1918 1919
    Examples:
        .. code-block:: python
B
Bai Yifan 已提交
1920

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
            # adaptive avg pool3d
            # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n],
            # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
            # of input data into l * m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive avg pool performs calculations as follow:
            #
            #     for i in range(l):
            #         for j in range(m):
            #             for k in range(n):
            #                 dstart = floor(i * D / l)
            #                 dend = ceil((i + 1) * D / l)
            #                 hstart = floor(j * H / m)
            #                 hend = ceil((j + 1) * H / m)
            #                 wstart = floor(k * W / n)
            #                 wend = ceil((k + 1) * W / n)
            #                 output[:, :, i, j, k] =
            #                     avg(input[:, :, dstart:dend, hstart: hend, wstart: wend])
            import paddle
1940 1941

            input_data = paddle.randn(shape=(2, 3, 8, 32, 32))
1942
            out = paddle.nn.functional.adaptive_avg_pool3d(
1943
                            x = input_data,
1944
                            output_size=[3, 3, 3])
1945
            # out.shape is [2, 3, 3, 3, 3]
1946

1947
    """
Z
zhiboniu 已提交
1948
    if not in_dynamic_mode():
L
Ligoml 已提交
1949 1950 1951
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_avg_pool3d'
        )
1952
        check_type(data_format, 'data_format', str, 'adaptive_avg_pool3d')
1953 1954 1955 1956

    if data_format not in ["NCDHW", "NDHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
L
Ligoml 已提交
1957 1958
            "Attr(data_format): %s." % str(data_format)
        )
1959 1960 1961 1962 1963 1964 1965 1966 1967

    if data_format == "NCDHW":
        in_l, in_h, in_w = x.shape[2:5]
    else:
        in_l, in_h, in_w = x.shape[1:4]

    if isinstance(output_size, int):
        output_size = utils.convert_to_list(output_size, 3, 'output_size')
    else:
1968
        output_size = list(output_size)
1969
        if output_size[0] is None:
1970
            output_size[0] = in_l
1971
        if output_size[1] is None:
1972
            output_size[1] = in_h
1973
        if output_size[2] is None:
1974 1975
            output_size[2] = in_w

1976
    if in_dygraph_mode():
L
Ligoml 已提交
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
        return _C_ops.pool3d(
            x,
            output_size,
            [1, 1, 1],
            [0, 0, 0],
            False,
            True,
            data_format,
            'avg',
            False,
            True,
            "EXPLICIT",
            False,
        )
1991
    elif _in_legacy_dygraph():
L
Ligoml 已提交
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
        return _legacy_C_ops.pool3d(
            x,
            'pooling_type',
            'avg',
            'ksize',
            output_size,
            'global_pooling',
            False,
            'adaptive',
            True,
            'data_format',
            data_format,
        )
2005 2006 2007 2008

    l_type = 'pool3d'

    helper = LayerHelper(l_type, **locals())
2009
    dtype = helper.input_dtype(input_param_name='x')
2010 2011 2012
    pool_out = helper.create_variable_for_type_inference(dtype)
    outputs = {"Out": pool_out}

L
Ligoml 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": "avg",
            "ksize": output_size,
            "adaptive": True,
            "data_format": data_format,
        },
    )
2024 2025

    return pool_out
2026 2027


2028
def adaptive_max_pool1d(x, output_size, return_mask=False, name=None):
2029 2030 2031 2032 2033 2034 2035 2036 2037
    """
    This API implements adaptive max pooling 1d operation.
    See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` .

    Args:
        x (Tensor): The input tensor of pooling operator, which is a 3-D tensor
                              with shape [N, C, L].  The format of input tensor is NCL,
                              where N is batch size, C is the number of channels, L is the
                              length of the feature. The data type is float32 or float64.
2038
        output_size (int): The pool kernel size. The value should be an integer.
2039
        return_mask (bool): If true, the index of max pooling point will be returned along
2040 2041 2042 2043 2044 2045 2046
                with outputs. It cannot be set in average pooling type. Default False.
        name(str, optional): For detailed information, please refer
                                 to :ref:`api_guide_Name`. Usually name is no need to set and
                                 None by default.
    Returns:
            Tensor: The output tensor of adaptive pooling result. The data type is same
                      as input tensor.
L
Ligoml 已提交
2047

2048 2049
    Examples:
        .. code-block:: python
2050

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
              # max adaptive pool1d
              # suppose input data in shape of [N, C, L], `output_size` is m or [m],
              # output shape is [N, C, m], adaptive pool divide L dimension
              # of input data into m grids averagely and performs poolings in each
              # grid to get output.
              # adaptive max pool performs calculations as follow:
              #
              #     for i in range(m):
              #         lstart = floor(i * L / m)
              #         lend = ceil((i + 1) * L / m)
              #         output[:, :, i] = max(input[:, :, lstart: lend])
              #
              import paddle
              import paddle.nn.functional as F
2065

2066
              data = paddle.uniform([1, 3, 32], paddle.float32)
2067 2068
              pool_out = F.adaptive_max_pool1d(data, output_size=16)
              # pool_out shape: [1, 3, 16])
2069
              pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True)
2070 2071 2072
              # pool_out shape: [1, 3, 16] indices  shape: [1, 3, 16]
    """
    pool_type = 'max'
Z
zhiboniu 已提交
2073
    if not in_dynamic_mode():
L
Ligoml 已提交
2074 2075 2076
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d'
        )
2077 2078
        check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d')
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d')
2079 2080 2081 2082 2083
    _check_input(x, 3)

    pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size')

    x = unsqueeze(x, [2])
2084
    if in_dygraph_mode():
L
Ligoml 已提交
2085 2086 2087 2088 2089 2090 2091 2092
        pool_out = _C_ops.max_pool2d_with_index(
            x, pool_size, [1, 1], [0, 0], False, True
        )
        return (
            (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
            if return_mask
            else squeeze(pool_out[0], [2])
        )
2093
    if _in_legacy_dygraph():
L
Ligoml 已提交
2094 2095 2096 2097 2098 2099 2100 2101
        pool_out = _legacy_C_ops.max_pool2d_with_index(
            x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True
        )
        return (
            (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
            if return_mask
            else squeeze(pool_out[0], [2])
        )
2102

2103 2104
    l_type = 'max_pool2d_with_index'

2105
    helper = LayerHelper(l_type, **locals())
2106
    dtype = helper.input_dtype(input_param_name='x')
2107 2108
    pool_out = helper.create_variable_for_type_inference(dtype)

2109
    mask = helper.create_variable_for_type_inference('int32')
2110 2111
    outputs = {"Out": pool_out, "Mask": mask}

L
Ligoml 已提交
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": pool_type,
            "ksize": pool_size,
            "adaptive": True,
        },
    )
2122

L
Ligoml 已提交
2123 2124 2125 2126 2127
    return (
        (squeeze(pool_out, [2]), squeeze(mask, [2]))
        if return_mask
        else squeeze(pool_out, [2])
    )
2128 2129


2130
def adaptive_max_pool2d(x, output_size, return_mask=False, name=None):
2131
    """
L
Ligoml 已提交
2132 2133
    This operation applies a 2D adaptive max pooling on input tensor.
    See more details in :ref:`api_nn_pooling_AdaptiveMaxPool2d` .
2134

L
Ligoml 已提交
2135 2136 2137 2138 2139
    Args:
        x (Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor. The data type can be float16, float32, float64, int32 or int64.
        output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two elements, (H, W). H and W can be either a int, or None which means the size will be the same as that of the input.
        return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default.
2140

L
Ligoml 已提交
2141 2142
    Returns:
        Tensor: The output tensor of adaptive max pool2d result. The data type is same as input tensor.
2143

L
Ligoml 已提交
2144 2145
    Examples:
        .. code-block:: python
2146

L
Ligoml 已提交
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
          # max adaptive pool2d
          # suppose input data in the shape of [N, C, H, W], `output_size` is [m, n]
          # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
          # of input data into m*n grids averagely and performs poolings in each
          # grid to get output.
          # adaptive max pool performs calculations as follow:
          #
          #     for i in range(m):
          #         for j in range(n):
          #             hstart = floor(i * H / m)
          #             hend = ceil((i + 1) * H / m)
          #             wstart = floor(i * W / n)
          #             wend = ceil((i + 1) * W / n)
          #             output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend])
          #
          import paddle
2163

L
Ligoml 已提交
2164 2165 2166 2167 2168
          input_data = paddle.randn(shape=(2, 3, 32, 32))
          out = paddle.nn.functional.adaptive_max_pool2d(
                        x = input_data,
                        output_size=[3, 3])
          # out.shape is [2, 3, 3, 3]
2169
    """
Z
zhiboniu 已提交
2170
    if not in_dynamic_mode():
L
Ligoml 已提交
2171 2172 2173
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d'
        )
2174
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d')
L
Ligoml 已提交
2175
        # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d')
2176 2177 2178 2179 2180 2181
    _check_input(x, 4)

    in_h, in_w = x.shape[2:4]
    if isinstance(output_size, int):
        output_size = utils.convert_to_list(output_size, 2, 'output_size')
    else:
2182
        output_size = list(output_size)
2183 2184 2185 2186
        if output_size[0] == None:
            output_size[0] = in_h
        if output_size[1] == None:
            output_size[1] = in_w
2187
    if in_dygraph_mode():
L
Ligoml 已提交
2188 2189 2190
        pool_out = _C_ops.max_pool2d_with_index(
            x, output_size, [1, 1], [0, 0], False, True
        )
2191 2192
        return pool_out if return_mask else pool_out[0]
    if _in_legacy_dygraph():
L
Ligoml 已提交
2193 2194 2195
        pool_out = _legacy_C_ops.max_pool2d_with_index(
            x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True
        )
2196
        return pool_out if return_mask else pool_out[0]
2197 2198 2199 2200

    l_type = 'max_pool2d_with_index'

    helper = LayerHelper(l_type, **locals())
2201
    dtype = helper.input_dtype(input_param_name='x')
2202 2203
    pool_out = helper.create_variable_for_type_inference(dtype)

2204
    mask = helper.create_variable_for_type_inference('int32')
2205 2206
    outputs = {"Out": pool_out, "Mask": mask}

L
Ligoml 已提交
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": 'max',
            "ksize": output_size,
            "adaptive": True,
        },
    )
    # return (pool_out, mask) if return_mask else pool_out
2218 2219 2220
    return pool_out


2221
def adaptive_max_pool3d(x, output_size, return_mask=False, name=None):
2222
    """
L
Ligoml 已提交
2223 2224
    This operation applies a 3D adaptive max pooling on input tensor.
    See more details in :ref:`api_nn_pooling_AdaptiveMaxPool3d` .
2225

L
Ligoml 已提交
2226 2227 2228 2229 2230
    Args:
        x (Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor. The data type can be float32, float64.
        output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of the input.
        return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default.
2231

L
Ligoml 已提交
2232 2233
    Returns:
        Tensor: The output tensor of adaptive max pool3d result. The data type is same as input tensor.
2234

L
Ligoml 已提交
2235 2236
    Examples:
        .. code-block:: python
2237

L
Ligoml 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
          # adaptive max pool3d
          # suppose input data in the shape of [N, C, D, H, W], `output_size` is [l, m, n]
          # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
          # of input data into m*n grids averagely and performs poolings in each
          # grid to get output.
          # adaptive max pool performs calculations as follow:
          #
          #     for i in range(l):
          #         for j in range(m):
          #             for k in range(n):
          #                 dstart = floor(i * D / l)
          #                 dend = ceil((i + 1) * D / l)
          #                 hstart = floor(i * H / m)
          #                 hend = ceil((i + 1) * H / m)
          #                 wstart = floor(i * W / n)
          #                 wend = ceil((i + 1) * W / n)
          #             output[:, :, i, j, k] = max(input[:, :, dstart: dend, hstart: hend, wstart: wend])
          #
          import paddle
2257

L
Ligoml 已提交
2258 2259 2260 2261 2262
          input_data = paddle.randn(shape=(2, 3, 8, 32, 32))
          out = paddle.nn.functional.adaptive_max_pool3d(
                        x = input_data,
                        output_size=[3, 3, 3])
          # out.shape is [2, 3, 3, 3, 3]
2263 2264
    """

Z
zhiboniu 已提交
2265
    if not in_dynamic_mode():
L
Ligoml 已提交
2266 2267 2268
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d'
        )
2269
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d')
L
Ligoml 已提交
2270
        # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d')
2271 2272 2273 2274 2275 2276
    _check_input(x, 5)

    in_l, in_h, in_w = x.shape[2:5]
    if isinstance(output_size, int):
        output_size = utils.convert_to_list(output_size, 3, 'output_size')
    else:
2277
        output_size = list(output_size)
2278 2279 2280 2281 2282 2283 2284
        if output_size[0] == None:
            output_size[0] = in_l
        if output_size[1] == None:
            output_size[1] = in_h
        if output_size[2] == None:
            output_size[2] = in_w

Z
zhiboniu 已提交
2285
    if in_dynamic_mode():
2286 2287
        if in_dygraph_mode():
            # By default, strides is [1,1,1] and paddings is [0, 0, 0]
L
Ligoml 已提交
2288 2289 2290
            pool_out = _C_ops.max_pool3d_with_index(
                x, output_size, [1, 1, 1], [0, 0, 0], False, True
            )
2291 2292
        elif _in_legacy_dygraph():
            pool_out = _legacy_C_ops.max_pool3d_with_index(
L
Ligoml 已提交
2293 2294
                x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True
            )
2295
        return pool_out if return_mask else pool_out[0]
2296 2297 2298 2299

    l_type = 'max_pool3d_with_index'

    helper = LayerHelper(l_type, **locals())
2300
    dtype = helper.input_dtype(input_param_name='x')
2301 2302
    pool_out = helper.create_variable_for_type_inference(dtype)

2303
    mask = helper.create_variable_for_type_inference('int32')
2304 2305
    outputs = {"Out": pool_out, "Mask": mask}

L
Ligoml 已提交
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
    helper.append_op(
        type=l_type,
        inputs={"X": x},
        outputs=outputs,
        attrs={
            "pooling_type": 'max',
            "ksize": output_size,
            "adaptive": True,
        },
    )
2316

2317
    return (pool_out, mask) if return_mask else pool_out