test_bicubic_interp_op.py 16.3 KB
Newer Older
X
xiaoting 已提交
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

X
xiaoting 已提交
17 18
import numpy as np
from op_test import OpTest
19

X
xiaoting 已提交
20
import paddle
21
import paddle.fluid as fluid
X
xiaoting 已提交
22
from paddle.fluid import Program, program_guard
L
Li Fuchen 已提交
23
from paddle.nn.functional import interpolate
X
xiaoting 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51


def cubic_1(x, a):
    return ((a + 2) * x - (a + 3)) * x * x + 1


def cubic_2(x, a):
    return ((a * x - 5 * a) * x + 8 * a) * x - 4 * a


def cubic_interp1d(x0, x1, x2, x3, t):
    param = [0, 0, 0, 0]
    a = -0.75
    x_1 = t
    x_2 = 1.0 - t
    param[0] = cubic_2(x_1 + 1.0, a)
    param[1] = cubic_1(x_1, a)
    param[2] = cubic_1(x_2, a)
    param[3] = cubic_2(x_2 + 1.0, a)
    return x0 * param[0] + x1 * param[1] + x2 * param[2] + x3 * param[3]


def value_bound(input, w, h, x, y):
    access_x = int(max(min(x, w - 1), 0))
    access_y = int(max(min(y, h - 1), 0))
    return input[:, :, access_y, access_x]


52 53 54 55 56 57 58 59 60
def bicubic_interp_np(
    input,
    out_h,
    out_w,
    out_size=None,
    actual_shape=None,
    align_corners=True,
    data_layout='kNCHW',
):
X
xiaoting 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73
    """trilinear interpolation implement in shape [N, C, H, W]"""
    if data_layout == "NHWC":
        input = np.transpose(input, (0, 3, 1, 2))  # NHWC => NCHW
    if out_size is not None:
        out_h = out_size[0]
        out_w = out_size[1]
    if actual_shape is not None:
        out_h = actual_shape[0]
        out_w = actual_shape[1]
    batch_size, channel, in_h, in_w = input.shape

    ratio_h = ratio_w = 0.0
    if out_h > 1:
74
        if align_corners:
X
xiaoting 已提交
75 76 77 78 79
            ratio_h = (in_h - 1.0) / (out_h - 1.0)
        else:
            ratio_h = 1.0 * in_h / out_h

    if out_w > 1:
80
        if align_corners:
X
xiaoting 已提交
81 82 83 84 85 86 87
            ratio_w = (in_w - 1.0) / (out_w - 1.0)
        else:
            ratio_w = 1.0 * in_w / out_w

    out = np.zeros((batch_size, channel, out_h, out_w))

    for k in range(out_h):
88
        if align_corners:
X
xiaoting 已提交
89 90 91
            h = ratio_h * k
        else:
            h = ratio_h * (k + 0.5) - 0.5
92
        input_y = np.floor(h)
X
xiaoting 已提交
93 94
        y_t = h - input_y
        for l in range(out_w):
95
            if align_corners:
X
xiaoting 已提交
96 97 98
                w = ratio_w * l
            else:
                w = ratio_w * (l + 0.5) - 0.5
99
            input_x = np.floor(w)
X
xiaoting 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
            x_t = w - input_x
            for i in range(batch_size):
                for j in range(channel):
                    coefficients = [0, 0, 0, 0]
                    for ii in range(4):
                        access_x_0 = int(max(min(input_x - 1, in_w - 1), 0))
                        access_x_1 = int(max(min(input_x + 0, in_w - 1), 0))
                        access_x_2 = int(max(min(input_x + 1, in_w - 1), 0))
                        access_x_3 = int(max(min(input_x + 2, in_w - 1), 0))
                        access_y = int(max(min(input_y - 1 + ii, in_h - 1), 0))

                        coefficients[ii] = cubic_interp1d(
                            input[i, j, access_y, access_x_0],
                            input[i, j, access_y, access_x_1],
114 115 116 117 118 119 120 121 122 123 124
                            input[i, j, access_y, access_x_2],
                            input[i, j, access_y, access_x_3],
                            x_t,
                        )
                    out[i, j, k, l] = cubic_interp1d(
                        coefficients[0],
                        coefficients[1],
                        coefficients[2],
                        coefficients[3],
                        y_t,
                    )
