test_pool1d_api.py 14.6 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
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.nn.functional as F
23 24 25 26 27 28 29 30 31 32


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


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

    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


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

    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]

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


C
cnn 已提交
117
class TestPool1D_API(unittest.TestCase):
118 119 120 121 122 123 124 125 126 127 128 129
    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")
130 131 132
            result_np = avg_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0], ceil_mode=False
            )
133 134

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

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

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

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

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

D
Double_V 已提交
160 161 162 163
    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)
164 165 166 167 168 169 170
            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 已提交
171

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

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

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

181 182 183 184 185 186
    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")
187 188 189
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[2], strides=[2], paddings=[0]
            )
190 191

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

    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)

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

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

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

D
Double_V 已提交
217 218 219 220
    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)
221 222 223
            result, index = F.max_pool1d(
                input, kernel_size=2, stride=2, padding=0, return_mask=True
            )
D
Double_V 已提交
224

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

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

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

237 238 239 240
    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)
241 242 243
            result = F.max_pool1d(
                input, kernel_size=2, stride=2, padding="SAME"
            )
244

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

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

    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)
255 256 257
            result = F.avg_pool1d(
                input, kernel_size=2, stride=2, padding="SAME"
            )
258

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

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

    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 已提交
274
            self.check_max_dygraph_return_index_results(place)
275 276


277
class TestPool1DError_API(unittest.TestCase):
278 279 280
    def test_error_api(self):
        def run1():
            with fluid.dygraph.guard():
281 282 283
                input_np = np.random.uniform(-1, 1, [2, 3, 32]).astype(
                    np.float32
                )
284 285
                input_pd = fluid.dygraph.to_variable(input_np)
                padding = [[2]]
286 287 288
                res_pd = F.max_pool1d(
                    input_pd, kernel_size=2, stride=2, padding=padding
                )
289 290 291 292 293

        self.assertRaises(ValueError, run1)

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

        self.assertRaises(ValueError, run2)

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

        self.assertRaises(ValueError, run3)

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

        self.assertRaises(ValueError, run4)

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

        self.assertRaises(ValueError, run5)

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

        self.assertRaises(ValueError, run6)

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

        self.assertRaises(ValueError, run7)

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

        self.assertRaises(ValueError, run_kernel_out_of_range)

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

        self.assertRaises(ValueError, run_stride_out_of_range)

420 421 422 423 424 425 426 427 428 429 430 431
        def run_zero_stride():
            with fluid.dygraph.guard():
                array = np.array([1], dtype=np.float32)
                x = paddle.to_tensor(
                    np.reshape(array, [1, 1, 1]), dtype='float32'
                )
                out = F.max_pool1d(
                    x, 1, stride=0, padding=1, return_mask=True, ceil_mode=True
                )

        self.assertRaises(ValueError, run_zero_stride)

432 433 434

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