test_pool2d_op.py 50.3 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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 __future__ import print_function
16
from __future__ import division
17

C
chengduoZH 已提交
18 19
import unittest
import numpy as np
20

21
import paddle.fluid.core as core
A
arlesniak 已提交
22
from paddle.fluid.tests.unittests.op_test import OpTest
23
import paddle.fluid as fluid
24
from paddle.fluid import Program, program_guard
C
chengduoZH 已提交
25 26


27 28 29 30 31 32 33 34
def adaptive_start_index(index, input_size, output_size):
    return int(np.floor(index * input_size / output_size))


def adaptive_end_index(index, input_size, output_size):
    return int(np.ceil((index + 1) * input_size / output_size))


35 36 37 38 39
def max_pool2D_forward_naive(x,
                             ksize,
                             strides,
                             paddings,
                             global_pool=0,
40
                             ceil_mode=False,
41
                             exclusive=True,
42
                             adaptive=False,
43
                             data_type=np.float64):
44 45
    if data_type == np.float64 and core.is_compiled_with_rocm():
        data_type = np.float32
C
chengduoZH 已提交
46
    N, C, H, W = x.shape
C
chengduoZH 已提交
47 48
    if global_pool == 1:
        ksize = [H, W]
49 50 51
    if adaptive:
        H_out, W_out = ksize
    else:
52 53
        H_out = (H - ksize[0] + 2 * paddings[0] + strides[0] -
                 1) // strides[0] + 1 if ceil_mode else (
54
                     H - ksize[0] + 2 * paddings[0]) // strides[0] + 1
55 56
        W_out = (W - ksize[1] + 2 * paddings[1] + strides[1] -
                 1) // strides[1] + 1 if ceil_mode else (
57
                     W - ksize[1] + 2 * paddings[1]) // strides[1] + 1
C
chengduoZH 已提交
58
    out = np.zeros((N, C, H_out, W_out))
59 60
    for i in range(H_out):
        for j in range(W_out):
61 62 63 64 65 66 67 68 69 70
            if adaptive:
                r_start = adaptive_start_index(i, H, ksize[0])
                r_end = adaptive_end_index(i, H, ksize[0])
                c_start = adaptive_start_index(j, W, ksize[1])
                c_end = adaptive_end_index(j, W, ksize[1])
            else:
                r_start = np.max((i * strides[0] - paddings[0], 0))
                r_end = np.min((i * strides[0] + ksize[0] - paddings[0], H))
                c_start = np.max((j * strides[1] - paddings[1], 0))
                c_end = np.min((j * strides[1] + ksize[1] - paddings[1], W))
C
chengduoZH 已提交
71 72 73 74 75 76
            x_masked = x[:, :, r_start:r_end, c_start:c_end]

            out[:, :, i, j] = np.max(x_masked, axis=(2, 3))
    return out


77 78 79 80 81
def avg_pool2D_forward_naive(x,
                             ksize,
                             strides,
                             paddings,
                             global_pool=0,
82
                             ceil_mode=False,
83
                             exclusive=True,
84
                             adaptive=False,
85
                             data_type=np.float64):
86 87
    if data_type == np.float64 and core.is_compiled_with_rocm():
        data_type = np.float32
C
chengduoZH 已提交
88
    N, C, H, W = x.shape
C
chengduoZH 已提交
89 90
    if global_pool == 1:
        ksize = [H, W]
91 92 93
    if adaptive:
        H_out, W_out = ksize
    else:
94 95
        H_out = (H - ksize[0] + 2 * paddings[0] + strides[0] -
                 1) // strides[0] + 1 if ceil_mode else (
96
                     H - ksize[0] + 2 * paddings[0]) // strides[0] + 1
97 98
        W_out = (W - ksize[1] + 2 * paddings[1] + strides[1] -
                 1) // strides[1] + 1 if ceil_mode else (
99
                     W - ksize[1] + 2 * paddings[1]) // strides[1] + 1
C
chengduoZH 已提交
100
    out = np.zeros((N, C, H_out, W_out))
101 102
    for i in range(H_out):
        for j in range(W_out):
103 104 105 106 107 108
            if adaptive:
                r_start = adaptive_start_index(i, H, ksize[0])
                r_end = adaptive_end_index(i, H, ksize[0])
                c_start = adaptive_start_index(j, W, ksize[1])
                c_end = adaptive_end_index(j, W, ksize[1])
            else:
D
Double_V 已提交
109 110 111 112 113 114 115 116 117 118
                r_start = i * strides[0] - paddings[0]
                r_end = i * strides[0] + ksize[0] - paddings[0]
                c_start = j * strides[1] - paddings[1]
                c_end = j * strides[1] + ksize[1] - paddings[1]
                field_size = (r_end - r_start) * (c_end - c_start)
                r_start = np.max((r_start, 0))
                r_end = np.min((r_end, H))
                c_start = np.max((c_start, 0))
                c_end = np.min((c_end, W))

C
chengduoZH 已提交
119 120
            x_masked = x[:, :, r_start:r_end, c_start:c_end]

D
Double_V 已提交
121 122 123
            if (exclusive or adaptive):
                field_size = (r_end - r_start) * (c_end - c_start)

124
            if data_type == np.int8 or data_type == np.uint8:
125 126 127
                out[:, :, i,
                    j] = (np.rint(np.sum(x_masked, axis=(2, 3)) /
                                  field_size)).astype(data_type)
128 129 130
            else:
                out[:, :, i, j] = (np.sum(x_masked, axis=(2, 3)) /
                                   field_size).astype(data_type)
C
chengduoZH 已提交
131 132 133
    return out


134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
def pool2D_forward_naive(x,
                         ksize,
                         strides,
                         paddings,
                         global_pool=0,
                         ceil_mode=False,
                         exclusive=True,
                         adaptive=False,
                         data_format='NCHW',
                         pool_type="max",
                         padding_algorithm="EXPLICIT"):

    # update paddings
    def _get_padding_with_SAME(input_shape, pool_size, pool_stride):
        padding = []
        for input_size, filter_size, stride_size in zip(input_shape, pool_size,
                                                        pool_stride):
            out_size = int((input_size + stride_size - 1) / stride_size)
