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

import unittest
F
From00 已提交
16
import paddle
17
import numpy as np
F
From00 已提交
18
import paddle.fluid as fluid
19
import paddle.fluid.core as core
F
From00 已提交
20
from paddle.fluid.framework import _test_eager_guard
X
xiaoting 已提交
21
from paddle.nn.functional import avg_pool2d, max_pool2d
22
from test_pool2d_op import avg_pool2D_forward_naive, max_pool2D_forward_naive, pool2D_forward_naive
23 24


C
cnn 已提交
25
class TestPool2D_API(unittest.TestCase):
26

27 28 29 30 31 32 33 34
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_avg_static_results(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
35 36 37
            input = fluid.data(name="input",
                               shape=[2, 3, 32, 32],
                               dtype="float32")
38 39 40
            result = avg_pool2d(input, kernel_size=2, stride=2, padding=0)

            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
41 42 43 44 45
            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='avg')
46 47 48 49 50

            exe = fluid.Executor(place)
            fetches = exe.run(fluid.default_main_program(),
                              feed={"input": input_np},
                              fetch_list=[result])
51
            np.testing.assert_allclose(fetches[0], result_np, rtol=1e-05)
52 53 54 55 56 57 58

    def check_avg_dygraph_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
            result = avg_pool2d(input, kernel_size=2, stride=2, padding=0)

59 60 61 62 63
            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='avg')
64
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
65

66 67 68
            avg_pool2d_dg = paddle.nn.layer.AvgPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
69
            result = avg_pool2d_dg(input)
70
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
71

D
Double_V 已提交
72 73 74 75
    def check_avg_dygraph_padding_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
76 77 78 79 80 81 82 83 84 85 86 87
            result = avg_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=1,
                                ceil_mode=False)

            result_np = avg_pool2D_forward_naive(input_np,
                                                 ksize=[2, 2],
                                                 strides=[2, 2],
                                                 paddings=[1, 1],
                                                 ceil_mode=False,
                                                 exclusive=False)
88
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
89

90 91 92 93
            avg_pool2d_dg = paddle.nn.layer.AvgPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=1,
                                                      ceil_mode=False)
D
Double_V 已提交
94
            result = avg_pool2d_dg(input)
95
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
96 97 98 99 100

    def check_avg_dygraph_ceilmode_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
101 102 103 104 105 106 107 108 109 110 111
            result = avg_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=0,
                                ceil_mode=True)

            result_np = avg_pool2D_forward_naive(input_np,
                                                 ksize=[2, 2],
                                                 strides=[2, 2],
                                                 paddings=[0, 0],
                                                 ceil_mode=True)
112
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
113

114 115 116 117
            avg_pool2d_dg = paddle.nn.layer.AvgPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0,
                                                      ceil_mode=True)
D
Double_V 已提交
118
            result = avg_pool2d_dg(input)
119
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
120

121 122
    def check_max_static_results(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
123 124 125
            input = fluid.data(name="input",
                               shape=[2, 3, 32, 32],
                               dtype="float32")
126 127 128
            result = max_pool2d(input, kernel_size=2, stride=2, padding=0)

            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
129 130 131 132 133
            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='max')
134 135 136 137 138

            exe = fluid.Executor(place)
            fetches = exe.run(fluid.default_main_program(),
                              feed={"input": input_np},
                              fetch_list=[result])
139
            np.testing.assert_allclose(fetches[0], result_np, rtol=1e-05)
140 141 142 143 144

    def check_max_dygraph_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
145 146 147 148 149 150 151 152 153 154 155
            result = max_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=0,
                                return_mask=False)

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='max')
156
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
157

158 159 160
            max_pool2d_dg = paddle.nn.layer.MaxPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
161
            result = max_pool2d_dg(input)
162
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
163

D
Double_V 已提交
164 165 166 167 168
    def check_max_dygraph_nhwc_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(
                np.transpose(input_np, [0, 2, 3, 1]))
