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

15
from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode
姜永久 已提交
16
from paddle.fluid.framework import Variable, in_dygraph_mode
17

18
from ...fluid.data_feeder import check_type, check_variable_and_dtype
19 20
from ...fluid.layers import LayerHelper
from ...tensor.manipulation import squeeze, unsqueeze
21 22

# TODO: define pooling functions
23 24 25 26 27 28
from ...utils import (
    _contain_var,
    _convert_to_tensor_list,
    _is_symmetric_padding,
    convert_to_list,
)
29

30 31
__all__ = []

32

33 34 35 36 37
def _is_list_or_tuple(input):
    return isinstance(input, (list, tuple))


def _check_input(x, dimension):
38
    if len(x.shape) != dimension:
39 40
        raise ValueError(
            "Excepted Input X is {}-D tensor, but received {}-D {}".format(
41 42 43
                dimension, len(x.shape), type(x)
            )
        )
44 45


46
def _check_instance(x, x_name, types=(int, float)):
47 48

    if not isinstance(x, types):
49 50
        raise ValueError(
            "Excepted {} type for {} but received type: {}. ".format(
51 52 53
                types, x_name, type(x)
            )
        )
54 55


D
Double_V 已提交
56 57 58 59
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(
60 61 62 63
                "Excepted the input {} to be greater than {} but received x: {}. ".format(
                    x_name, min_limit, x
                )
            )
D
Double_V 已提交
64 65 66 67 68

    for ele in x:
        _check_value(ele, x_name)


69 70 71
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]
72
    else:
73
        return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0]
74 75


76 77 78 79
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_
80 81


82 83 84 85 86
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 "
87 88
                "Attr(data_format): %s" % str(data_format)
            )
89 90 91 92 93 94
        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 "
95 96
                "Attr(data_format): %s" % str(data_format)
            )
97 98 99 100 101 102
        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 "
103 104
                "Attr(data_format): %s" % str(data_format)
            )
105 106
        else:
            return True if data_format == "NDHWC" else False
107 108


109 110 111 112 113
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(
114 115 116 117
                "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.".format(
                    padding
                )
            )
118
        if padding == "VALID":
119
            if ceil_mode is not False:
120
                raise ValueError(
121
                    "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. "
122 123
                    "Received ceil_mode: True."
                )
124 125 126 127 128 129 130 131 132 133 134 135

            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):
136
                raise ValueError(
137
                    "Non-zero padding({}) in the batch or channel dimensions "
138 139
                    "is not supported.".format(padding)
                )
140
            padding_algorithm = "EXPLICIT"
141
            padding = _exclude_padding_in_batch_and_channel(
142 143
                padding, channel_last
            )
144
            if _is_symmetric_padding(padding, num_dims):
145 146 147 148
                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"
149 150
            padding = convert_to_list(padding, 2 * num_dims, 'padding')
            if _is_symmetric_padding(padding, num_dims):
151 152 153 154
                padding = padding[0::2]
        # for padding like [pad_d1, pad_d2, ...]
        elif len(padding) == num_dims and isinstance(padding[0], int):
            padding_algorithm = "EXPLICIT"
155
            padding = convert_to_list(padding, num_dims, 'padding')
156 157 158
        else:
            raise ValueError("Invalid padding: {}".format(padding))
    # for integer padding
159
    else:
160
        padding_algorithm = "EXPLICIT"
161
        padding = convert_to_list(padding, num_dims, 'padding')
162 163
    return padding, padding_algorithm

164

165
def _expand_low_nd_padding(padding):
166
    # 1d to 2d fake input
167 168 169 170 171 172
    if len(padding) == 2:
        padding = [0] * 2 + padding
    elif len(padding) == 1:
        padding = [0] + padding
    else:
        raise ValueError(
173 174 175 176
            "The size of padding's dimmention should be 1 or 2. But got padding={}".format(
                padding
            )
        )
177 178 179
    return padding


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

    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,
196
                          `L` is the length of the feature. The data type is float16, float32 or float64.
197
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
198
            it must contain an integer.
199
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
200 201 202 203 204 205 206 207
            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.
208
        exclusive (bool): Whether to exclude padding points in average pooling
209
                          mode, default is `True`.
210
        ceil_mode (bool): ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width.
211
            If it is set to False, the floor function will be used. The default value is False.
212 213 214 215 216 217 218 219
        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
220

C
Chen Long 已提交
221
            import paddle
222
            import paddle.nn as nn
C
Chen Long 已提交
223

224 225 226 227
            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]