152 153
            pad_sum = np.max(
                ((out_size - 1) * stride_size + filter_size - input_size, 0))
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
            pad_0 = int(pad_sum / 2)
            pad_1 = int(pad_sum - pad_0)
            padding.append(pad_0)
            padding.append(pad_1)
        return padding

    if isinstance(padding_algorithm, str):
        padding_algorithm = padding_algorithm.upper()
        if padding_algorithm not in ["SAME", "VALID", "EXPLICIT"]:
            raise ValueError("Unknown Attr(padding_algorithm): '%s'. "
                             "It can only be 'SAME' or 'VALID'." %
                             str(padding_algorithm))

        if padding_algorithm == "VALID":
            paddings = [0, 0, 0, 0]
            if ceil_mode != False:
                raise ValueError(
                    "When Attr(pool_padding) is \"VALID\", Attr(ceil_mode)"
                    " must be False. "
                    "Received ceil_mode: True.")
        elif padding_algorithm == "SAME":
            input_data_shape = []
            if data_format == "NCHW":
                input_data_shape = x.shape[2:4]
            elif data_format == "NHWC":
                input_data_shape = x.shape[1:3]
            paddings = _get_padding_with_SAME(input_data_shape, ksize, strides)

    assert len(paddings) == 2 or len(paddings) == 4
    is_sys = True if len(paddings) == 2 else False

    N = x.shape[0]
    C, H, W = [x.shape[1], x.shape[2], x.shape[3]] if data_format == 'NCHW' \
        else [x.shape[3], x.shape[1], x.shape[2]]

    if global_pool == 1:
        ksize = [H, W]
        paddings = [0 for _ in range(len(paddings))]

    pad_h_up = paddings[0] if is_sys else paddings[0]
    pad_h_down = paddings[0] if is_sys else paddings[1]
    pad_w_left = paddings[1] if is_sys else paddings[2]
    pad_w_right = paddings[1] if is_sys else paddings[3]

    if adaptive:
        H_out, W_out = ksize
    else:
        H_out = (H - ksize[0] + pad_h_up + pad_h_down + strides[0] - 1) // strides[0] + 1 \
            if ceil_mode else (H - ksize[0] + pad_h_up + pad_h_down) // strides[0] + 1
        W_out = (W - ksize[1] + pad_w_left + pad_w_right + strides[1] - 1) // strides[1] + 1 \
            if ceil_mode else (W - ksize[1] + pad_w_left + pad_w_right) // strides[1] + 1

    out = np.zeros((N, C, H_out, W_out)) if data_format=='NCHW' \
        else np.zeros((N, H_out, W_out, C))
    for i in range(H_out):
        if adaptive:
            in_h_start = adaptive_start_index(i, H, ksize[0])
            in_h_end = adaptive_end_index(i, H, ksize[0])
        else:
            in_h_start = np.max((i * strides[0] - pad_h_up, 0))
            in_h_end = np.min((i * strides[0] + ksize[0] - pad_h_up, H))

        for j in range(W_out):
            if adaptive:
                in_w_start = adaptive_start_index(j, W, ksize[1])
                in_w_end = adaptive_end_index(j, W, ksize[1])
            else:
D
Double_V 已提交
221 222 223 224 225 226 227 228 229 230
                in_h_start = i * strides[0] - pad_h_up
                in_w_start = j * strides[1] - pad_w_left
                in_h_end = i * strides[0] + ksize[0] - pad_h_up
                in_w_end = j * strides[1] + ksize[1] - pad_w_left

                field_size = (in_h_end - in_h_start) * (in_w_end - in_w_start)
                in_h_start = np.max((in_h_start, 0))
                in_w_start = np.max((in_w_start, 0))
                in_h_end = np.min((in_h_end, H))
                in_w_end = np.min((in_w_end, W))
231 232 233 234

            if data_format == 'NCHW':
                x_masked = x[:, :, in_h_start:in_h_end, in_w_start:in_w_end]
                if pool_type == 'avg':
D
Double_V 已提交
235
                    if (exclusive or adaptive):
236 237 238
                        field_size = (in_h_end - in_h_start) * (in_w_end -
                                                                in_w_start)

D
Double_V 已提交
239 240

#                         if (exclusive or adaptive) else (ksize[0] * ksize[1])
241 242 243 244 245 246
                    out[:, :, i, j] = np.sum(x_masked, axis=(2, 3)) / field_size
                elif pool_type == 'max':
                    out[:, :, i, j] = np.max(x_masked, axis=(2, 3))
            elif data_format == 'NHWC':
                x_masked = x[:, in_h_start:in_h_end, in_w_start:in_w_end, :]
                if pool_type == 'avg':
D
Double_V 已提交
247
                    if (exclusive or adaptive):
248 249
                        field_size = (in_h_end - in_h_start) * (in_w_end -
                                                                in_w_start)
250 251 252 253 254 255
                    out[:, i, j, :] = np.sum(x_masked, axis=(1, 2)) / field_size
                elif pool_type == 'max':
                    out[:, i, j, :] = np.max(x_masked, axis=(1, 2))
    return out


A
arlesniak 已提交
256
class TestPool2D_Op_Mixin(object):
257

C
chengduoZH 已提交
258
    def setUp(self):
K
Kexin Zhao 已提交
259
        self.op_type = "pool2d"
260
        self.use_cudnn = False
261
        self.init_kernel_type()
262
        self.use_mkldnn = False
X
xiaolil1 已提交
263
        self.init_data_type()
C
chengduoZH 已提交
264
        self.init_test_case()
265 266
        self.padding_algorithm = "EXPLICIT"
        self.init_paddings()
C
chengduoZH 已提交
267
        self.init_global_pool()
K
Kexin Zhao 已提交
268
        self.init_kernel_type()
C
chengduoZH 已提交
269
        self.init_pool_type()
270
        self.init_ceil_mode()
271
        self.init_exclusive()
272
        self.init_adaptive()
273 274 275
        self.init_data_format()
        self.init_shape()

K
Kexin Zhao 已提交
276
        input = np.random.random(self.shape).astype(self.dtype)
277 278 279 280 281 282
        output = pool2D_forward_naive(input, self.ksize, self.strides,
                                      self.paddings, self.global_pool,
                                      self.ceil_mode, self.exclusive,
                                      self.adaptive, self.data_format,
                                      self.pool_type,
                                      self.padding_algorithm).astype(self.dtype)
K
Kexin Zhao 已提交
283
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(input)}
C
chengduoZH 已提交
284 285 286 287 288

        self.attrs = {
            'strides': self.strides,
            'paddings': self.paddings,
            'ksize': self.ksize,
C
chengduoZH 已提交
289 290
            'pooling_type': self.pool_type,
            'global_pooling': self.global_pool,
291
            'use_cudnn': self.use_cudnn,
292
            'use_mkldnn': self.use_mkldnn,
293
            'ceil_mode': self.ceil_mode,
294
            'data_format': self.data_format,
295
            'exclusive': self.exclusive,
296 297
            'adaptive': self.adaptive,
            "padding_algorithm": self.padding_algorithm,
C
chengduoZH 已提交
298 299
        }

K
Kexin Zhao 已提交
300
        self.outputs = {'Out': output}
C
chengduoZH 已提交
301

302
    def has_cudnn(self):
303 304
        return core.is_compiled_with_cuda() and self.use_cudnn

C
chengduoZH 已提交
305
    def test_check_output(self):
306
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
307
        if self.has_cudnn():