169 170 171 172 173 174 175 176 177 178 179 180
            result = max_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=0,
                                return_mask=False,
                                data_format="NHWC")

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='max')
181 182 183 184
            np.testing.assert_allclose(np.transpose(result.numpy(),
                                                    [0, 3, 1, 2]),
                                       result_np,
                                       rtol=1e-05)
D
Double_V 已提交
185 186 187 188 189

    def check_max_dygraph_padding_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
190 191 192 193 194 195 196 197 198 199 200 201
            result = max_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=1,
                                ceil_mode=False)

            result_np = max_pool2D_forward_naive(input_np,
                                                 ksize=[2, 2],
                                                 strides=[2, 2],
                                                 paddings=[1, 1],
                                                 ceil_mode=False,
                                                 exclusive=False)
202
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
203

204 205 206 207
            max_pool2d_dg = paddle.nn.layer.MaxPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=1,
                                                      ceil_mode=False)
D
Double_V 已提交
208
            result = max_pool2d_dg(input)
209
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
210 211 212 213 214

    def check_max_dygraph_ceilmode_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
215 216 217 218 219 220 221 222 223 224 225
            result = max_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=0,
                                ceil_mode=True)

            result_np = max_pool2D_forward_naive(input_np,
                                                 ksize=[2, 2],
                                                 strides=[2, 2],
                                                 paddings=[0, 0],
                                                 ceil_mode=True)
226
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
227

228 229 230 231
            max_pool2d_dg = paddle.nn.layer.MaxPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0,
                                                      ceil_mode=True)
D
Double_V 已提交
232
            result = max_pool2d_dg(input)
233
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
234

235 236 237 238
    def check_max_dygraph_stride_is_none(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
239 240 241 242 243 244 245 246 247 248 249 250
            result, indices = max_pool2d(input,
                                         kernel_size=2,
                                         stride=None,
                                         padding="SAME",
                                         return_mask=True)

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='max',
                                             padding_algorithm="SAME")
251
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
252

253 254 255
            max_pool2d_dg = paddle.nn.layer.MaxPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
256
            result = max_pool2d_dg(input)
257
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
258 259 260 261 262

    def check_avg_dygraph_stride_is_none(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
263 264 265 266 267 268 269 270 271 272 273
            result = avg_pool2d(input,
                                kernel_size=2,
                                stride=None,
                                padding="SAME")

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='avg',
                                             padding_algorithm="SAME")
274
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
275

276 277 278
            avg_pool2d_dg = paddle.nn.layer.AvgPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
279
            result = avg_pool2d_dg(input)
280
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
281 282 283 284 285 286

    def check_max_dygraph_padding(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
            padding = [[0, 0], [0, 0], [0, 0], [0, 0]]
287 288 289 290 291 292 293 294 295 296 297
            result = max_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=padding,
                                return_mask=False)

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='max')
298
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
299

300 301 302
            max_pool2d_dg = paddle.nn.layer.MaxPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
303
            result = max_pool2d_dg(input)
304
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
305 306 307 308 309 310

    def check_avg_divisor(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
            padding = [[0, 0], [0, 0], [0, 0], [0, 0]]
311 312 313 314 315 316 317 318 319 320 321
            result = avg_pool2d(input,
                                kernel_size=2,
                                stride=2,
                                padding=padding,
                                divisor_override=4)

            result_np = pool2D_forward_naive(input_np,
                                             ksize=[2, 2],
                                             strides=[2, 2],
                                             paddings=[0, 0],
                                             pool_type='avg')
322
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
323

324 325 326
            avg_pool2d_dg = paddle.nn.layer.AvgPool2D(kernel_size=2,
                                                      stride=2,
                                                      padding=0)
327
            result = avg_pool2d_dg(input)
328
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
329 330 331 332 333 334 335 336 337 338 339 340

    def test_pool2d(self):
        for place in self.places:

            self.check_max_dygraph_results(place)
            self.check_avg_dygraph_results(place)
            self.check_max_static_results(place)
            self.check_avg_static_results(place)
            self.check_max_dygraph_stride_is_none(place)
            self.check_avg_dygraph_stride_is_none(place)
            self.check_max_dygraph_padding(place)
            self.check_avg_divisor(place)
D
Double_V 已提交
341 342 343
            self.check_max_dygraph_padding_results(place)
            self.check_max_dygraph_ceilmode_results(place)
            self.check_max_dygraph_nhwc_results(place)
344

345
    def test_dygraph_api(self):
F
From00 已提交
346 347 348
        with _test_eager_guard():
            self.test_pool2d()

349

C
cnn 已提交
350
class TestPool2DError_API(unittest.TestCase):
351

352
    def test_error_api(self):
353

354 355 356 357 358 359
        def run1():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = [[0, 1], [0, 0], [0, 0], [0, 0]]
360 361 362 363
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding)
364 365 366 367 368 369 370 371 372

        self.assertRaises(ValueError, run1)

        def run2():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = [[0, 1], [0, 0], [0, 0], [0, 0]]