228 229 230
    """
    """NCL to NCHW"""
    data_format = "NCHW"
Z
zhiboniu 已提交
231
    if not in_dynamic_mode():
232 233 234
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'avg_pool1d'
        )
235
    _check_input(x, 3)
236
    x = unsqueeze(x, [2])
237
    kernel_size = convert_to_list(kernel_size, 1, 'kernel_size')
238 239 240 241
    kernel_size = [1] + kernel_size
    if stride is None:
        stride = kernel_size
    else:
242
        stride = convert_to_list(stride, 1, 'pool_stride')
243 244
        stride = [1] + stride

D
Double_V 已提交
245 246 247
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

248
    channel_last = _channel_last("NCL", 1)
249 250 251
    padding, padding_algorithm = _update_padding_nd(
        padding, 1, channel_last=channel_last, ceil_mode=ceil_mode
    )
252

253 254
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)
255

256
    if in_dygraph_mode():
257 258 259 260 261 262 263 264 265 266 267 268 269
        output = _C_ops.pool2d(
            x,
            kernel_size,
            stride,
            padding,
            ceil_mode,
            exclusive,
            data_format,
            'avg',
            False,
            False,
            padding_algorithm,
        )
270 271
        return squeeze(output, [2])

姜永久 已提交
272 273 274 275 276
    else:
        op_type = 'pool2d'
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
277

姜永久 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        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,
            },
        )
296

姜永久 已提交
297
        return squeeze(pool_out, [2])
298 299


300 301 302 303 304 305 306 307 308 309 310
def avg_pool2d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    ceil_mode=False,
    exclusive=True,
    divisor_override=None,
    data_format="NCHW",
    name=None,
):
311
    """
312 313
    This API implements average pooling 2d operation.
    See more details in :ref:`api_nn_pooling_AvgPool2d` .
D
Double_V 已提交
314

315
    Args:
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        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
336
        exclusive (bool): Whether to exclude padding points in average pooling
337 338 339 340 341
                          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]`.
342 343 344
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
345

346 347
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
348

349 350
    Examples:
        .. code-block:: python
351

C
Chen Long 已提交
352 353
            import paddle
            import paddle.nn.functional as F
354

C
Chen Long 已提交
355
            # avg pool2d
356
            x = paddle.uniform([1, 3, 32, 32], paddle.float32)
C
Chen Long 已提交
357 358 359 360
            out = F.avg_pool2d(x,
                            kernel_size=2,
                            stride=2, padding=0)
            # out.shape [1, 3, 16, 16]
361
    """
362
    kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
363 364 365
    if stride is None:
        stride = kernel_size
    else:
366
        stride = convert_to_list(stride, 2, 'pool_stride')
367

D
Double_V 已提交
368 369 370
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

371
    channel_last = _channel_last(data_format, 2)
372 373 374
    padding, padding_algorithm = _update_padding_nd(
        padding, 2, channel_last, ceil_mode=ceil_mode
    )
375

姜永久 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389
    if in_dygraph_mode():
        output = _C_ops.pool2d(
            x,
            kernel_size,
            stride,
            padding,
            ceil_mode,
            exclusive,
            data_format,
            'avg',
            False,
            False,
            padding_algorithm,
        )
390 391 392 393 394
        if divisor_override is None:
            return output
        else:
            _check_instance(divisor_override, "divisor_override")
            return output * (kernel_size[0] * kernel_size[1]) / divisor_override
姜永久 已提交
395 396 397 398 399 400
    else:
        op_type = 'pool2d'
        helper = LayerHelper(op_type, **locals())
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool2d')
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
401

姜永久 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
        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,
            },
        )
420

姜永久 已提交
421 422 423 424 425 426 427
        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
            )
428 429


430 431 432 433 434 435 436 437 438 439 440
def avg_pool3d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    ceil_mode=False,
    exclusive=True,
    divisor_override=None,
    data_format="NCDHW",
    name=None,
):
441
    """
442 443
    This API implements average pooling 3d operation.
    See more details in :ref:`api_nn_pooling_AvgPool3d` .
444 445

    Args:
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        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}
464
        exclusive (bool): Whether to exclude padding points in average pooling
465 466 467 468 469
                          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]`.
470
        name(str, optional): For detailed information, please refer
471 472
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
473

474
    Returns:
475
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
476

477 478
    Examples:
        .. code-block:: python
479

480
          import paddle
C
Chen Long 已提交
481

482
          x = paddle.uniform([1, 3, 32, 32, 32], paddle.float32)
483 484 485 486 487 488 489
          # avg pool3d
          out = paddle.nn.functional.avg_pool3d(
                                            x,
                                            kernel_size = 2,
                                            stride = 2,
                                            padding=0)
          # out.shape: [1, 3, 16, 16, 16]