308
            place = core.CUDAPlace(0)
309 310
            self.check_output_with_place(
                place, atol=1e-5, check_dygraph=(self.use_mkldnn == False))
311
        else:
312
            self.check_output(check_dygraph=(self.use_mkldnn == False))
C
chengduoZH 已提交
313 314

    def test_check_grad(self):
K
Kexin Zhao 已提交
315 316
        if self.dtype == np.float16:
            return
317
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
318
        if self.has_cudnn() and self.pool_type != "max":
319
            place = core.CUDAPlace(0)
320 321 322 323 324
            self.check_grad_with_place(place,
                                       set(['X']),
                                       'Out',
                                       max_relative_error=0.07,
                                       check_dygraph=(self.use_mkldnn == False))
325
        elif self.pool_type != "max":
326 327 328 329
            self.check_grad(set(['X']),
                            'Out',
                            max_relative_error=0.07,
                            check_dygraph=(self.use_mkldnn == False))
C
chengduoZH 已提交
330

331 332 333 334
    def init_data_format(self):
        self.data_format = "NCHW"

    def init_shape(self):
C
chengduoZH 已提交
335
        self.shape = [2, 3, 5, 5]
336 337

    def init_test_case(self):
C
chengduoZH 已提交
338 339
        self.ksize = [3, 3]
        self.strides = [1, 1]
340 341

    def init_paddings(self):
C
chengduoZH 已提交
342
        self.paddings = [0, 0]
343
        self.padding_algorithm = "EXPLICIT"
C
chengduoZH 已提交
344

K
Kexin Zhao 已提交
345
    def init_kernel_type(self):
346
        self.use_cudnn = False
C
chengduoZH 已提交
347

X
xiaolil1 已提交
348
    def init_data_type(self):
349
        self.dtype = np.float32 if core.is_compiled_with_rocm() else np.float64
X
xiaolil1 已提交
350

C
chengduoZH 已提交
351 352
    def init_pool_type(self):
        self.pool_type = "avg"
C
chengduoZH 已提交
353 354 355 356
        self.pool2D_forward_naive = avg_pool2D_forward_naive

    def init_global_pool(self):
        self.global_pool = True
C
chengduoZH 已提交
357

358 359 360
    def init_ceil_mode(self):
        self.ceil_mode = False

361 362 363
    def init_exclusive(self):
        self.exclusive = True

364 365 366
    def init_adaptive(self):
        self.adaptive = False

C
chengduoZH 已提交
367

A
arlesniak 已提交
368 369 370 371
class TestPool2D_Op(TestPool2D_Op_Mixin, OpTest):
    pass


C
chengduo 已提交
372
class TestCase1(TestPool2D_Op):
373

C
chengduoZH 已提交
374
    def init_test_case(self):
C
chengduoZH 已提交
375 376
        self.ksize = [3, 3]
        self.strides = [1, 1]
377 378

    def init_paddings(self):
C
chengduoZH 已提交
379
        self.paddings = [0, 0]
C
chengduoZH 已提交
380

C
chengduoZH 已提交
381 382
    def init_pool_type(self):
        self.pool_type = "avg"
C
chengduoZH 已提交
383 384 385 386
        self.pool2D_forward_naive = avg_pool2D_forward_naive

    def init_global_pool(self):
        self.global_pool = False
C
chengduoZH 已提交
387

388 389 390
    def init_shape(self):
        self.shape = [2, 3, 7, 7]

C
chengduoZH 已提交
391

C
chengduo 已提交
392
class TestCase2(TestPool2D_Op):
393

C
chengduoZH 已提交
394
    def init_test_case(self):
C
chengduoZH 已提交
395 396
        self.ksize = [3, 3]
        self.strides = [1, 1]
397 398

    def init_paddings(self):
C
chengduoZH 已提交
399 400
        self.paddings = [1, 1]

C
chengduoZH 已提交
401 402
    def init_pool_type(self):
        self.pool_type = "avg"
C
chengduoZH 已提交
403
        self.pool2D_forward_naive = avg_pool2D_forward_naive
C
chengduoZH 已提交
404

C
chengduoZH 已提交
405 406
    def init_global_pool(self):
        self.global_pool = False
C
chengduoZH 已提交
407

408 409 410
    def init_shape(self):
        self.shape = [2, 3, 7, 7]

C
chengduoZH 已提交
411

C
chengduo 已提交
412
class TestCase3(TestPool2D_Op):
413

C
chengduoZH 已提交
414 415
    def init_pool_type(self):
        self.pool_type = "max"
C
chengduoZH 已提交
416
        self.pool2D_forward_naive = max_pool2D_forward_naive
C
chengduoZH 已提交
417

C
chengduoZH 已提交
418 419

class TestCase4(TestCase1):
420

C
chengduoZH 已提交
421 422 423 424
    def init_pool_type(self):
        self.pool_type = "max"
        self.pool2D_forward_naive = max_pool2D_forward_naive

C
chengduoZH 已提交
425 426

class TestCase5(TestCase2):
427

C
chengduoZH 已提交
428 429
    def init_pool_type(self):
        self.pool_type = "max"
C
chengduoZH 已提交
430
        self.pool2D_forward_naive = max_pool2D_forward_naive
C
chengduoZH 已提交
431 432


C
chengduo 已提交
433
#--------------------test pool2d cudnn--------------------
C
chengduoZH 已提交
434 435


C
chengduo 已提交
436
def create_test_cudnn_class(parent):
437

C
chengduo 已提交
438 439 440
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestCUDNNCase(parent):
441

C
chengduo 已提交
442 443
        def init_kernel_type(self):
            self.use_cudnn = True
K
Kexin Zhao 已提交
444

C
chengduo 已提交
445 446 447
    cls_name = "{0}_{1}".format(parent.__name__, "CUDNNOp")
    TestCUDNNCase.__name__ = cls_name
    globals()[cls_name] = TestCUDNNCase
K
Kexin Zhao 已提交
448 449


C
chengduo 已提交
450 451 452 453 454 455
create_test_cudnn_class(TestPool2D_Op)
create_test_cudnn_class(TestCase1)
create_test_cudnn_class(TestCase2)
create_test_cudnn_class(TestCase3)
create_test_cudnn_class(TestCase4)
create_test_cudnn_class(TestCase5)
C
chengduoZH 已提交
456

C
chengduo 已提交
457
#--------------------test pool2d cudnn_fp16--------------------
C
chengduoZH 已提交
458

K
Kexin Zhao 已提交
459

C
chengduo 已提交
460
def create_test_cudnn_fp16_class(parent, check_grad=True):
461

C
chengduo 已提交
462 463 464
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestCUDNNFp16Case(parent):
465

C
chengduo 已提交
466 467 468
        def init_kernel_type(self):
            self.use_cudnn = True
            self.dtype = np.float16
K
Kexin Zhao 已提交
469

