test_adaptive_avg_pool2d.py 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   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.

from __future__ import print_function
from __future__ import division

18
import os
19 20 21 22 23 24 25 26 27
import unittest
import numpy as np

import paddle.fluid.core as core
from op_test import OpTest
import paddle
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard

28 29
from test_attribute_var import UnittestBase

30 31 32 33 34 35 36 37 38

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


39 40 41
def adaptive_pool2d_forward(x,
                            output_size,
                            data_format='NCHW',
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
                            pool_type="avg"):

    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 (isinstance(output_size, int) or output_size == None):
        H_out = output_size
        W_out = output_size
        output_size = [H_out, W_out]
    else:
        H_out, W_out = output_size

    if output_size[0] == None:
        output_size[0] = H
        H_out = H
    if output_size[1] == None:
        output_size[1] = W
        W_out = W

    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):
        in_h_start = adaptive_start_index(i, H, output_size[0])
        in_h_end = adaptive_end_index(i, H, output_size[0])

        for j in range(W_out):
            in_w_start = adaptive_start_index(j, W, output_size[1])
            in_w_end = adaptive_end_index(j, W, output_size[1])

            if data_format == 'NCHW':
                x_masked = x[:, :, in_h_start:in_h_end, in_w_start:in_w_end]
                if pool_type == 'avg':
76 77
                    field_size = ((in_h_end - in_h_start) *
                                  (in_w_end - in_w_start))
78 79 80 81 82 83
                    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':
84 85
                    field_size = ((in_h_end - in_h_start) *
                                  (in_w_end - in_w_start))
86 87 88 89 90 91
                    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


C
cnn 已提交
92
class TestAdaptiveAvgPool2DAPI(unittest.TestCase):
93

94 95
    def setUp(self):
        self.x_np = np.random.random([2, 3, 7, 7]).astype("float32")
96 97 98
        self.res_1_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[3, 3],
                                                pool_type="avg")
99

100 101 102
        self.res_2_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=5,
                                                pool_type="avg")
103

104 105 106
        self.res_3_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[2, 5],
                                                pool_type="avg")
107

108 109 110 111
        self.res_4_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[3, 3],
                                                pool_type="avg",
                                                data_format="NHWC")
112

113 114 115
        self.res_5_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[None, 3],
                                                pool_type="avg")
116 117 118 119 120 121

    def test_static_graph(self):
        for use_cuda in ([False, True]
                         if core.is_compiled_with_cuda() else [False]):
            place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
            paddle.enable_static()
122
            x = paddle.fluid.data(name="x", shape=[2, 3, 7, 7], dtype="float32")
123

124 125
            out_1 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[3, 3])
126 127 128

            out_2 = paddle.nn.functional.adaptive_avg_pool2d(x=x, output_size=5)

129 130
            out_3 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[2, 5])
131

132 133 134
            out_4 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[3, 3],
                                                             data_format="NHWC")
135 136 137 138 139

            out_5 = paddle.nn.functional.adaptive_avg_pool2d(
                x=x, output_size=[None, 3])

            exe = paddle.static.Executor(place=place)
140 141 142 143
            [res_1, res_2, res_3, res_4,
             res_5] = exe.run(fluid.default_main_program(),
                              feed={"x": self.x_np},
                              fetch_list=[out_1, out_2, out_3, out_4, out_5])
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

            assert np.allclose(res_1, self.res_1_np)

            assert np.allclose(res_2, self.res_2_np)

            assert np.allclose(res_3, self.res_3_np)

            assert np.allclose(res_4, self.res_4_np)

            assert np.allclose(res_5, self.res_5_np)

    def test_dynamic_graph(self):
        for use_cuda in ([False, True]
                         if core.is_compiled_with_cuda() else [False]):
            place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
            paddle.disable_static(place=place)
Z
Zhou Wei 已提交
160
            x = paddle.to_tensor(self.x_np)
161

162 163
            out_1 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[3, 3])
164 165 166

            out_2 = paddle.nn.functional.adaptive_avg_pool2d(x=x, output_size=5)

167 168
            out_3 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[2, 5])
169

170 171 172
            out_4 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                             output_size=[3, 3],
                                                             data_format="NHWC")
173 174 175 176

            out_5 = paddle.nn.functional.adaptive_avg_pool2d(
                x=x, output_size=[None, 3])

177 178 179
            out_6 = paddle.nn.functional.interpolate(x=x,
                                                     mode="area",
                                                     size=[2, 5])
180

181 182 183 184 185 186 187 188 189 190
            assert np.allclose(out_1.numpy(), self.res_1_np)

            assert np.allclose(out_2.numpy(), self.res_2_np)

            assert np.allclose(out_3.numpy(), self.res_3_np)

            assert np.allclose(out_4.numpy(), self.res_4_np)

            assert np.allclose(out_5.numpy(), self.res_5_np)

191 192
            assert np.allclose(out_6.numpy(), self.res_3_np)

193

C
cnn 已提交
194
class TestAdaptiveAvgPool2DClassAPI(unittest.TestCase):
195

196 197
    def setUp(self):
        self.x_np = np.random.random([2, 3, 7, 7]).astype("float32")
198 199 200
        self.res_1_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[3, 3],
                                                pool_type="avg")
201

202 203 204
        self.res_2_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=5,
                                                pool_type="avg")
205

206 207 208
        self.res_3_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[2, 5],
                                                pool_type="avg")
209

210 211 212 213
        self.res_4_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[3, 3],
                                                pool_type="avg",
                                                data_format="NHWC")