490
    """
491
    kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
492 493 494
    if stride is None:
        stride = kernel_size
    else:
495
        stride = convert_to_list(stride, 3, 'pool_stride')
496

497
    channel_last = _channel_last(data_format, 3)
498 499 500
    padding, padding_algorithm = _update_padding_nd(
        padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
    )
501

D
Double_V 已提交
502 503 504
    _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
    _check_value_limitation(stride, "stride", min_limit=1e-3)

505
    if in_dygraph_mode():
506 507 508 509 510 511 512 513 514 515 516 517 518
        pool_out = _C_ops.pool3d(
            x,
            kernel_size,
            stride,
            padding,
            ceil_mode,
            exclusive,
            data_format,
            'avg',
            False,
            False,
            padding_algorithm,
        )
519 520 521
    else:
        op_type = "pool3d"
        helper = LayerHelper(op_type, **locals())
522 523 524
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'avg_pool3d'
        )
525 526 527 528
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
        outputs = {"Out": pool_out}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        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,
            },
        )
547

548 549 550 551
    if divisor_override is None:
        return pool_out
    else:
        _check_instance(divisor_override, "divisor_override")
552 553 554 555 556
        return (
            pool_out
            * (kernel_size[0] * kernel_size[1] * kernel_size[2])
            / divisor_override
        )
557 558


559 560 561 562 563 564 565 566 567
def max_pool1d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    name=None,
):
568
    """
569 570
    This API implements max pooling 1d opereation.
    See more details in :ref:`api_nn_pooling_MaxPool1d` .
571 572

    Args:
573 574 575
        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.
576
        kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
577
            it must contain an integer.
578
        stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
579 580 581 582 583 584 585 586
            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.
587
        return_mask (bool): Whether return the max indices along with the outputs. default is `False`.
588 589
        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.
590 591 592 593 594
        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.
595

596 597
    Examples:
        .. code-block:: python
598

599 600
          import paddle
          import paddle.nn.functional as F
C
Chen Long 已提交
601

602
          data = paddle.uniform([1, 3, 32], paddle.float32)
603 604
          pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0)
          # pool_out shape: [1, 3, 16]
605
          pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
606
          # pool_out shape: [1, 3, 16],  indices shape: [1, 3, 16]
607
    """
608 609 610 611
    """NCL to NCHW"""
    data_format = "NCHW"
    _check_input(x, 3)
    x = unsqueeze(x, [2])
612
    kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
613 614 615
    if stride is None:
        stride = kernel_size
    else:
616
        stride = [1] + convert_to_list(stride, 1, 'pool_stride')
617

618 619 620
    padding, padding_algorithm = _update_padding_nd(
        padding, 1, ceil_mode=ceil_mode
    )
621

622 623
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)
624

F
From00 已提交
625 626
    if in_dygraph_mode():
        if return_mask:
627 628 629 630 631 632 633 634
            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 已提交
635
        else:
636 637 638 639 640 641 642 643 644 645 646 647 648
            pool_out = _C_ops.pool2d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
            )
F
From00 已提交
649 650
            return squeeze(pool_out, [2])

姜永久 已提交
651
    else:
W
Weilong Wu 已提交
652
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d')
姜永久 已提交
653 654 655 656 657 658
        op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
        mask = helper.create_variable_for_type_inference('int32')
        outputs = {"Out": pool_out, "Mask": mask}
659

姜永久 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
        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,
            },
        )
678

姜永久 已提交
679 680 681 682 683
        return (
            (squeeze(pool_out, [2]), squeeze(mask, [2]))
            if return_mask
            else squeeze(pool_out, [2])
        )
684 685


686
def _unpool_output_size(x, kernel_size, stride, padding, output_size):
687 688 689
    assert output_size is None or isinstance(output_size, (list, tuple)), (
        "Required output_size is None|list|tuple, but received %s" % output_size
    )
690 691 692
    input_size = x.shape
    default_size = []
    for d in range(len(kernel_size)):
693 694 695 696 697
        default_size.append(
            (input_size[-len(kernel_size) + d] - 1) * stride[d]
            + kernel_size[d]
            - 2 * padding[d]
        )
698 699

    has_static_var = False
700
    if output_size is None:
701
        return default_size
702
    elif _contain_var(output_size):
姜永久 已提交
703
        if not in_dygraph_mode():
704
            has_static_var = True
705
            output_size = _convert_to_tensor_list(output_size)
706 707 708
        else:
            for i, var in enumerate(output_size):
                if isinstance(var, Variable):
709
                    output_size[i] = var.numpy().item()
710 711 712 713 714 715 716

    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(
717 718 719
                len(kernel_size), len(kernel_size) + 2, len(output_size)
            )
        )
720 721 722 723 724 725
    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(
726 727 728 729
                    'invalid output_size "{}" (dim {} must be between {} and {})'.format(
                        output_size, d, min_size, max_size
                    )
                )
730 731

    return output_size
732 733


734 735 736 737 738 739 740 741 742 743
def max_unpool1d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCL",
    output_size=None,
    name=None,
):
744
    r"""
745
    This API implements max unpooling 1d opereation.
746 747
    `max_unpool1d` accepts the output of `max_pool1d` as input,
    including the indices of the maximum value and calculate the partial inverse.
748 749 750 751
    All non-maximum values ​​are set to zero.

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

753 754 755 756 757 758 759 760
    .. 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
761
                          shape [N, C, L]. The format of input tensor is `"NCL"`,
762 763 764
                          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
765
                          shape [N, C, L]. The format of input tensor is `"NCL"` ,