C
chengduo 已提交
470
        def test_check_output(self):
471
            # TODO(wangzhongpu): support mkldnn op in dygraph mode
C
chengduo 已提交
472 473 474
            if core.is_compiled_with_cuda():
                place = core.CUDAPlace(0)
                if core.is_float16_supported(place):
475 476 477 478
                    self.check_output_with_place(
                        place,
                        atol=1e-3,
                        check_dygraph=(self.use_mkldnn == False))
K
Kexin Zhao 已提交
479

C
chengduo 已提交
480
        def test_check_grad(self):
481
            # TODO(wangzhongpu): support mkldnn op in dygraph mode
K
Kexin Zhao 已提交
482
            place = core.CUDAPlace(0)
C
chengduo 已提交
483 484 485
            if core.is_float16_supported(
                    place) and self.pool_type != "max" and check_grad:
                self.check_grad_with_place(
486 487 488 489 490
                    place,
                    set(['X']),
                    'Out',
                    max_relative_error=0.07,
                    check_dygraph=(self.use_mkldnn == False))
K
Kexin Zhao 已提交
491

C
chengduo 已提交
492 493 494
    cls_name = "{0}_{1}".format(parent.__name__, "CUDNNFp16Op")
    TestCUDNNFp16Case.__name__ = cls_name
    globals()[cls_name] = TestCUDNNFp16Case
K
Kexin Zhao 已提交
495

C
chengduoZH 已提交
496

497
def create_test_fp16_class(parent, check_grad=True):
498

499 500 501
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestFp16Case(parent):
502

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        def init_kernel_type(self):
            self.use_cudnn = False
            self.dtype = np.float16

        def test_check_output(self):
            # TODO(wangzhongpu): support mkldnn op in dygraph mode
            if core.is_compiled_with_cuda():
                place = core.CUDAPlace(0)
                if core.is_float16_supported(place):
                    self.check_output_with_place(
                        place,
                        atol=1e-3,
                        check_dygraph=(self.use_mkldnn == False))

        def test_check_grad(self):
            # TODO(wangzhongpu): support mkldnn op in dygraph mode
            place = core.CUDAPlace(0)
            if core.is_float16_supported(
                    place) and self.pool_type != "max" and check_grad:
                self.check_grad_with_place(
                    place,
                    set(['X']),
                    'Out',
                    max_relative_error=0.07,
                    check_dygraph=(self.use_mkldnn == False))

    cls_name = "{0}_{1}".format(parent.__name__, "Fp16Op")
    TestFp16Case.__name__ = cls_name
    globals()[cls_name] = TestFp16Case


C
chengduo 已提交
534 535 536 537 538 539
create_test_cudnn_fp16_class(TestPool2D_Op)
create_test_cudnn_fp16_class(TestCase1, check_grad=False)
create_test_cudnn_fp16_class(TestCase2)
create_test_cudnn_fp16_class(TestCase3)
create_test_cudnn_fp16_class(TestCase4)
create_test_cudnn_fp16_class(TestCase5)
C
chengduoZH 已提交
540

541 542 543 544 545 546 547
create_test_fp16_class(TestPool2D_Op)
create_test_fp16_class(TestCase1, check_grad=False)
create_test_fp16_class(TestCase2)
create_test_fp16_class(TestCase3)
create_test_fp16_class(TestCase4)
create_test_fp16_class(TestCase5)

C
chengduo 已提交
548
#--------------------test pool2d use ceil mode--------------------
K
Kexin Zhao 已提交
549 550


C
chengduo 已提交
551
def create_test_cudnn_use_ceil_class(parent):
552

C
chengduo 已提交
553 554 555
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestPool2DUseCeilCase(parent):
556

C
chengduo 已提交
557 558
        def init_kernel_type(self):
            self.use_cudnn = True
K
Kexin Zhao 已提交
559

C
chengduo 已提交
560 561
        def init_ceil_mode(self):
            self.ceil_mode = True
C
chengduoZH 已提交
562

C
chengduo 已提交
563 564 565
    cls_name = "{0}_{1}".format(parent.__name__, "CUDNNOpCeilMode")
    TestPool2DUseCeilCase.__name__ = cls_name
    globals()[cls_name] = TestPool2DUseCeilCase
K
Kexin Zhao 已提交
566 567


C
chengduo 已提交
568 569
create_test_cudnn_use_ceil_class(TestPool2D_Op)
create_test_cudnn_use_ceil_class(TestCase1)
K
Kexin Zhao 已提交
570

571

C
chengduo 已提交
572
def create_test_use_ceil_class(parent):
573

C
chengduo 已提交
574
    class TestPool2DUseCeilCase(parent):
575

C
chengduo 已提交
576 577
        def init_ceil_mode(self):
            self.ceil_mode = True
578

C
chengduo 已提交
579 580 581
    cls_name = "{0}_{1}".format(parent.__name__, "CeilModeCast")
    TestPool2DUseCeilCase.__name__ = cls_name
    globals()[cls_name] = TestPool2DUseCeilCase
582 583


C
chengduo 已提交
584 585
create_test_use_ceil_class(TestCase1)
create_test_use_ceil_class(TestCase2)
586

587

588
class TestAvgInclude(TestCase2):
589

590 591 592
    def init_exclusive(self):
        self.exclusive = False

593

C
chengduo 已提交
594
class TestCUDNNAvgInclude(TestCase2):
595

C
chengduo 已提交
596 597 598
    def init_kernel_type(self):
        self.use_cudnn = True

599 600 601
    def init_exclusive(self):
        self.exclusive = False

602

603
class TestAvgPoolAdaptive(TestCase1):
604

605 606 607 608
    def init_adaptive(self):
        self.adaptive = True


609
class TestAvgPoolAdaptiveAsyOutSize(TestCase1):
610

611 612 613 614 615 616 617 618 619 620 621 622
    def init_adaptive(self):
        self.adaptive = True

    def init_shape(self):
        self.shape = [8, 3, 6, 6]

    def init_test_case(self):
        self.ksize = [2, 3]
        self.strides = [1, 1]
        self.paddings = [0, 0, 0, 0]


623 624 625 626
#-------test pool2d with asymmetric padding-----


class TestPool2D_AsyPadding(TestPool2D_Op):
627

628 629 630 631 632 633 634 635 636 637
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 0, 1, 2]

    def init_shape(self):
        self.shape = [2, 3, 5, 5]


class TestCase1_AsyPadding(TestCase1):
638

639 640 641 642 643 644 645 646 647 648
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 0, 1, 0]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


class TestCase2_AsyPadding(TestCase2):
649

650 651 652 653 654 655 656 657 658 659
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 2, 1, 2]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


class TestCase3_AsyPadding(TestCase3):
660

661 662 663 664 665 666 667 668 669 670
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 0, 1, 2]

    def init_shape(self):
        self.shape = [2, 3, 5, 5]