214

215 216 217
        self.res_5_np = adaptive_pool2d_forward(x=self.x_np,
                                                output_size=[None, 3],
                                                pool_type="avg")
218 219 220 221 222 223

    def test_static_graph(self):
        for use_cuda in ([False, True]
                         if core.is_compiled_with_cuda() else [False]):
            place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
            paddle.enable_static()
224
            x = paddle.fluid.data(name="x", shape=[2, 3, 7, 7], dtype="float32")
225

C
cnn 已提交
226
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[3, 3])
227 228
            out_1 = adaptive_avg_pool(x=x)

C
cnn 已提交
229
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=5)
230 231
            out_2 = adaptive_avg_pool(x=x)

C
cnn 已提交
232
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[2, 5])
233 234
            out_3 = adaptive_avg_pool(x=x)

235 236
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[3, 3],
                                                            data_format="NHWC")
237 238
            out_4 = adaptive_avg_pool(x=x)

C
cnn 已提交
239
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(
240 241 242 243
                output_size=[None, 3])
            out_5 = adaptive_avg_pool(x=x)

            exe = paddle.static.Executor(place=place)
244 245 246 247
            [res_1, res_2, res_3, res_4,
             res_5] = exe.run(fluid.default_main_program(),
                              feed={"x": self.x_np},
                              fetch_list=[out_1, out_2, out_3, out_4, out_5])
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

            assert np.allclose(res_1, self.res_1_np)

            assert np.allclose(res_2, self.res_2_np)

            assert np.allclose(res_3, self.res_3_np)

            assert np.allclose(res_4, self.res_4_np)

            assert np.allclose(res_5, self.res_5_np)

    def test_dynamic_graph(self):
        for use_cuda in ([False, True]
                         if core.is_compiled_with_cuda() else [False]):
            place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
            paddle.disable_static(place=place)
Z
Zhou Wei 已提交
264
            x = paddle.to_tensor(self.x_np)
265

C
cnn 已提交
266
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[3, 3])
267 268
            out_1 = adaptive_avg_pool(x=x)

C
cnn 已提交
269
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=5)
270 271
            out_2 = adaptive_avg_pool(x=x)

C
cnn 已提交
272
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[2, 5])
273 274
            out_3 = adaptive_avg_pool(x=x)

275 276
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=[3, 3],
                                                            data_format="NHWC")
277 278
            out_4 = adaptive_avg_pool(x=x)

C
cnn 已提交
279
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(
280 281 282 283 284 285 286 287 288 289 290 291 292 293
                output_size=[None, 3])
            out_5 = adaptive_avg_pool(x=x)

            assert np.allclose(out_1.numpy(), self.res_1_np)

            assert np.allclose(out_2.numpy(), self.res_2_np)

            assert np.allclose(out_3.numpy(), self.res_3_np)

            assert np.allclose(out_4.numpy(), self.res_4_np)

            assert np.allclose(out_5.numpy(), self.res_5_np)


294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
class TestOutputSizeTensor(UnittestBase):

    def init_info(self):
        self.shapes = [[1, 3, 6, 6]]
        self.save_path = os.path.join(self.temp_dir.name, self.path_prefix())

    def test_static(self):
        paddle.enable_static()
        main_prog = Program()
        starup_prog = Program()
        with program_guard(main_prog, starup_prog):
            fc = paddle.nn.Linear(6, 6)
            x = paddle.randn(self.shapes[0])
            x.stop_gradient = False
            feat = fc(x)  # [1,3,6,6]

            out1, out2 = self.call_func(feat)

            sgd = paddle.optimizer.SGD()
            sgd.minimize(paddle.mean(out1 + out2))
            self.assertTrue(self.var_prefix() in str(main_prog))

            exe = paddle.static.Executor()
            exe.run(starup_prog)
            res = exe.run(fetch_list=[out1, out2])
            np.testing.assert_allclose(res[0], res[1])
            paddle.static.save_inference_model(self.save_path, [x],
                                               [out1, out2], exe)
            # Test for Inference Predictor
            infer_outs = self.infer_prog()
            np.testing.assert_array_equal(infer_outs[0].shape, (1, 3, 3, 3))
            np.testing.assert_allclose(infer_outs[0], infer_outs[1])

    def path_prefix(self):
        return 'pool2d_tensor'

    def var_prefix(self):
        return "Vars["

    def call_func(self, x):
        # list[Tensor]
        output_size = [paddle.assign([3]), paddle.assign([3])]
        out1 = paddle.nn.functional.adaptive_avg_pool2d(x=x, output_size=[3, 3])
        out2 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                        output_size=output_size)
        return out1, out2


class TestOutputSizeListTensor(TestOutputSizeTensor):

    def path_prefix(self):
        return 'pool2d_tensors'

    def call_func(self, x):
        # list[int, Tensor]
        output_size = [paddle.assign([3]), 3]
        out1 = paddle.nn.functional.adaptive_avg_pool2d(x=x, output_size=[3, 3])
        out2 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                        output_size=output_size)
        return out1, out2


class TestOutputSizeListTensor2(TestOutputSizeTensor):

    def path_prefix(self):
        return 'pool2d_tensor2'

    def call_func(self, x):
        # A Tensor
        output_size = paddle.assign([3, 3])
        out1 = paddle.nn.functional.adaptive_avg_pool2d(x=x, output_size=[3, 3])
        out2 = paddle.nn.functional.adaptive_avg_pool2d(x=x,
                                                        output_size=output_size)
        return out1, out2


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