766 767 768 769 770 771 772
                          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.
773
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
774 775 776 777 778 779 780 781 782 783
                           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:
784
        Tensor: The output tensor of unpooling result.
785 786 787

    Examples:
        .. code-block:: python
788

789 790 791 792 793 794 795 796 797 798 799 800
            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"]:
801 802 803 804
        raise ValueError(
            "Attr(data_format) should be 'NCL'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
805 806 807
    data_format = "NCHW"
    x = unsqueeze(x, [2])
    indices = unsqueeze(indices, [2])
808
    kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
809 810 811
    if stride is None:
        stride = kernel_size
    else:
812
        stride = [1] + convert_to_list(stride, 1, 'pool_stride')
813 814 815 816
    padding, padding_algorithm = _update_padding_nd(padding, 1)
    # use 2d to implenment 1d should expand padding in advance.
    padding = _expand_low_nd_padding(padding)

817 818 819
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
820

X
xiaoting 已提交
821
    if in_dygraph_mode():
822 823 824
        output = _C_ops.unpool(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
X
xiaoting 已提交
825 826
        return squeeze(output, [2])
    elif in_dynamic_mode():
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
        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,
        )
843 844 845 846 847 848 849
        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)

850 851 852 853 854 855 856 857 858 859 860 861
    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,
        },
    )
862 863 864
    return squeeze(unpool_out, [2])


865 866 867 868 869 870 871 872 873 874
def max_unpool2d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCHW",
    output_size=None,
    name=None,
):
875
    r"""
876
    This API implements max unpooling 2d opereation.
877
    See more details in :ref:`api_nn_pooling_MaxUnPool2D` .
878

879 880

    Args:
881
        x (Tensor): The input tensor of unpooling operator which is a 4-D tensor with
882
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"`,
883
                          where `N` is batch size, `C` is the number of channels,
884 885
                          `H` is the height of the feature, and `W` is the width of the
                          feature. The data type if float32 or float64.
886
        indices (Tensor): The indices given out by maxpooling2d which is a 4-D tensor with
887
                          shape [N, C, H, W]. The format of input tensor is `"NCHW"` ,
888 889 890 891 892 893 894 895
                          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.
896
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
897 898
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, padding).
899 900 901
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
902

903 904 905 906 907 908 909 910 911 912 913 914 915

        - 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:
916
            Tensor: The output tensor of unpooling result.
917 918 919 920

        Raises:
            ValueError: If the input is not a 4-D tensor.
            ValueError: If indeces shape is not equal input shape.
921

922 923 924

        Examples:
            .. code-block:: python
925

C
Chen Long 已提交
926 927
            import paddle
            import paddle.nn.functional as F
928

929
            data = paddle.rand(shape=[1,1,6,6])
930 931 932 933 934
            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]

935
            # specify a different output size than input size
936
            unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0, output_size=[7,7])
937
            # unpool_out shape: [1, 1, 7, 7]
938

939
    """
940 941 942 943 944 945 946 947 948
    if x.ndim != 4:
        raise ValueError(
            f'The x should have [N, C, H, W] format, but received {x.shape}.'
        )
    if indices.ndim != 4:
        raise ValueError(
            f'The indices should have [N, C, H, W] format, but received {indices.shape}.'
        )

949
    kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
950 951 952
    if stride is None:
        stride = kernel_size
    else:
953 954
        stride = convert_to_list(stride, 2, 'pool_stride')
    padding = convert_to_list(padding, 2, 'padding')
955 956

    if data_format not in ["NCHW"]:
957 958 959 960
        raise ValueError(
            "Attr(data_format) should be 'NCHW'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
961

962 963 964
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
965

X
xiaoting 已提交
966
    if in_dygraph_mode():
967 968 969
        output = _C_ops.unpool(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
970
        return output
X
xiaoting 已提交
971
    elif in_dynamic_mode():
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
        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,
        )
988 989 990 991 992 993 994
        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)

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    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,
        },
    )
1007 1008 1009
    return unpool_out


1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
def max_unpool3d(
    x,
    indices,
    kernel_size,
    stride=None,
    padding=0,
    data_format="NCDHW",
    output_size=None,
    name=None,
):
1020
    r"""
1021
    This API implements max unpooling 3d opereation.
1022 1023
    `max_unpool3d` accepts the output of `max_pool3d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1024 1025 1026 1027
    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
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    .. 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
1043
                          shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`,
1044
                          where `N` is batch size, `C` is the number of channels, `D` is
1045
                          the depth of the feature, `H` is the height of the feature,
1046 1047
                          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
1048
                          shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` ,
1049
                          where `N` is batch size, `C` is the number of channels, `D` is
1050
                          the depth of the feature, `H` is the height of the feature,
1051 1052 1053 1054 1055 1056
                          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.
1057
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
                           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:
1068
        Tensor: The output tensor of unpooling result.
1069 1070 1071

    Examples:
        .. code-block:: python
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            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]

    """
