test_unpool_op.py 17.2 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15
import os
S
sweetsky0901 已提交
16 17
import unittest
import numpy as np
18
from op_test import OpTest
X
xiaoting 已提交
19
import paddle
20 21 22 23
import paddle.nn.functional as F
from paddle.fluid import Program, program_guard

from test_attribute_var import UnittestBase
S
sweetsky0901 已提交
24 25


26 27 28 29
def _unpool_output_size(x, kernel_size, stride, padding, output_size):
    input_size = x.shape
    default_size = []
    for d in range(len(kernel_size)):
30 31
        default_size.append((input_size[-len(kernel_size) + d] - 1) *
                            stride[d] + kernel_size[d] - 2 * padding[d])
32 33 34 35 36 37 38 39 40
    if output_size is None:
        ret = default_size
    else:
        ret = output_size
    return ret


def unpool2dmax_forward_naive(input, indices, ksize, strides, paddings,
                              output_size):
S
sweetsky0901 已提交
41
    s0, s1, s2, s3 = input.shape
42 43 44 45
    output_size = _unpool_output_size(input, ksize, strides, paddings,
                                      output_size)
    out_hsize = output_size[0]
    out_wsize = output_size[1]
46
    out = np.zeros((s0, s1, out_hsize, out_wsize))
47 48 49 50
    for nidx in range(s0):
        for cidx in range(s1):
            for h in range(s2):
                for w in range(s3):
S
sweetsky0901 已提交
51
                    index = indices[nidx, cidx, h, w]
M
minqiyang 已提交
52
                    hidx = (index - index % out_wsize) // out_wsize
53
                    widx = index % out_wsize
54
                    out[nidx, cidx, hidx, widx] = \
S
sweetsky0901 已提交
55
                            input[nidx, cidx, h, w]
S
sweetsky0901 已提交
56 57 58 59

    return out


X
xiaoting 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
def max_unpool2d_wrapper(x,
                         indices,
                         kernel_size,
                         stride=None,
                         padding=0,
                         output_size=None,
                         data_format="NCHW",
                         name=None):
    out = paddle.nn.functional.max_unpool2d(x,
                                            indices,
                                            kernel_size,
                                            stride=stride,
                                            padding=padding,
                                            data_format=data_format,
                                            output_size=output_size,
                                            name=name)
    return out


S
sweetsky0901 已提交
79
class TestUnpoolOp(OpTest):
80

S
sweetsky0901 已提交
81 82
    def setUp(self):
        self.op_type = "unpool"
X
xiaoting 已提交
83
        self.python_api = max_unpool2d_wrapper
S
sweetsky0901 已提交
84
        self.init_test_case()
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        input = np.random.randint(0, 100, self.shape)
        nsize, csize, hsize, wsize = input.shape
        self.output_size = _unpool_output_size(input, self.ksize, self.strides,
                                               self.paddings, self.output_size)
        indices = np.random.permutation(
            np.arange(0, self.output_size[0] * self.output_size[1]))[:hsize *
                                                                     wsize]
        indices = np.reshape(indices, [hsize, wsize])
        idx_list = []
        for n in range(nsize):
            c_list = []
            for c in range(csize):
                c_list.append(indices.tolist())
            idx_list.append(c_list)
        indices = np.array(idx_list)

S
sweetsky0901 已提交
101
        output = self.unpool2d_forward_naive(input, indices, self.ksize, \
102 103
                self.strides, self.paddings, self.output_size).astype("float64")

S
sweetsky0901 已提交
104
        self.inputs = {
105
            'X': input.astype('float64'),
S
sweetsky0901 已提交
106
            'Indices': indices.astype('int32')
S
sweetsky0901 已提交
107
        }
S
sweetsky0901 已提交
108
        self.attrs = {
S
sweetsky0901 已提交
109 110 111 112
            'strides': self.strides,
            'paddings': self.paddings,
            'ksize': self.ksize,
            'unpooling_type': self.unpooling_type,
113
            'output_size': self.output_size,
S
sweetsky0901 已提交
114
        }
115
        self.outputs = {'Out': output.astype('float64')}