373 374 375 376 377
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    data_format='NHWC')
378 379 380 381 382 383 384 385 386

        self.assertRaises(ValueError, run2)

        def run3():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "padding"
387 388 389 390 391
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    data_format='NHWC')
392 393 394 395 396 397 398 399 400

        self.assertRaises(ValueError, run3)

        def run3_avg():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "padding"
401 402 403 404 405
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    data_format='NHWC')
406 407 408 409 410 411 412 413 414

        self.assertRaises(ValueError, run3_avg)

        def run4():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
415 416 417 418 419 420
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    ceil_mode=True,
                                    data_format='NHWC')
421 422 423 424 425 426 427 428 429

        self.assertRaises(ValueError, run4)

        def run4_avg():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
430 431 432 433 434 435
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    ceil_mode=True,
                                    data_format='NHWC')
436 437 438 439 440 441 442 443 444

        self.assertRaises(ValueError, run4_avg)

        def run5():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "padding"
445 446 447 448 449
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    data_format='NHWC')
450 451 452 453 454 455 456 457 458

        self.assertRaises(ValueError, run5)

        def run6():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
459 460 461 462 463 464
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    ceil_mode=True,
                                    data_format='NHWC')
465 466 467 468 469 470 471 472 473

        self.assertRaises(ValueError, run6)

        def run7():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
474 475 476 477 478 479
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    ceil_mode=False,
                                    data_format='NNNN')
480 481 482 483 484 485 486 487 488

        self.assertRaises(ValueError, run7)

        def run8():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
489 490 491 492 493 494
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=padding,
                                    ceil_mode=False,
                                    data_format='NNNN')
495 496 497

        self.assertRaises(ValueError, run8)

D
Double_V 已提交
498 499 500 501 502
        def run9():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
503 504 505 506 507 508 509
                res_pd = max_pool2d(input_pd,
                                    kernel_size=2,
                                    stride=2,
                                    padding=0,
                                    ceil_mode=False,
                                    data_format='NHWC',
                                    return_mask=True)
D
Double_V 已提交
510 511 512

        self.assertRaises(ValueError, run9)

D
Double_V 已提交
513 514 515 516 517
        def run_kernel_out_of_range():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
518 519 520 521 522 523
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=[-1, 2],
                                    stride=2,
                                    padding=0,
                                    ceil_mode=False,
                                    data_format='NHWC')
D
Double_V 已提交
524 525 526 527 528 529 530 531

        self.assertRaises(ValueError, run_kernel_out_of_range)

        def run_stride_out_of_range():
            with fluid.dygraph.guard():
                input_np = np.random.uniform(-1, 1,
                                             [2, 3, 32, 32]).astype(np.float32)
                input_pd = fluid.dygraph.to_variable(input_np)
532 533 534 535 536 537
                res_pd = avg_pool2d(input_pd,
                                    kernel_size=3,
                                    stride=[0, 2],
                                    padding=0,
                                    ceil_mode=False,
                                    data_format='NHWC')
D
Double_V 已提交
538 539 540

        self.assertRaises(ValueError, run_stride_out_of_range)

541
    def test_dygraph_api(self):
F
From00 已提交
542 543 544
        with _test_eager_guard():
            self.test_error_api()

545 546 547

if __name__ == '__main__':
    unittest.main()