1083 1084 1085 1086 1087 1088 1089 1090 1091
    if x.ndim != 5:
        raise ValueError(
            f'The x should have [N, C, D, H, W] format, but received {x.shape}.'
        )
    if indices.ndim != 5:
        raise ValueError(
            f'The indices should have [N, C, D, H, W] format, but received {indices.shape}.'
        )

1092
    kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
1093 1094 1095
    if stride is None:
        stride = kernel_size
    else:
1096 1097
        stride = convert_to_list(stride, 3, 'pool_stride')
    padding = convert_to_list(padding, 3, 'padding')
1098 1099

    if data_format not in ["NCDHW"]:
1100 1101 1102 1103
        raise ValueError(
            "Attr(data_format) should be 'NCDHW'. Received "
            "Attr(data_format): %s." % str(data_format)
        )
1104

1105 1106 1107
    output_size = _unpool_output_size(
        x, kernel_size, stride, padding, output_size
    )
1108

X
xiaoting 已提交
1109
    if in_dygraph_mode():
1110 1111 1112
        output = _C_ops.unpool3d(
            x, indices, kernel_size, stride, padding, output_size, data_format
        )
1113
        return output
X
xiaoting 已提交
1114
    elif in_dynamic_mode():
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
        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,
        )
1131 1132 1133 1134 1135 1136 1137
        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)

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    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,
        },
    )
1150 1151 1152
    return unpool_out


1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
def max_pool2d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    data_format="NCHW",
    name=None,
):
W
Wei Shengyu 已提交
1163 1164 1165
    """
    This API implements max pooling 2d operation.
    See more details in :ref:`api_nn_pooling_MaxPool2d` .
W
Wei Shengyu 已提交
1166

W
Wei Shengyu 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    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 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

          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 已提交
1210
    """
W
Wei Shengyu 已提交
1211

1212
    kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
1213 1214 1215
    if stride is None:
        stride = kernel_size
    else:
1216
        stride = convert_to_list(stride, 2, 'pool_stride')
1217 1218 1219 1220

    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
1221 1222
            "Attr(data_format): %s." % str(data_format)
        )
1223 1224 1225

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

1226 1227 1228
    padding, padding_algorithm = _update_padding_nd(
        padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode
    )
1229

1230
    if data_format == "NHWC" and return_mask:
D
Double_V 已提交
1231
        raise ValueError(
1232
            "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d"
D
Double_V 已提交
1233 1234
        )

F
From00 已提交
1235 1236
    if in_dygraph_mode():
        if return_mask:
1237 1238 1239
            output = _C_ops.max_pool2d_with_index(
                x, kernel_size, stride, padding, False, False
            )
F
From00 已提交
1240 1241
            return output if return_mask else output[0]
        else:
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
            return _C_ops.pool2d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
            )
F
From00 已提交
1255

姜永久 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264
    else:
        op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
        helper = LayerHelper(op_type, **locals())
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'max_pool2d'
        )
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)

1265
        if return_mask:
姜永久 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            mask = helper.create_variable_for_type_inference("int32")
            outputs = {"Out": pool_out, "Mask": mask}

            helper.append_op(
                type="max_pool2d_with_index",
                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,
                },
1286
            )
姜永久 已提交
1287 1288
            return (pool_out, mask)

D
Double_V 已提交
1289
        else:
姜永久 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
            outputs = {"Out": pool_out}

            helper.append_op(
                type="pool2d",
                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,
                },
1309
            )
姜永久 已提交
1310
            return pool_out
1311 1312


1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
def max_pool3d(
    x,
    kernel_size,
    stride=None,
    padding=0,
    return_mask=False,
    ceil_mode=False,
    data_format="NCDHW",
    name=None,
):
1323
    """
1324 1325
    This API implements max pooling 2d operation.
    See more details in :ref:`api_nn_pooling_MaxPool3d` .
W
Wei Shengyu 已提交
1326

1327 1328
    Args:
        x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
D
Double_V 已提交
1329
                          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.
1330
        kernel_size (int|list|tuple): The pool kernel size. If the kernel size
1331
            is a tuple or list, it must contain three integers,
1332
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
1333
            Otherwise, the pool kernel size will be the cube of an int.
1334 1335
        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).
1336
            Otherwise, the pool stride size will be a cube of an int.
1337 1338 1339 1340 1341 1342 1343
        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.
1344
        ceil_mode (bool): ${ceil_mode_comment}
1345
        return_mask (bool): Whether to return the max indices along with the outputs. Default False. Only support "NDCHW" data_format.
1346 1347 1348 1349 1350 1351
        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.
1352

1353 1354
    Returns:
        Tensor: The output tensor of pooling result. The data type is same as input tensor.
W
Wei Shengyu 已提交
1355

1356 1357
    Examples:
        .. code-block:: python
1358

W
Wei Shengyu 已提交
1359 1360
          import paddle
          import paddle.nn.functional as F
1361

W
Wei Shengyu 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
          # 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]
1377
    """
