test_pool1d_api.py 14.5 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
16 17 18 19

import numpy as np

import paddle
F
From00 已提交
20 21 22 23
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.nn.functional as F
from paddle.fluid.framework import _test_eager_guard
24 25 26 27 28 29 30 31 32 33


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))


34 35 36 37 38 39 40 41 42 43 44
def max_pool1D_forward_naive(
    x,
    ksize,
    strides,
    paddings,
    global_pool=0,
    ceil_mode=False,
    exclusive=False,
    adaptive=False,
    data_type=np.float64,
):
45 46 47 48 49 50
    N, C, L = x.shape
    if global_pool == 1:
        ksize = [L]
    if adaptive:
        L_out = ksize[0]
    else:
51 52 53 54 55
        L_out = (
            (L - ksize[0] + 2 * paddings[0] + strides[0] - 1) // strides[0] + 1
            if ceil_mode
            else (L - ksize[0] + 2 * paddings[0]) // strides[0] + 1
        )
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

    out = np.zeros((N, C, L_out))
    for i in range(L_out):
        if adaptive:
            r_start = adaptive_start_index(i, L, ksize[0])
            r_end = adaptive_end_index(i, L, ksize[0])
        else:
            r_start = np.max((i * strides[0] - paddings[0], 0))
            r_end = np.min((i * strides[0] + ksize[0] - paddings[0], L))
        x_masked = x[:, :, r_start:r_end]

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


71 72 73 74 75 76 77 78 79 80 81
def avg_pool1D_forward_naive(
    x,
    ksize,
    strides,
    paddings,
    global_pool=0,
    ceil_mode=False,
    exclusive=False,
    adaptive=False,
    data_type=np.float64,
):
82 83 84 85 86 87
    N, C, L = x.shape
    if global_pool == 1:
        ksize = [L]
    if adaptive:
        L_out = ksize[0]
    else:
88 89 90 91 92
        L_out = (
            (L - ksize[0] + 2 * paddings[0] + strides[0] - 1) // strides[0] + 1
            if ceil_mode
            else (L - ksize[0] + 2 * paddings[0]) // strides[0] + 1
        )
93 94 95 96 97 98 99 100 101 102 103

    out = np.zeros((N, C, L_out))
    for i in range(L_out):
        if adaptive:
            r_start = adaptive_start_index(i, L, ksize[0])
            r_end = adaptive_end_index(i, L, ksize[0])
        else:
            r_start = np.max((i * strides[0] - paddings[0], 0))
            r_end = np.min((i * strides[0] + ksize[0] - paddings[0], L))
        x_masked = x[:, :, r_start:r_end]

104 105 106
        field_size = (
            (r_end - r_start) if (exclusive or adaptive) else (ksize[0])
        )
107
        if data_type == np.int8 or data_type == np.uint8:
108 109 110
            out[:, :, i] = (
                np.rint(np.sum(x_masked, axis=(2, 3)) / field_size)
            ).astype(data_type)
111
        else:
112 113 114
            out[:, :, i] = (np.sum(x_masked, axis=(2)) / field_size).astype(
                data_type
            )
115 116 117
    return out


C
cnn 已提交
118
class TestPool1D_API(unittest.TestCase):
119 120 121 122 123 124 125 126 127 128 129 130
    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()):
            input = fluid.data(name="input", shape=[2, 3, 32], dtype="float32")
            result = F.avg_pool1d(input, kernel_size=2, stride=2, padding=0)

            input_np = np.random.random([2, 3, 32]).astype("float32")
131 132 133
            result_np = avg_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0], ceil_mode=False
            )
134 135

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

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

149 150 151
            result_np = avg_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
152

153
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
154

155 156 157
            avg_pool1d_dg = paddle.nn.layer.AvgPool1D(
                kernel_size=2, stride=None, padding=0
            )
158
            result = avg_pool1d_dg(input)
159
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
160

D
Double_V 已提交
161 162 163 164
    def check_avg_dygraph_padding_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
165 166 167 168 169 170 171
            result = F.avg_pool1d(
                input, kernel_size=2, stride=2, padding=[1], exclusive=True
            )

            result_np = avg_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[1], exclusive=False
            )
D
Double_V 已提交
172

173
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
174

175 176 177
            avg_pool1d_dg = paddle.nn.AvgPool1D(
                kernel_size=2, stride=None, padding=1, exclusive=True
            )
178

D
Double_V 已提交
179
            result = avg_pool1d_dg(input)
180
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
181