S
sweetsky0901 已提交
116 117

    def test_check_output(self):
X
xiaoting 已提交
118
        self.check_output(check_eager=True)
S
sweetsky0901 已提交
119 120

    def test_check_grad(self):
X
xiaoting 已提交
121
        self.check_grad(['X'], 'Out', check_eager=True)
S
sweetsky0901 已提交
122 123

    def init_test_case(self):
S
sweetsky0901 已提交
124
        self.unpool2d_forward_naive = unpool2dmax_forward_naive
S
sweetsky0901 已提交
125
        self.unpooling_type = "max"
126 127 128 129 130 131 132 133
        self.shape = [2, 4, 7, 8]
        self.ksize = [2, 2]
        self.strides = [2, 2]
        self.paddings = [0, 0]
        self.output_size = None


class TestUnpoolOpcase1(TestUnpoolOp):
134

135 136 137 138 139 140 141 142 143 144
    def init_test_case(self):
        self.unpool2d_forward_naive = unpool2dmax_forward_naive
        self.unpooling_type = "max"
        self.shape = [3, 2, 5, 5]
        self.ksize = [4, 4]
        self.strides = [2, 2]
        self.paddings = [0, 0]
        self.output_size = None


145
class TestUnpoolOpOutputsize(TestUnpoolOp):
146

147 148 149 150 151 152 153
    def init_test_case(self):
        self.unpool2d_forward_naive = unpool2dmax_forward_naive
        self.unpooling_type = "max"
        self.shape = [3, 2, 5, 5]
        self.ksize = [4, 4]
        self.strides = [2, 2]
        self.paddings = [0, 0]
X
xiaoting 已提交
154
        self.output_size = [12, 12]
155 156


157
class TestUnpoolOpOutput(TestUnpoolOp):
158

159 160 161 162 163
    def init_test_case(self):
        self.unpool2d_forward_naive = unpool2dmax_forward_naive
        self.unpooling_type = "max"
        self.shape = [3, 2, 5, 5]
        self.ksize = [4, 4]
S
sweetsky0901 已提交
164 165
        self.strides = [2, 2]
        self.paddings = [0, 0]
X
xiaoting 已提交
166
        self.output_size = [12, 12]
167 168 169


class TestUnpoolOpException(unittest.TestCase):
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    def test_exception(self):
        import paddle.nn.functional as F
        import paddle

        def indices_size_error():
            data = paddle.randint(shape=[1, 1, 3, 3])
            indices = paddle.reshape(paddle.arange(0, 12), shape[1, 1, 3, 4])
            MaxPool2D = F.maxunpool2d(data, indices, kernel_size=2, stride=2)

        def indices_value_error():
            data = paddle.randint(shape=[1, 1, 3, 3])
            indices = paddle.reshape(paddle.arange(4, 40), shape[1, 1, 3, 4])
            MaxPool2D = F.maxunpool2d(data, indices, kernel_size=2, stride=2)

        def data_format_error():
            data = paddle.randint(shape=[1, 1, 3, 3])
            indices = paddle.reshape(paddle.arange(4, 40), shape[1, 1, 3, 4])
188 189 190 191 192
            MaxPool2D = F.maxunpool2d(data,
                                      indices,
                                      kernel_size=2,
                                      stride=2,
                                      data_format="NHWC")
193 194 195 196

        def data_outputsize_error():
            data = paddle.randint(shape=[1, 1, 3, 3])
            indices = paddle.reshape(paddle.arange(4, 40), shape[1, 1, 3, 4])
197 198 199 200 201
            MaxPool2D = F.maxunpool2d(data,
                                      indices,
                                      kernel_size=2,
                                      stride=2,
                                      output_size=[5, 6, 7, 8])
202 203 204 205

        def data_outputsize_error2():
            data = paddle.randint(shape=[1, 1, 3, 3])
            indices = paddle.reshape(paddle.arange(4, 40), shape[1, 1, 3, 4])
206 207 208 209 210
            MaxPool2D = F.maxunpool2d(data,
                                      indices,
                                      kernel_size=2,
                                      stride=2,
                                      output_size=[100, 100])