W
Wei Shengyu 已提交
1378

1379
    kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
1380 1381 1382
    if stride is None:
        stride = kernel_size
    else:
1383
        stride = convert_to_list(stride, 3, 'pool_stride')
1384

1385
    channel_last = _channel_last(data_format, 3)
1386

1387 1388 1389
    padding, padding_algorithm = _update_padding_nd(
        padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
    )
1390

1391
    if data_format == "NDHWC" and return_mask:
D
Double_V 已提交
1392
        raise ValueError(
1393
            "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d"
D
Double_V 已提交
1394 1395
        )

F
From00 已提交
1396 1397
    if in_dygraph_mode():
        if return_mask:
1398 1399 1400
            output = _C_ops.max_pool3d_with_index(
                x, kernel_size, stride, padding, False, False
            )
F
From00 已提交
1401 1402
            return output if return_mask else output[0]
        else:
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
            return _C_ops.pool3d(
                x,
                kernel_size,
                stride,
                padding,
                ceil_mode,
                True,
                data_format,
                'max',
                False,
                False,
                padding_algorithm,
            )
F
From00 已提交
1416

姜永久 已提交
1417 1418 1419 1420 1421 1422 1423 1424
    else:
        op_type = "max_pool3d_with_index" if return_mask else "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)
        mask = helper.create_variable_for_type_inference('int32')
        outputs = {"Out": pool_out, "Mask": mask}
1425

姜永久 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
        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,
            },
        )
1444

姜永久 已提交
1445
        return (pool_out, mask) if return_mask else pool_out
1446 1447


1448
def adaptive_avg_pool1d(x, output_size, name=None):
1449
    """
1450 1451
    Adaptive average pooling 1d operation on :attr:`x` according to :attr:`output_size`.

1452 1453
    Notes:
        See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` .
D
Double_V 已提交
1454

1455
    Args:
1456 1457 1458
        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.
1459

1460
    Returns:
1461
        Tensor: The result of 1D adaptive average pooling. Its data type is same as input.
1462

1463 1464
    Examples:
        .. code-block:: python
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

            # 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])
1484 1485 1486
    """
    pool_type = 'avg'
    _check_input(x, 3)
1487
    pool_size = [1] + convert_to_list(output_size, 1, 'pool_size')
1488

1489
    x = unsqueeze(x, [2])
1490
    if in_dygraph_mode():
1491
        x = x._use_gpudnn(False)
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
        pool_out = _C_ops.pool2d(
            x,
            pool_size,
            [1, 1],
            [0, 0],
            False,
            True,
            "NCHW",
            pool_type,
            False,
            True,
            "EXPLICIT",
        )
1505
        return squeeze(pool_out, [2])
姜永久 已提交
1506 1507
    else:
        l_type = "pool2d"
1508 1509 1510 1511
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'adaptive_pool2d'
        )
        check_type(output_size, 'pool_size', (int), 'adaptive_pool1d')
姜永久 已提交
1512 1513 1514
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
1515

姜永久 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        outputs = {"Out": pool_out}
        helper.append_op(
            type=l_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
                "pooling_type": pool_type,
                "ksize": pool_size,
                "adaptive": True,
            },
        )
1527

姜永久 已提交
1528
        return squeeze(pool_out, [2])
1529 1530


1531
def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None):
1532
    r"""
1533

1534 1535
    Applies 2D adaptive avg pooling on input tensor. The h and w dimensions
    of the output tensor are determined by the parameter output_size.
1536

1537
    For avg adaptive pool2d:
1538

1539
    ..  math::
1540 1541 1542 1543
        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}) \\
1544
        Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
1545 1546 1547

    Args:
        x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
1548
                          The data type can be float32 or float64.
1549 1550 1551
        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.
1552
        data_format (str, optional): The data format of the input and output data. An optional string
1553 1554 1555 1556 1557
            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.
1558

1559
    Returns:
1560
        Tensor, The output tensor of avg adaptive pool2d result. The data type is same as input tensor.
1561

1562 1563
    Examples:
        .. code-block:: python
B
Bai Yifan 已提交
1564

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
            # 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
1581

1582
            x = paddle.rand([2, 3, 32, 32])
1583
            # x.shape is [2, 3, 32, 32]
1584
            out = paddle.nn.functional.adaptive_avg_pool2d(
1585 1586
                            x = x,
                            output_size=[3, 3])
1587
            # out.shape is [2, 3, 3, 3]
1588

1589 1590 1591 1592
    """
    if data_format not in ["NCHW", "NHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
1593 1594
            "Attr(data_format): %s." % str(data_format)
        )
1595 1596 1597 1598 1599 1600 1601

    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):
1602
        output_size = convert_to_list(output_size, 2, 'output_size')
1603
    else:
1604
        output_size = list(output_size)
1605
        if output_size[0] is None:
1606
            output_size[0] = in_h