class TestCase4_AsyPadding(TestCase4):
671

672 673 674 675 676 677 678 679 680 681
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 0, 1, 0]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


class TestCase5_AsyPadding((TestCase5)):
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [2, 2, 1, 2]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


create_test_cudnn_class(TestPool2D_AsyPadding)
create_test_cudnn_class(TestCase1_AsyPadding)
create_test_cudnn_class(TestCase2_AsyPadding)
create_test_cudnn_class(TestCase3_AsyPadding)
create_test_cudnn_class(TestCase4_AsyPadding)
create_test_cudnn_class(TestCase5_AsyPadding)

create_test_cudnn_fp16_class(TestPool2D_AsyPadding)
create_test_cudnn_fp16_class(TestCase1_AsyPadding, check_grad=False)
create_test_cudnn_fp16_class(TestCase2_AsyPadding)
create_test_cudnn_fp16_class(TestCase3_AsyPadding)
create_test_cudnn_fp16_class(TestCase4_AsyPadding)
create_test_cudnn_fp16_class(TestCase5_AsyPadding)

create_test_cudnn_use_ceil_class(TestPool2D_AsyPadding)
create_test_cudnn_use_ceil_class(TestCase1_AsyPadding)

create_test_use_ceil_class(TestCase1_AsyPadding)
create_test_use_ceil_class(TestCase2_AsyPadding)


class TestAvgInclude_AsyPadding(TestCase2):
714

715 716 717 718 719 720 721 722 723 724 725 726 727
    def init_exclusive(self):
        self.exclusive = False

    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 2, 1, 2]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


class TestCUDNNAvgInclude_AsyPadding(TestCase2):
728

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    def init_kernel_type(self):
        self.use_cudnn = True

    def init_exclusive(self):
        self.exclusive = False

    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [2, 1, 1, 1]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


class TestAvgPoolAdaptive_AsyPadding(TestCase1):
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759
    def init_adaptive(self):
        self.adaptive = True

    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 1]
        self.paddings = [1, 1, 0, 2]

    def init_shape(self):
        self.shape = [2, 3, 7, 7]


#----------- test channel_last --------------
class TestPool2D_channel_last(TestPool2D_Op):
760

761 762 763 764 765 766 767 768
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 5, 5, 3]


class TestCase1_channel_last(TestCase1):
769

770 771 772 773 774 775 776 777
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase2_channel_last(TestCase2):
778

779 780 781 782 783 784 785 786
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase3_channel_last(TestCase3):
787

788 789 790 791 792 793 794 795
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 5, 5, 3]


class TestCase4_channel_last(TestCase4):
796

797 798 799 800 801 802 803 804
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase5_channel_last(TestCase5):
805

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


create_test_cudnn_class(TestPool2D_channel_last)
create_test_cudnn_class(TestCase1_channel_last)
create_test_cudnn_class(TestCase2_channel_last)
create_test_cudnn_class(TestCase3_channel_last)
create_test_cudnn_class(TestCase4_channel_last)
create_test_cudnn_class(TestCase5_channel_last)

create_test_cudnn_fp16_class(TestPool2D_channel_last)
create_test_cudnn_fp16_class(TestCase1_channel_last, check_grad=False)
create_test_cudnn_fp16_class(TestCase2_channel_last)
create_test_cudnn_fp16_class(TestCase3_channel_last)
create_test_cudnn_fp16_class(TestCase4_channel_last)
create_test_cudnn_fp16_class(TestCase5_channel_last)

create_test_cudnn_use_ceil_class(TestPool2D_channel_last)
create_test_cudnn_use_ceil_class(TestCase1_channel_last)

create_test_use_ceil_class(TestCase1_channel_last)
create_test_use_ceil_class(TestCase2_channel_last)


class TestCase5_Max(TestCase2):
835

836 837 838 839 840 841 842 843
    def init_pool_type(self):
        self.pool_type = "max"

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        if self.has_cudnn() and self.pool_type == "max":
            place = core.CUDAPlace(0)
844 845 846 847
            self.check_grad_with_place(place,
                                       set(['X']),
                                       'Out',
                                       max_relative_error=1.00)
848 849 850 851 852
        elif self.pool_type == "max":
            self.check_grad(set(['X']), 'Out', max_relative_error=1.00)


class TestCase5_channel_last_Max(TestCase5_Max):
853

854 855 856 857 858 859 860 861 862 863 864 865
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


create_test_cudnn_class(TestCase5_Max)
create_test_cudnn_class(TestCase5_channel_last_Max)


class TestAvgInclude_channel_last(TestCase2_channel_last):
866

867 868 869 870 871
    def init_exclusive(self):
        self.exclusive = False


class TestCUDNNAvgInclude_channel_last(TestCase2_channel_last):
872

873 874 875 876 877 878 879 880
    def init_kernel_type(self):
        self.use_cudnn = True

    def init_exclusive(self):
        self.exclusive = False


class TestAvgPoolAdaptive_channel_last(TestCase1_channel_last):
881

882 883 884 885 886
    def init_adaptive(self):
        self.adaptive = True


class TestPool2D_AsyPadding_channel_last(TestPool2D_AsyPadding):
887

888 889 890 891 892 893 894 895
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 5, 5, 3]


class TestCase1_AsyPadding_channel_last(TestCase1_AsyPadding):
896

897 898 899 900 901 902 903 904
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase2_AsyPadding_channel_last(TestCase2_AsyPadding):
905

906 907 908 909 910 911 912 913
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase3_AsyPadding_channel_last(TestCase3_AsyPadding):
914

915 916 917 918 919 920 921 922
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 5, 5, 3]


class TestCase4_AsyPadding_channel_last(TestCase4_AsyPadding):
923

924 925 926 927 928 929 930 931
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


class TestCase5_AsyPadding_channel_last(TestCase5_AsyPadding):
932

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


create_test_cudnn_class(TestPool2D_AsyPadding_channel_last)
create_test_cudnn_class(TestCase1_AsyPadding_channel_last)
create_test_cudnn_class(TestCase2_AsyPadding_channel_last)
create_test_cudnn_class(TestCase3_AsyPadding_channel_last)
create_test_cudnn_class(TestCase4_AsyPadding_channel_last)
create_test_cudnn_class(TestCase5_AsyPadding_channel_last)

create_test_cudnn_fp16_class(TestPool2D_AsyPadding_channel_last)
948 949
create_test_cudnn_fp16_class(TestCase1_AsyPadding_channel_last,
                             check_grad=False)
950 951 952 953 954 955 956 957 958 959 960 961 962
create_test_cudnn_fp16_class(TestCase2_AsyPadding_channel_last)
create_test_cudnn_fp16_class(TestCase3_AsyPadding_channel_last)
create_test_cudnn_fp16_class(TestCase4_AsyPadding_channel_last)
create_test_cudnn_fp16_class(TestCase5_AsyPadding_channel_last)