211 212 213 214 215 216 217 218 219

        self.assertRaises(ValueError, indices_size_error)
        self.assertRaises(ValueError, indices_value_error)
        self.assertRaises(ValueError, data_format_error)
        self.assertRaises(ValueError, data_outputsize_error)
        self.assertRaises(ValueError, data_outputsize_error2)


class TestUnpoolOpAPI_dy(unittest.TestCase):
220

221 222 223 224 225 226 227 228 229 230 231 232
    def test_case(self):
        import paddle
        import paddle.nn.functional as F
        import paddle.fluid.core as core
        import paddle.fluid as fluid
        import numpy as np

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
        with fluid.dygraph.guard(place):
233 234
            input_data = np.array([[[[1, 2, 3, 4], [5, 6, 7,
                                                    8], [9, 10, 11, 12],
235 236
                                     [13, 14, 15, 16]]]]).astype("float32")
            input_x = paddle.to_tensor(input_data)
237 238 239 240 241 242 243 244 245
            output, indices = F.max_pool2d(input_x,
                                           kernel_size=2,
                                           stride=2,
                                           return_mask=True)
            out_pp = F.max_unpool2d(output,
                                    indices,
                                    kernel_size=2,
                                    stride=2,
                                    output_size=(5, 5))
246 247 248 249
            output_np = output.numpy()
            indices_np = indices.numpy()
            expect_res =unpool2dmax_forward_naive(output_np, indices_np, [2,2], \
                [2,2], [0,0], [5,5]).astype("float64")
250
            np.testing.assert_allclose(out_pp.numpy(), expect_res, rtol=1e-05)
251 252 253


class TestUnpoolOpAPI_dy2(unittest.TestCase):
254

255 256 257 258 259 260 261 262 263 264 265 266
    def test_case(self):
        import paddle
        import paddle.nn.functional as F
        import paddle.fluid.core as core
        import paddle.fluid as fluid
        import numpy as np

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
        with fluid.dygraph.guard(place):
267 268
            input_data = np.array([[[[1, 2, 3, 4], [5, 6, 7,
                                                    8], [9, 10, 11, 12],
269 270
                                     [13, 14, 15, 16]]]]).astype("float32")
            input_x = paddle.to_tensor(input_data)
271 272 273 274 275 276 277 278 279
            output, indices = F.max_pool2d(input_x,
                                           kernel_size=2,
                                           stride=2,
                                           return_mask=True)
            out_pp = F.max_unpool2d(output,
                                    indices,
                                    kernel_size=2,
                                    stride=None,
                                    output_size=(5, 5))
280 281 282 283
            output_np = output.numpy()
            indices_np = indices.numpy()
            expect_res =unpool2dmax_forward_naive(output_np, indices_np, [2,2], \
                [2,2], [0,0], [5,5]).astype("float64")
284
            np.testing.assert_allclose(out_pp.numpy(), expect_res, rtol=1e-05)
285 286 287


class TestUnpoolOpAPI_dy3(unittest.TestCase):
288

289 290 291 292 293 294 295 296 297 298 299
    def test_case(self):
        import paddle
        import paddle.fluid.core as core
        import paddle.fluid as fluid
        import numpy as np

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
        with fluid.dygraph.guard(place):
300 301
            input_data = np.array([[[[1, 2, 3, 4], [5, 6, 7,
                                                    8], [9, 10, 11, 12],
302 303
                                     [13, 14, 15, 16]]]]).astype("float32")
            input_x = paddle.to_tensor(input_data)
304 305 306
            Pool2d = paddle.nn.MaxPool2D(kernel_size=2,
                                         stride=2,
                                         return_mask=True)
307 308 309 310 311 312 313 314
            UnPool = paddle.nn.MaxUnPool2D(kernel_size=2, stride=2)

            output, indices = Pool2d(input_x)
            out_pp = UnPool(output, indices)
            output_np = output.numpy()
            indices_np = indices.numpy()
            expect_res =unpool2dmax_forward_naive(output_np, indices_np, [2,2], \
                [2,2], [0,0], [4,4]).astype("float64")