1607
        if output_size[1] is None:
1608 1609
            output_size[1] = in_w

姜永久 已提交
1610
    if in_dygraph_mode():
1611 1612 1613 1614
        output_size = [
            item.numpy().item(0) if isinstance(item, Variable) else item
            for item in output_size
        ]
1615
    # output_size support Variable in static graph mode
1616 1617
    elif _contain_var(output_size):
        output_size = _convert_to_tensor_list(output_size)
1618

F
From00 已提交
1619
    if in_dygraph_mode():
1620
        x = x._use_gpudnn(False)
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        return _C_ops.pool2d(
            x,
            output_size,
            [1, 1],
            [0, 0],
            False,
            True,
            data_format,
            'avg',
            False,
            True,
            "EXPLICIT",
        )
F
From00 已提交
1634

姜永久 已提交
1635 1636
    else:
        l_type = 'pool2d'
1637 1638 1639 1640
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d'
        )
        check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')
姜永久 已提交
1641 1642 1643
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
1644

姜永久 已提交
1645
        outputs = {"Out": pool_out}
1646

姜永久 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
        helper.append_op(
            type=l_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
                "pooling_type": "avg",
                "ksize": output_size,
                "adaptive": True,
                "data_format": data_format,
            },
        )
1658

姜永久 已提交
1659
        return pool_out
1660 1661 1662


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

1665 1666
    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.
1667

1668
    For avg adaptive pool3d:
1669

1670
    ..  math::
1671 1672 1673 1674 1675 1676
        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}) \\
1677 1678
        Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
            {(dend - dstart) * (hend - hstart) * (wend - wstart)}
1679 1680 1681

    Args:
        x (Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor.
1682 1683 1684 1685 1686
            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
1687 1688
            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].
1689 1690 1691
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.

1692
    Returns:
1693
        Tensor, The output tensor of avg adaptive pool3d result. The data type is same as input tensor.
1694

1695 1696
    Examples:
        .. code-block:: python
B
Bai Yifan 已提交
1697

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
            # 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
1717 1718

            input_data = paddle.randn(shape=(2, 3, 8, 32, 32))
1719
            out = paddle.nn.functional.adaptive_avg_pool3d(
1720
                            x = input_data,
1721
                            output_size=[3, 3, 3])
1722
            # out.shape is [2, 3, 3, 3, 3]
1723

1724 1725 1726 1727
    """
    if data_format not in ["NCDHW", "NDHWC"]:
        raise ValueError(
            "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
1728 1729
            "Attr(data_format): %s." % str(data_format)
        )
1730 1731 1732 1733 1734 1735 1736

    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):
1737
        output_size = convert_to_list(output_size, 3, 'output_size')
1738
    else:
1739
        output_size = list(output_size)
1740
        if output_size[0] is None:
1741
            output_size[0] = in_l
1742
        if output_size[1] is None:
1743
            output_size[1] = in_h
1744
        if output_size[2] is None:
1745 1746
            output_size[2] = in_w

1747
    if in_dygraph_mode():
1748
        x = x._use_gpudnn(False)
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
        return _C_ops.pool3d(
            x,
            output_size,
            [1, 1, 1],
            [0, 0, 0],
            False,
            True,
            data_format,
            'avg',
            False,
            True,
            "EXPLICIT",
        )
姜永久 已提交
1762 1763
    else:
        l_type = 'pool3d'
1764

1765 1766 1767 1768 1769
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d'
        )
        check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')

姜永久 已提交
1770 1771 1772 1773
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
        outputs = {"Out": pool_out}
1774

姜永久 已提交
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        helper.append_op(
            type=l_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
                "pooling_type": "avg",
                "ksize": output_size,
                "adaptive": True,
                "data_format": data_format,
            },
        )
1786

姜永久 已提交
1787
        return pool_out
1788 1789


1790
def adaptive_max_pool1d(x, output_size, return_mask=False, name=None):
1791 1792 1793 1794 1795 1796 1797 1798 1799
    """
    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.
1800
        output_size (int): The pool kernel size. The value should be an integer.
1801
        return_mask (bool): If true, the index of max pooling point will be returned along
1802 1803 1804 1805 1806 1807 1808
                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.
1809

1810 1811
    Examples:
        .. code-block:: python
1812

1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
              # 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
1827

1828
              data = paddle.uniform([1, 3, 32], paddle.float32)
1829 1830
              pool_out = F.adaptive_max_pool1d(data, output_size=16)
              # pool_out shape: [1, 3, 16])
1831
              pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True)