create_test_cudnn_use_ceil_class(TestPool2D_AsyPadding_channel_last)
create_test_cudnn_use_ceil_class(TestCase1_AsyPadding_channel_last)

create_test_use_ceil_class(TestCase1_AsyPadding_channel_last)
create_test_use_ceil_class(TestCase2_AsyPadding_channel_last)


class TestAvgInclude_AsyPadding_channel_last(TestAvgInclude_AsyPadding):
963

964 965 966 967 968 969 970
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


971 972 973
class TestCUDNNAvgInclude_AsyPadding_channel_last(TestCUDNNAvgInclude_AsyPadding
                                                  ):

974 975 976 977 978 979 980
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


981 982 983
class TestAvgPoolAdaptive_AsyPadding_channel_last(TestAvgPoolAdaptive_AsyPadding
                                                  ):

984 985 986 987 988 989 990 991 992 993 994
    def init_data_format(self):
        self.data_format = "NHWC"

    def init_shape(self):
        self.shape = [2, 7, 7, 3]


# test paddings: SAME VALID


def create_test_padding_SAME_class(parent):
995

996
    class TestPaddingSMAECase(parent):
997

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        def init_paddings(self):
            self.paddings = [0, 0]
            self.padding_algorithm = "SAME"

    cls_name = "{0}_{1}".format(parent.__name__, "PaddingSAMEOp")
    TestPaddingSMAECase.__name__ = cls_name
    globals()[cls_name] = TestPaddingSMAECase


create_test_padding_SAME_class(TestPool2D_Op)
create_test_padding_SAME_class(TestCase1)
create_test_padding_SAME_class(TestCase2)
create_test_padding_SAME_class(TestCase3)
create_test_padding_SAME_class(TestCase4)
create_test_padding_SAME_class(TestCase5)

create_test_padding_SAME_class(TestPool2D_channel_last)
create_test_padding_SAME_class(TestCase1_channel_last)
create_test_padding_SAME_class(TestCase2_channel_last)
create_test_padding_SAME_class(TestCase3_channel_last)
create_test_padding_SAME_class(TestCase4_channel_last)
create_test_padding_SAME_class(TestCase5_channel_last)


def create_test_cudnn_padding_SAME_class(parent):
1023

1024 1025 1026
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestCUDNNPaddingSMAECase(parent):
1027

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        def init_kernel_type(self):
            self.use_cudnn = True

        def init_paddings(self):
            self.paddings = [1, 1]
            self.padding_algorithm = "SAME"

    cls_name = "{0}_{1}".format(parent.__name__, "CudnnPaddingSAMEOp")
    TestCUDNNPaddingSMAECase.__name__ = cls_name
    globals()[cls_name] = TestCUDNNPaddingSMAECase


create_test_cudnn_padding_SAME_class(TestPool2D_Op)
create_test_cudnn_padding_SAME_class(TestCase1)
create_test_cudnn_padding_SAME_class(TestCase2)
create_test_cudnn_padding_SAME_class(TestCase3)
create_test_cudnn_padding_SAME_class(TestCase4)
create_test_cudnn_padding_SAME_class(TestCase5)

create_test_cudnn_padding_SAME_class(TestPool2D_channel_last)
create_test_cudnn_padding_SAME_class(TestCase1_channel_last)
create_test_cudnn_padding_SAME_class(TestCase2_channel_last)
create_test_cudnn_padding_SAME_class(TestCase3_channel_last)
create_test_cudnn_padding_SAME_class(TestCase4_channel_last)
create_test_cudnn_padding_SAME_class(TestCase5_channel_last)


def create_test_padding_VALID_class(parent):
1056

1057
    class TestPaddingVALIDCase(parent):
1058

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
        def init_paddings(self):
            self.paddings = [1, 1]
            self.padding_algorithm = "VALID"

    cls_name = "{0}_{1}".format(parent.__name__, "PaddingVALIDOp")
    TestPaddingVALIDCase.__name__ = cls_name
    globals()[cls_name] = TestPaddingVALIDCase


create_test_padding_VALID_class(TestPool2D_Op)
create_test_padding_VALID_class(TestCase1)
create_test_padding_VALID_class(TestCase2)
create_test_padding_VALID_class(TestCase3)
create_test_padding_VALID_class(TestCase4)
create_test_padding_VALID_class(TestCase5)

create_test_padding_VALID_class(TestPool2D_channel_last)
create_test_padding_VALID_class(TestCase1_channel_last)
create_test_padding_VALID_class(TestCase2_channel_last)
create_test_padding_VALID_class(TestCase3_channel_last)
create_test_padding_VALID_class(TestCase4_channel_last)
create_test_padding_VALID_class(TestCase5_channel_last)


def create_test_cudnn_padding_VALID_class(parent):
1084

1085 1086 1087
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestCUDNNPaddingVALIDCase(parent):
1088

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        def init_kernel_type(self):
            self.use_cudnn = True

        def init_paddings(self):
            self.paddings = [1, 1]
            self.padding_algorithm = "VALID"

    cls_name = "{0}_{1}".format(parent.__name__, "CudnnPaddingVALIDOp")
    TestCUDNNPaddingVALIDCase.__name__ = cls_name
    globals()[cls_name] = TestCUDNNPaddingVALIDCase


create_test_cudnn_padding_VALID_class(TestPool2D_Op)
create_test_cudnn_padding_VALID_class(TestCase1)
create_test_cudnn_padding_VALID_class(TestCase2)
create_test_cudnn_padding_VALID_class(TestCase3)
create_test_cudnn_padding_VALID_class(TestCase4)
create_test_cudnn_padding_VALID_class(TestCase5)

create_test_cudnn_padding_VALID_class(TestPool2D_channel_last)
create_test_cudnn_padding_VALID_class(TestCase1_channel_last)
create_test_cudnn_padding_VALID_class(TestCase2_channel_last)
create_test_cudnn_padding_VALID_class(TestCase3_channel_last)
create_test_cudnn_padding_VALID_class(TestCase4_channel_last)
create_test_cudnn_padding_VALID_class(TestCase5_channel_last)


1116
class TestCase1_strides(TestCase1):
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    def init_test_case(self):
        self.ksize = [3, 3]
        self.strides = [1, 2]

    def init_shape(self):
        self.shape = [2, 3, 4, 5]


create_test_cudnn_class(TestCase1_strides)
create_test_padding_SAME_class(TestCase1_strides)
create_test_cudnn_padding_SAME_class(TestCase1_strides)


1131
# ----- test API
C
cnn 已提交
1132
class TestPool2DAPI(unittest.TestCase):
1133