X
xiaoting 已提交
125 126 127 128 129 130 131 132 133 134 135 136
    if data_layout == "NHWC":
        out = np.transpose(out, (0, 2, 3, 1))  # NCHW => NHWC
    return out.astype(input.dtype)


class TestBicubicInterpOp(OpTest):
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
        self.data_layout = 'NCHW'
        self.init_test_case()
        self.op_type = "bicubic_interp"
137 138 139
        # NOTE(dev): some AsDispensible input is not used under imperative mode.
        # Skip check_eager while found them in Inputs.
        self.check_eager = True
X
xiaoting 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        input_np = np.random.random(self.input_shape).astype("float64")

        if self.data_layout == "NCHW":
            in_h = self.input_shape[2]
            in_w = self.input_shape[3]
        else:
            in_h = self.input_shape[1]
            in_w = self.input_shape[2]

        if self.scale > 0:
            out_h = int(in_h * self.scale)
            out_w = int(in_w * self.scale)
        else:
            out_h = self.out_h
            out_w = self.out_w

156 157 158 159 160 161 162 163 164
        output_np = bicubic_interp_np(
            input_np,
            out_h,
            out_w,
            self.out_size,
            self.actual_shape,
            self.align_corners,
            self.data_layout,
        )
X
xiaoting 已提交
165 166 167
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
168
            self.check_eager = False
X
xiaoting 已提交
169 170
        if self.actual_shape is not None:
            self.inputs['OutSize'] = self.actual_shape
171
            self.check_eager = False
X
xiaoting 已提交
172 173 174 175 176 177 178

        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
            'scale': self.scale,
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
179
            'data_layout': self.data_layout,
X
xiaoting 已提交
180 181 182 183
        }
        self.outputs = {'Out': output_np}

    def test_check_output(self):
184
        self.check_output(check_eager=self.check_eager)
X
xiaoting 已提交
185 186

    def test_check_grad(self):
187 188 189
        self.check_grad(
            ['X'], 'Out', in_place=True, check_eager=self.check_eager
        )
X
xiaoting 已提交
190 191 192 193 194 195

    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [2, 3, 5, 5]
        self.out_h = 2
        self.out_w = 2
196
        self.scale = 0.0
X
xiaoting 已提交
197 198 199 200 201 202 203 204 205 206
        self.out_size = np.array([3, 3]).astype("int32")
        self.align_corners = True


