test_adaptive_max_pool1d.py 4.4 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

import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import check_out_dtype, paddle_static_guard
19

20 21
import paddle
import paddle.fluid as fluid
22 23
import paddle.fluid.core as core
import paddle.nn.functional as F
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


C
cnn 已提交
71
class TestPool1D_API(unittest.TestCase):
72 73 74 75 76 77 78 79 80 81 82 83
    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_adaptive_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.adaptive_max_pool1d(input, output_size=16)

84 85 86
            result_np = max_pool1D_forward_naive(
                input_np, ksize=[16], strides=[0], paddings=[0], adaptive=True
            )
87
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
88

C
cnn 已提交
89
            ada_max_pool1d_dg = paddle.nn.layer.AdaptiveMaxPool1D(
90 91
                output_size=16
            )
92
            result = ada_max_pool1d_dg(input)
93
            np.testing.assert_allclose(result.numpy(), result_np, rtol=1e-05)
94 95

    def check_adaptive_max_static_results(self, place):
W
wanghuancoder 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                input = fluid.data(
                    name="input", shape=[2, 3, 32], dtype="float32"
                )
                result = F.adaptive_max_pool1d(input, output_size=16)

                input_np = np.random.random([2, 3, 32]).astype("float32")
                result_np = max_pool1D_forward_naive(
                    input_np,
                    ksize=[16],
                    strides=[2],
                    paddings=[0],
                    adaptive=True,
                )

                exe = fluid.Executor(place)
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": input_np},
                    fetch_list=[result],
                )
                np.testing.assert_allclose(fetches[0], result_np, rtol=1e-05)
119 120 121 122 123 124 125

    def test_adaptive_max_pool1d(self):
        for place in self.places:
            self.check_adaptive_max_dygraph_results(place)
            self.check_adaptive_max_static_results(place)


126 127 128 129
class TestOutDtype(unittest.TestCase):
    def test_max_pool(self):
        api_fn = F.adaptive_max_pool1d
        shape = [1, 3, 32]
130 131 132 133 134 135
        check_out_dtype(
            api_fn,
            in_specs=[(shape,)],
            expect_dtypes=['float32', 'float64'],
            output_size=16,
        )
136 137


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