1832 1833 1834 1835
              # pool_out shape: [1, 3, 16] indices  shape: [1, 3, 16]
    """
    _check_input(x, 3)

1836
    pool_size = [1] + convert_to_list(output_size, 1, 'pool_size')
1837 1838

    x = unsqueeze(x, [2])
1839
    if in_dygraph_mode():
1840 1841 1842 1843 1844 1845 1846 1847
        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])
        )
姜永久 已提交
1848 1849
    else:
        l_type = 'max_pool2d_with_index'
1850

1851 1852 1853 1854 1855 1856
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d'
        )
        check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d')
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d')

姜永久 已提交
1857 1858 1859
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
1860

姜永久 已提交
1861 1862
        mask = helper.create_variable_for_type_inference('int32')
        outputs = {"Out": pool_out, "Mask": mask}
1863

姜永久 已提交
1864 1865 1866 1867 1868
        helper.append_op(
            type=l_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
1869
                "pooling_type": 'max',
姜永久 已提交
1870 1871 1872 1873
                "ksize": pool_size,
                "adaptive": True,
            },
        )
1874

姜永久 已提交
1875 1876 1877 1878 1879
        return (
            (squeeze(pool_out, [2]), squeeze(mask, [2]))
            if return_mask
            else squeeze(pool_out, [2])
        )
1880 1881


1882
def adaptive_max_pool2d(x, output_size, return_mask=False, name=None):
1883
    """
1884 1885
    This operation applies a 2D adaptive max pooling on input tensor.
    See more details in :ref:`api_nn_pooling_AdaptiveMaxPool2d` .
1886

1887 1888 1889 1890 1891
    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.
1892

1893 1894
    Returns:
        Tensor: The output tensor of adaptive max pool2d result. The data type is same as input tensor.
1895

1896 1897
    Examples:
        .. code-block:: python
1898

1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
          # 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
1915

1916 1917 1918 1919 1920
          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]
1921 1922 1923 1924 1925
    """
    _check_input(x, 4)

    in_h, in_w = x.shape[2:4]
    if isinstance(output_size, int):
1926
        output_size = convert_to_list(output_size, 2, 'output_size')
1927
    else:
1928
        output_size = list(output_size)
1929
        if output_size[0] is None:
1930
            output_size[0] = in_h
1931
        if output_size[1] is None:
1932
            output_size[1] = in_w
1933
    if in_dygraph_mode():
1934 1935 1936
        pool_out = _C_ops.max_pool2d_with_index(
            x, output_size, [1, 1], [0, 0], False, True
        )
1937
        return pool_out if return_mask else pool_out[0]
姜永久 已提交
1938 1939
    else:
        l_type = 'max_pool2d_with_index'
1940

1941 1942 1943 1944 1945 1946
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d'
        )
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d')
        # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d')

姜永久 已提交
1947 1948 1949
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
1950

姜永久 已提交
1951 1952
        mask = helper.create_variable_for_type_inference('int32')
        outputs = {"Out": pool_out, "Mask": mask}
1953

姜永久 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
        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
        return pool_out
1966 1967


1968
def adaptive_max_pool3d(x, output_size, return_mask=False, name=None):
1969
    """
1970 1971
    This operation applies a 3D adaptive max pooling on input tensor.
    See more details in :ref:`api_nn_pooling_AdaptiveMaxPool3d` .
1972

1973 1974 1975 1976 1977
    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.
1978

1979 1980
    Returns:
        Tensor: The output tensor of adaptive max pool3d result. The data type is same as input tensor.
1981

1982 1983
    Examples:
        .. code-block:: python
1984

1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
          # 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
2004

2005 2006 2007 2008 2009
          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]
2010 2011 2012 2013 2014
    """
    _check_input(x, 5)

    in_l, in_h, in_w = x.shape[2:5]
    if isinstance(output_size, int):
2015
        output_size = convert_to_list(output_size, 3, 'output_size')
2016
    else:
2017
        output_size = list(output_size)
2018
        if output_size[0] is None:
2019
            output_size[0] = in_l
2020
        if output_size[1] is None:
2021
            output_size[1] = in_h
2022
        if output_size[2] is None:
2023 2024
            output_size[2] = in_w

姜永久 已提交
2025 2026 2027 2028 2029
    if in_dygraph_mode():
        # By default, strides is [1,1,1] and paddings is [0, 0, 0]
        pool_out = _C_ops.max_pool3d_with_index(
            x, output_size, [1, 1, 1], [0, 0, 0], False, True
        )
2030
        return pool_out if return_mask else pool_out[0]
姜永久 已提交
2031 2032
    else:
        l_type = 'max_pool3d_with_index'
2033

2034 2035 2036 2037 2038 2039
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d'
        )
        check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d')
        # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d')

姜永久 已提交
2040 2041 2042
        helper = LayerHelper(l_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        pool_out = helper.create_variable_for_type_inference(dtype)
2043

姜永久 已提交
2044 2045
        mask = helper.create_variable_for_type_inference('int32')
        outputs = {"Out": pool_out, "Mask": mask}
2046

姜永久 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
        helper.append_op(
            type=l_type,
            inputs={"X": x},
            outputs=outputs,
            attrs={
                "pooling_type": 'max',
                "ksize": output_size,
                "adaptive": True,
            },
        )
2057

姜永久 已提交
2058
        return (pool_out, mask) if return_mask else pool_out