315
            np.testing.assert_allclose(out_pp.numpy(), expect_res, rtol=1e-05)
316 317 318


class TestUnpoolOpAPI_st(unittest.TestCase):
319

320 321 322 323 324 325 326 327 328 329 330
    def test_case(self):
        import paddle
        import paddle.nn.functional as F
        import paddle.fluid.core as core
        import paddle.fluid as fluid
        paddle.enable_static()

        input_data = np.array([[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
                                 [13, 14, 15, 16]]]]).astype("float32")

        x = fluid.data(name="x", shape=[1, 1, 4, 4], dtype="float32")
331 332 333 334 335 336 337 338 339
        output, indices = F.max_pool2d(x,
                                       kernel_size=2,
                                       stride=2,
                                       return_mask=True)
        unpool_out = F.max_unpool2d(output,
                                    indices,
                                    kernel_size=2,
                                    stride=None,
                                    output_size=(5, 5))
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())

        results = exe.run(paddle.fluid.default_main_program(),\
                          feed={"x":input_data},
                          fetch_list=[unpool_out],
                          return_numpy=True)

        pool_out_np = np.array([[[[6., 8.], [14., 16.]]]]).astype("float32")
        indices_np = np.array([[[[5, 7], [13, 15]]]]).astype("int32")
        expect_res =unpool2dmax_forward_naive(pool_out_np, indices_np, [2,2], \
            [2,2], [0,0], [5,5]).astype("float64")
356
        np.testing.assert_allclose(results[0], expect_res, rtol=1e-05)
S
sweetsky0901 已提交
357

S
sweetsky0901 已提交
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
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):
        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]

            out = self.call_func(feat)

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

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

    def path_prefix(self):
        return 'unpool_var'

    def var_prefix(self):
        return "Vars["

    def call_func(self, x):
        output_size = [paddle.assign([7]), paddle.assign([7])]
        pool_out, indices = F.max_pool2d(x,
                                         kernel_size=2,
                                         stride=2,
                                         padding=0,
                                         return_mask=True)
        # pool_out shape: [1, 1, 6, 6],  indices shape: [1, 1, 6, 6]
        unpool_out = F.max_unpool2d(pool_out,
                                    indices,
                                    kernel_size=2,
                                    padding=0,
                                    output_size=output_size)
        # unpool_out shape: [1, 1, 7, 7]
        return unpool_out


class TestZOutputSizeTensor2(unittest.TestCase):

    def setUp(self):
        paddle.disable_static()

    def tearDown(self):
        paddle.enable_static()

    def test_dygraph(self):
        x = paddle.randn([1, 3, 6, 6])
        pool_out, indices = F.max_pool2d(x,
                                         kernel_size=2,
                                         stride=2,
                                         padding=0,
                                         return_mask=True)
        output_size = [paddle.assign([7]), paddle.assign([7])]
        unpool_out = F.max_unpool2d(pool_out,
                                    indices,
                                    kernel_size=2,
                                    padding=0,
                                    output_size=output_size)
        np.testing.assert_array_equal(unpool_out.shape, [1, 3, 7, 7])


436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
class TestZOutputSizeTensor3(unittest.TestCase):

    def setUp(self):
        paddle.disable_static()

    def tearDown(self):
        paddle.enable_static()

    def test_dygraph(self):
        x = paddle.randn([1, 3, 6, 6])
        pool_out, indices = F.max_pool2d(x,
                                         kernel_size=2,
                                         stride=2,
                                         padding=0,
                                         return_mask=True)
        output_size = [
            paddle.assign([1]),
            paddle.assign([1]),
            paddle.assign([7]),
            paddle.assign([7])
        ]
        unpool_out = F.max_unpool2d(pool_out,
                                    indices,
                                    kernel_size=2,
                                    padding=0,
                                    output_size=output_size)
        np.testing.assert_array_equal(unpool_out.shape, [1, 3, 7, 7])


S
sweetsky0901 已提交
465
if __name__ == '__main__':
466
    paddle.enable_static()
S
sweetsky0901 已提交
467
    unittest.main()