1134 1135 1136 1137
    def test_api(self):
        x_NHWC = np.random.random([2, 5, 5, 3]).astype("float32")
        x_NCHW = np.random.random([2, 3, 5, 5]).astype("float32")

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        input_NHWC = fluid.layers.data(name="input_NHWC",
                                       shape=[2, 5, 5, 3],
                                       append_batch_size=False,
                                       dtype="float32")

        input_NCHW = fluid.layers.data(name="input_NCHW",
                                       shape=[2, 3, 5, 5],
                                       append_batch_size=False,
                                       dtype="float32")

        input_NHWC_negetive = fluid.layers.data(name="input_NHWC_negetive",
                                                shape=[2, -1, 5, 3],
                                                append_batch_size=False,
                                                dtype="float32")

        input_NCHW_negetive = fluid.layers.data(name="input_NCHW_negetive",
                                                shape=[2, 3, -1, -1],
                                                append_batch_size=False,
                                                dtype="float32")
1157

1158
        ksize = [3, 3]
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        out_1 = fluid.layers.pool2d(input=input_NHWC,
                                    pool_size=ksize,
                                    pool_type="max",
                                    pool_padding=[1, 1],
                                    use_cudnn=False,
                                    data_format="NHWC")

        out_2 = fluid.layers.pool2d(input=input_NHWC,
                                    pool_size=ksize,
                                    pool_type="avg",
                                    pool_padding=[[0, 0], [1, 1], [1, 1],
                                                  [0, 0]],
                                    use_cudnn=False,
                                    data_format="NHWC")

        out_3 = fluid.layers.pool2d(input=input_NCHW,
                                    pool_size=ksize,
                                    pool_type="avg",
                                    pool_padding=[[0, 0], [0, 0], [1, 1],
                                                  [1, 1]],
                                    use_cudnn=False,
                                    data_format="NCHW")

        out_4 = fluid.layers.pool2d(input=input_NCHW,
                                    pool_size=ksize,
                                    pool_type="avg",
                                    pool_padding=[1, 2, 1, 0],
                                    use_cudnn=False,
                                    data_format="NCHW")
1188
        # test VALID
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
        out_5 = fluid.layers.pool2d(input=input_NCHW,
                                    pool_size=ksize,
                                    pool_type="avg",
                                    pool_padding="VALID",
                                    use_cudnn=False,
                                    data_format="NCHW")

        out_6 = fluid.layers.pool2d(input=input_NHWC,
                                    pool_size=ksize,
                                    pool_type="max",
                                    pool_padding="VALID",
                                    use_cudnn=False,
                                    data_format="NHWC")
1202 1203

        # test SAME
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        out_7 = fluid.layers.pool2d(input=input_NCHW,
                                    pool_size=[4, 4],
                                    pool_type="avg",
                                    pool_padding="SAME",
                                    use_cudnn=False,
                                    data_format="NCHW")

        out_8 = fluid.layers.pool2d(input=input_NHWC,
                                    pool_size=[4, 4],
                                    pool_type="max",
                                    pool_padding="SAME",
                                    use_cudnn=False,
                                    data_format="NHWC")
1217

1218
        # test negetive
1219 1220 1221 1222 1223 1224
        out_9 = fluid.layers.pool2d(input=input_NHWC_negetive,
                                    pool_size=ksize,
                                    pool_type="avg",
                                    pool_padding=[0, 0],
                                    use_cudnn=False,
                                    data_format="NHWC")
1225 1226
        assert out_9.shape == (2, -1, 3, 3)

1227 1228 1229 1230 1231 1232
        out_10 = fluid.layers.pool2d(input=input_NCHW_negetive,
                                     pool_size=ksize,
                                     pool_type="avg",
                                     pool_padding=[0, 0],
                                     use_cudnn=False,
                                     data_format="NCHW")
1233 1234
        assert out_10.shape == (2, 3, -1, -1)

1235 1236 1237
        exe = fluid.Executor(place=fluid.CPUPlace())
        [res_1, res_2, res_3, res_4, res_5, res_6, res_7, res_8] = exe.run(
            fluid.default_main_program(),
1238 1239 1240 1241 1242 1243
            feed={
                "input_NHWC": x_NHWC,
                "input_NCHW": x_NCHW,
                "input_NHWC_negetive": x_NHWC,
                "input_NCHW_negetive": x_NCHW
            },
1244
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7, out_8])
1245 1246 1247

        assert np.allclose(
            res_1,
1248 1249 1250 1251 1252 1253
            pool2D_forward_naive(x=x_NHWC,
                                 ksize=ksize,
                                 pool_type="max",
                                 strides=[1, 1],
                                 paddings=[1, 1],
                                 data_format="NHWC"))
1254 1255 1256

        assert np.allclose(
            res_2,
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
            pool2D_forward_naive(x=x_NHWC,
                                 ksize=ksize,
                                 pool_type="avg",
                                 strides=[1, 1],
                                 paddings=[1, 1, 1, 1],
                                 data_format="NHWC"))
        assert np.allclose(res_3,
                           pool2D_forward_naive(x=x_NCHW,
                                                ksize=ksize,
                                                pool_type="avg",
                                                strides=[1, 1],
                                                paddings=[1, 1, 1, 1],
                                                data_format="NCHW"),
                           rtol=0.07,
                           atol=1e-05)

        assert np.allclose(res_4,
                           pool2D_forward_naive(x=x_NCHW,
                                                ksize=ksize,
                                                pool_type="avg",
                                                strides=[1, 1],
                                                paddings=[1, 2, 1, 0],
                                                data_format="NCHW"),
                           rtol=0.07,
                           atol=1e-05)
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

        # VALID
        assert np.allclose(
            res_5,
            pool2D_forward_naive(
                x=x_NCHW,
                ksize=ksize,
                pool_type="avg",
                strides=[1, 1],
                paddings=[10, 20],  # any ele is ok
                padding_algorithm="VALID",
                data_format="NCHW"),
            rtol=0.07,
            atol=1e-05)
        assert np.allclose(
            res_6,
1298 1299 1300 1301 1302 1303 1304
            pool2D_forward_naive(x=x_NHWC,
                                 ksize=ksize,
                                 pool_type="max",
                                 strides=[1, 1],
                                 paddings=[10, 20],
                                 padding_algorithm="VALID",
                                 data_format="NHWC"))
1305
        # SAME
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        assert np.allclose(res_7,
                           pool2D_forward_naive(x=x_NCHW,
                                                ksize=[4, 4],
                                                pool_type="avg",
                                                strides=[1, 1],
                                                paddings=[10, 20],
                                                padding_algorithm="SAME",
                                                data_format="NCHW"),
                           rtol=0.07,
                           atol=1e-05)
1316 1317 1318

        assert np.allclose(
            res_8,
1319 1320 1321 1322 1323 1324 1325
            pool2D_forward_naive(x=x_NHWC,
                                 ksize=[4, 4],
                                 pool_type="max",
                                 strides=[1, 1],
                                 paddings=[10, 20],
                                 padding_algorithm="SAME",
                                 data_format="NHWC"))