class TestBicubicInterpCase1(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
207
        self.scale = 0.0
X
xiaoting 已提交
208 209 210 211 212 213 214 215 216
        self.align_corners = True


class TestBicubicInterpCase2(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 10
        self.out_w = 8
217
        self.scale = 0.0
X
xiaoting 已提交
218 219 220 221 222 223 224 225 226
        self.align_corners = True


class TestBicubicInterpCase3(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [1, 1, 32, 64]
        self.out_h = 64
        self.out_w = 32
227
        self.scale = 0.0
X
xiaoting 已提交
228 229 230 231 232 233 234 235 236
        self.align_corners = False


class TestBicubicInterpCase4(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
237
        self.scale = 0.0
X
xiaoting 已提交
238 239 240 241 242 243 244 245 246 247
        self.out_size = np.array([2, 2]).astype("int32")
        self.align_corners = True


class TestBicubicInterpCase5(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 11
        self.out_w = 11
248
        self.scale = 0.0
X
xiaoting 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        self.out_size = np.array([6, 4]).astype("int32")
        self.align_corners = False


class TestBicubicInterpCase6(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [1, 1, 32, 64]
        self.out_h = 64
        self.out_w = 32
        self.scale = 0
        self.out_size = np.array([64, 32]).astype("int32")
        self.align_corners = False


class TestBicubicInterpSame(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [2, 3, 32, 64]
        self.out_h = 32
        self.out_w = 64
270
        self.scale = 0.0
X
xiaoting 已提交
271 272 273 274 275 276 277 278 279
        self.align_corners = True


class TestBicubicInterpDataLayout(TestBicubicInterpOp):
    def init_test_case(self):
        self.interp_method = 'bicubic'
        self.input_shape = [2, 5, 5, 3]
        self.out_h = 2
        self.out_w = 2
280
        self.scale = 0.0
X
xiaoting 已提交
281 282 283 284 285 286 287
        self.out_size = np.array([3, 3]).astype("int32")
        self.align_corners = True
        self.data_layout = "NHWC"


class TestBicubicInterpOpAPI(unittest.TestCase):
    def test_case(self):
288
        np.random.seed(200)
X
xiaoting 已提交
289 290 291 292 293 294 295 296
        x_data = np.random.random((2, 3, 6, 6)).astype("float32")
        dim_data = np.array([12]).astype("int32")
        shape_data = np.array([12, 12]).astype("int32")
        actual_size_data = np.array([12, 12]).astype("int32")
        scale_data = np.array([2.0]).astype("float32")

        prog = fluid.Program()
        startup_prog = fluid.Program()
297 298 299 300 301
        place = (
            fluid.CUDAPlace(0)
            if fluid.core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
X
xiaoting 已提交
302 303 304 305 306 307

        with fluid.program_guard(prog, startup_prog):

            x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")

            dim = fluid.data(name="dim", shape=[1], dtype="int32")
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
            shape_tensor = fluid.data(
                name="shape_tensor", shape=[2], dtype="int32"
            )
            actual_size = fluid.data(
                name="actual_size", shape=[2], dtype="int32"
            )
            scale_tensor = fluid.data(
                name="scale_tensor", shape=[1], dtype="float32"
            )

            out1 = interpolate(
                x, size=[12, 12], mode='bicubic', align_corners=False
            )
            out2 = interpolate(
                x, size=[12, dim], mode='bicubic', align_corners=False
            )
            out3 = interpolate(
                x, size=shape_tensor, mode='bicubic', align_corners=False
            )
            out4 = interpolate(
                x, size=[12, 12], mode='bicubic', align_corners=False
            )
            out5 = interpolate(
                x,
                scale_factor=scale_tensor,
                mode='bicubic',
                align_corners=False,
            )
X
xiaoting 已提交
336 337 338

            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
            results = exe.run(
                fluid.default_main_program(),
                feed={
                    "x": x_data,
                    "dim": dim_data,
                    "shape_tensor": shape_data,
                    "actual_size": actual_size_data,
                    "scale_tensor": scale_data,
                },
                fetch_list=[out1, out2, out3, out4, out5],
                return_numpy=True,
            )

            expect_res = bicubic_interp_np(
                x_data, out_h=12, out_w=12, align_corners=False
            )
X
xiaoting 已提交
355
            for res in results:
356
                np.testing.assert_allclose(res, expect_res, rtol=1e-05)
X
xiaoting 已提交
357 358 359

        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(x_data)
360 361 362
            interp = interpolate(
                x, size=[12, 12], mode='bicubic', align_corners=False
            )
X
xiaoting 已提交
363
            dy_result = interp.numpy()
364 365 366
            expect = bicubic_interp_np(
                x_data, out_h=12, out_w=12, align_corners=False
            )
367
            np.testing.assert_allclose(dy_result, expect, rtol=1e-05)
X
xiaoting 已提交
368 369 370 371 372 373


class TestBicubicOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # the input of interpoalte must be Variable.
374 375 376
            x1 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
            )
X
xiaoting 已提交
377 378 379 380 381 382
            self.assertRaises(TypeError, interpolate, x1)

            def test_mode_type():
                # mode must be "BILINEAR" "TRILINEAR" "NEAREST" "BICUBIC"
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")

383 384 385
                out = interpolate(
                    x, size=[12, 12], mode='UNKONWN', align_corners=False
                )
X
xiaoting 已提交
386 387 388

            def test_input_shape():
                x = fluid.data(name="x", shape=[2], dtype="float32")
389 390 391
                out = interpolate(
                    x, size=[12, 12], mode='BICUBIC', align_corners=False
                )
X
xiaoting 已提交
392 393 394

            def test_align_corcers():
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
395
                interpolate(x, size=[12, 12], mode='BICUBIC', align_corners=3)
X
xiaoting 已提交
396 397 398

            def test_out_shape():
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
399 400 401
                out = interpolate(
                    x, size=[12], mode='bicubic', align_corners=False
                )
X
xiaoting 已提交
402 403 404

            def test_attr_data_format():
                # for 5-D input, data_format only can be NCDHW or NDHWC
405 406 407 408 409 410 411 412 413
                input = fluid.data(
                    name="input", shape=[2, 3, 6, 9, 4], dtype="float32"
                )
                out = interpolate(
                    input,
                    size=[4, 8, 4, 5],
                    mode='trilinear',
                    data_format='NHWC',
                )
X
xiaoting 已提交
414 415 416

            def test_actual_shape():
                # the actual_shape  must be Variable.
417 418 419 420 421 422
                x = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
                out = interpolate(
                    x, size=[12, 12], mode='BICUBIC', align_corners=False
                )
X
xiaoting 已提交
423 424 425 426

            def test_scale_value():
                # the scale must be greater than zero.
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
427 428 429 430 431 432 433
                out = interpolate(
                    x,
                    size=None,
                    mode='BICUBIC',
                    align_corners=False,
                    scale_factor=-2.0,
                )
X
xiaoting 已提交
434 435 436

            def test_attr_5D_input():
                # for 5-D input, data_format only can be NCDHW or NDHWC
437 438 439 440 441 442 443 444 445
                input = fluid.data(
                    name="input", shape=[2, 3, 6, 9, 4], dtype="float32"
                )
                out = interpolate(
                    input,
                    size=[4, 8, 4, 5],
                    mode='trilinear',
                    data_format='NDHWC',
                )
X
xiaoting 已提交
446 447 448 449

            def test_scale_type():
                # the scale must be greater than zero.
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
450 451 452 453 454 455 456 457 458 459
                scale = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
                out = interpolate(
                    x,
                    size=None,
                    mode='bicubic',
                    align_corners=False,
                    scale_factor=scale,
                )
X
xiaoting 已提交
460 461 462

            def test_align_mode():
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
463 464 465 466 467 468 469 470
                out = interpolate(
                    x,
                    size=None,
                    mode='nearest',
                    align_corners=False,
                    align_mode=2,
                    scale_factor=1.0,
                )
X
xiaoting 已提交
471 472 473

            def test_outshape_and_scale():
                x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
474 475 476 477 478 479 480
                out = interpolate(
                    x,
                    size=None,
                    mode='bicubic',
                    align_corners=False,
                    scale_factor=None,
                )
X
xiaoting 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

            self.assertRaises(ValueError, test_mode_type)
            self.assertRaises(ValueError, test_input_shape)
            self.assertRaises(TypeError, test_align_corcers)
            self.assertRaises(ValueError, test_attr_data_format)
            self.assertRaises(TypeError, test_actual_shape)
            self.assertRaises(ValueError, test_scale_value)
            self.assertRaises(ValueError, test_out_shape)
            self.assertRaises(ValueError, test_attr_5D_input)
            self.assertRaises(TypeError, test_scale_type)
            self.assertRaises(ValueError, test_align_mode)
            self.assertRaises(ValueError, test_outshape_and_scale)


if __name__ == "__main__":
496
    paddle.enable_static()
X
xiaoting 已提交
497
    unittest.main()