182 183 184 185 186 187
    def check_max_static_results(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input = fluid.data(name="input", shape=[2, 3, 32], dtype="float32")
            result = F.max_pool1d(input, kernel_size=2, stride=2, padding=[0])

            input_np = np.random.random([2, 3, 32]).astype("float32")
188 189 190
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
191 192

            exe = fluid.Executor(place)
193 194 195 196 197
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
198
            np.testing.assert_allclose(fetches[0], result_np, rtol=1e-05)
199 200 201 202 203 204 205

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

206 207 208
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
209

210
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
211

212 213 214
            max_pool1d_dg = paddle.nn.layer.MaxPool1D(
                kernel_size=2, stride=None, padding=0
            )
215
            result = max_pool1d_dg(input)
216
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
217

D
Double_V 已提交
218 219 220 221
    def check_max_dygraph_return_index_results(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
222 223 224
            result, index = F.max_pool1d(
                input, kernel_size=2, stride=2, padding=0, return_mask=True
            )
D
Double_V 已提交
225

226 227 228
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
D
Double_V 已提交
229

230
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
231

232 233 234
            max_pool1d_dg = paddle.nn.layer.MaxPool1D(
                kernel_size=2, stride=None, padding=0
            )
D
Double_V 已提交
235
            result = max_pool1d_dg(input)
236
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
D
Double_V 已提交
237

238 239 240 241
    def check_max_dygraph_padding_same(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
242 243 244
            result = F.max_pool1d(
                input, kernel_size=2, stride=2, padding="SAME"
            )
245

246 247 248
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
249

250
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
251 252 253 254 255

    def check_avg_dygraph_padding_same(self, place):
        with fluid.dygraph.guard(place):
            input_np = np.random.random([2, 3, 32]).astype("float32")
            input = fluid.dygraph.to_variable(input_np)
256 257 258
            result = F.avg_pool1d(
                input, kernel_size=2, stride=2, padding="SAME"
            )
259

260 261 262
            result_np = avg_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
263

264
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
265 266 267 268 269 270 271 272 273 274

    def test_pool1d(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_padding_same(place)
            self.check_avg_dygraph_padding_same(place)
D
Double_V 已提交
275
            self.check_max_dygraph_return_index_results(place)
276

277
    def test_dygraph_api(self):
F
From00 已提交
278 279 280
        with _test_eager_guard():
            self.test_pool1d()

281

C
cnn 已提交
282
class TestPool2DError_API(unittest.TestCase):
283 284 285
    def test_error_api(self):
        def run1():
            with fluid.dygraph.guard():
286 287 288
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
289 290
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = [[2]]
291 292 293
                res_pd = F.max_pool1d(
                    input_pd, kernel_size=2, stride=2, padding=padding
                )
294 295 296 297 298

        self.assertRaises(ValueError, run1)

        def run2():
            with fluid.dygraph.guard():
299 300 301
                input_np = np.random.uniform(-1, 1, [2, 3, 32, 32]).astype(
                    np.float32
                )
302 303
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = [[2]]
304 305 306
                res_pd = F.max_pool1d(
                    input_pd, kernel_size=2, stride=2, padding=padding
                )
307 308 309 310 311

        self.assertRaises(ValueError, run2)

        def run3():
            with fluid.dygraph.guard():
312 313 314
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
315 316
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "padding"
317 318 319
                res_pd = F.max_pool1d(
                    input_pd, kernel_size=2, stride=2, padding=padding
                )
320 321 322 323 324

        self.assertRaises(ValueError, run3)

        def run4():
            with fluid.dygraph.guard():
325 326 327
                input_np = np.random.uniform(-1, 1, [2, 3, 32, 32]).astype(
                    np.float32
                )
328 329
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
330 331 332 333 334 335 336
                res_pd = F.max_pool1d(
                    input_pd,
                    kernel_size=2,
                    stride=2,
                    padding=padding,
                    ceil_mode=True,
                )
337 338 339 340 341

        self.assertRaises(ValueError, run4)

        def run5():
            with fluid.dygraph.guard():
342 343 344
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
345 346
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
347 348 349 350 351 352 353
                res_pd = F.max_pool1d(
                    input_pd,
                    kernel_size=2,
                    stride=2,
                    padding=padding,
                    ceil_mode=True,
                )
354 355 356 357 358

        self.assertRaises(ValueError, run5)

        def run6():
            with fluid.dygraph.guard():
359 360 361
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
362 363
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "VALID"
364 365 366 367 368 369 370
                res_pd = F.avg_pool1d(
                    input_pd,
                    kernel_size=2,
                    stride=2,
                    padding=padding,
                    ceil_mode=True,
                )
371 372 373 374 375

        self.assertRaises(ValueError, run6)

        def run7():
            with fluid.dygraph.guard():
376 377 378
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
379 380
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = "paddle"
381 382 383 384 385 386 387
                res_pd = F.avg_pool1d(
                    input_pd,
                    kernel_size=2,
                    stride=2,
                    padding=padding,
                    ceil_mode=True,
                )
388 389 390

        self.assertRaises(ValueError, run7)

D
Double_V 已提交
391 392
        def run_kernel_out_of_range():
            with fluid.dygraph.guard():
393 394 395
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
D
Double_V 已提交
396 397
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = 0
398 399 400 401 402 403 404
                res_pd = F.avg_pool1d(
                    input_pd,
                    kernel_size=-1,
                    stride=2,
                    padding=padding,
                    ceil_mode=True,
                )
D
Double_V 已提交
405 406 407 408 409

        self.assertRaises(ValueError, run_kernel_out_of_range)

        def run_stride_out_of_range():
            with fluid.dygraph.guard():
410 411 412
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
D
Double_V 已提交
413 414
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = 0
415 416 417 418 419 420 421
                res_pd = F.avg_pool1d(
                    input_pd,
                    kernel_size=2,
                    stride=0,
                    padding=padding,
                    ceil_mode=True,
                )
D
Double_V 已提交
422 423 424

        self.assertRaises(ValueError, run_stride_out_of_range)

425
    def test_dygraph_api(self):
F
From00 已提交
426 427 428
        with _test_eager_guard():
            self.test_error_api()

429 430 431

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