1326 1327


C
cnn 已提交
1328
class TestPool2DAPI_Error(unittest.TestCase):
1329

1330
    def test_api(self):
1331 1332 1333 1334
        input_NHWC = fluid.layers.data(name="input_NHWC",
                                       shape=[2, 5, 5, 3],
                                       append_batch_size=False,
                                       dtype="float32")
1335 1336
        ksize = [3, 3]

1337
        # cudnn type error
1338
        def run_1():
1339 1340 1341 1342 1343 1344
            out_1 = fluid.layers.pool2d(input=input_NHWC,
                                        pool_size=ksize,
                                        pool_type="max",
                                        pool_padding=[1, 1],
                                        use_cudnn=[0],
                                        data_format="NHWC")
1345

1346
        self.assertRaises(TypeError, run_1)
1347 1348 1349

        # data_format value error
        def run_2():
1350 1351 1352 1353 1354 1355
            out_2 = fluid.layers.pool2d(input=input_NHWC,
                                        pool_size=ksize,
                                        pool_type="max",
                                        pool_padding=[1, 1],
                                        use_cudnn=False,
                                        data_format="NHWCC")
1356 1357 1358 1359 1360

        self.assertRaises(ValueError, run_2)

        # padding str value error
        def run_3():
1361 1362 1363 1364 1365 1366
            out_3 = fluid.layers.pool2d(input=input_NHWC,
                                        pool_size=ksize,
                                        pool_type="max",
                                        pool_padding="VALIDSAME",
                                        use_cudnn=False,
                                        data_format="NHWC")
1367 1368 1369 1370 1371

        self.assertRaises(ValueError, run_3)

        # padding str valid and ceil_mode value error
        def run_4():
1372 1373 1374 1375 1376 1377 1378
            out_4 = fluid.layers.pool2d(input=input_NHWC,
                                        pool_size=ksize,
                                        pool_type="max",
                                        pool_padding="VALID",
                                        use_cudnn=False,
                                        ceil_mode=True,
                                        data_format="NHWC")
1379 1380 1381 1382 1383

        self.assertRaises(ValueError, run_4)

        # padding with 8 ele. value error
        def run_5():
1384 1385 1386 1387 1388 1389 1390
            out_5 = fluid.layers.pool2d(input=input_NHWC,
                                        pool_size=ksize,
                                        pool_type="max",
                                        pool_padding=[[1, 1], [0, 0], [0, 0],
                                                      [1, 1]],
                                        use_cudnn=False,
                                        data_format="NHWC")
1391 1392 1393 1394

        self.assertRaises(ValueError, run_5)


1395
class TestDygraphPool2DAPIError(unittest.TestCase):
1396

1397 1398 1399 1400
    def test_errors(self):
        with program_guard(Program(), Program()):
            # the input of Pool2D must be Variable.
            data1 = np.random.random((3, 32, 32, 5)).astype('float32')
1401 1402 1403 1404
            pool2d = fluid.dygraph.Pool2D(pool_size=2,
                                          pool_type='max',
                                          pool_stride=1,
                                          global_pooling=False)
1405 1406 1407 1408 1409
            self.assertRaises(TypeError, pool2d, data1)

            # the input dtype of Pool2D must be uint8 or int8 or float16 or float32 or float64
            # uint8 and int8 only can be set on mkldnn
            # float16 only can be set on GPU place
1410 1411 1412
            data2 = fluid.layers.data(name='x1',
                                      shape=[3, 32, 32, 5],
                                      dtype="int32")
1413 1414
            self.assertRaises(TypeError, pool2d, data2)

1415 1416 1417 1418
    def test_data_format_error(self):
        with program_guard(Program(), Program()):
            # the data_format must be 'NCHW' or 'NHWC'
            data1 = np.random.random((3, 32, 32, 5)).astype('float32')
1419 1420 1421 1422 1423 1424 1425
            self.assertRaises(ValueError,
                              fluid.dygraph.Pool2D,
                              pool_size=2,
                              pool_type='max',
                              pool_stride=1,
                              global_pooling=False,
                              data_format='NWHC')
1426 1427 1428


class TestDygraphPool2DAPI(unittest.TestCase):
1429

1430 1431 1432 1433
    def test_nhwc(self):
        with fluid.dygraph.guard():
            data = np.random.random((3, 32, 32, 5)).astype('float32')
            x = fluid.dygraph.to_variable(data)
1434 1435 1436 1437 1438 1439
            pool2d = fluid.dygraph.Pool2D(pool_size=2,
                                          pool_type='max',
                                          pool_stride=1,
                                          pool_padding=[0, 0],
                                          global_pooling=False,
                                          data_format='NHWC')
1440
            out1 = pool2d(x)
1441 1442 1443 1444
            out2 = pool2D_forward_naive(data, [2, 2], [1, 1],
                                        paddings=[0, 0],
                                        pool_type='max',
                                        data_format='NHWC')
1445 1446 1447 1448 1449 1450
            self.assertTrue(np.allclose(out1.numpy(), out2))

    def test_lower_case(self):
        with fluid.dygraph.guard():
            data = np.random.random((3, 32, 32, 5)).astype('float32')
            x = fluid.dygraph.to_variable(data)
1451 1452 1453 1454 1455 1456
            pool2d = fluid.dygraph.Pool2D(pool_size=2,
                                          pool_type='max',
                                          pool_stride=1,
                                          pool_padding=[0, 0],
                                          global_pooling=False,
                                          data_format='nhwc')
1457
            out1 = pool2d(x)
1458 1459 1460 1461
            out2 = pool2D_forward_naive(data, [2, 2], [1, 1],
                                        paddings=[0, 0],
                                        pool_type='max',
                                        data_format='NHWC')
1462 1463 1464 1465 1466 1467
            self.assertTrue(np.allclose(out1.numpy(), out2))

    def test_upper_case(self):
        with fluid.dygraph.guard():
            data = np.random.random((3, 32, 32, 5)).astype('float32')
            x = fluid.dygraph.to_variable(data)
1468 1469 1470 1471 1472 1473
            pool2d = fluid.dygraph.Pool2D(pool_size=2,
                                          pool_type='MAX',
                                          pool_stride=1,
                                          pool_padding=[0, 0],
                                          global_pooling=False,
                                          data_format='nhwc')
1474
            out1 = pool2d(x)
1475 1476 1477 1478
            out2 = pool2D_forward_naive(data, [2, 2], [1, 1],
                                        paddings=[0, 0],
                                        pool_type='max',
                                        data_format='NHWC')
1479 1480
            self.assertTrue(np.allclose(out1.numpy(), out2))

1481

C
chengduoZH 已提交
1482 1483
if __name__ == '__main__':
    unittest.main()