test_bilinear_interp_op.py 16.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2018 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

import unittest
import numpy as np
19
from op_test import OpTest
20
import paddle.fluid.core as core
21
import paddle.fluid as fluid
22 23
import paddle
paddle.enable_static()
24 25


26 27 28 29 30 31
def bilinear_interp_np(input,
                       out_h,
                       out_w,
                       out_size=None,
                       actual_shape=None,
                       align_corners=True,
32 33
                       align_mode=0,
                       data_layout='NCHW'):
34
    """bilinear interpolation implement in shape [N, C, H, W]"""
35 36
    if data_layout == "NHWC":
        input = np.transpose(input, (0, 3, 1, 2))  # NHWC => NCHW
37 38 39
    if out_size is not None:
        out_h = out_size[0]
        out_w = out_size[1]
40 41 42
    if actual_shape is not None:
        out_h = actual_shape[0]
        out_w = actual_shape[1]
43
    batch_size, channel, in_h, in_w = input.shape
44 45

    ratio_h = ratio_w = 0.0
T
tink2123 已提交
46 47 48 49 50 51 52 53 54 55
    if out_h > 1:
        if (align_corners):
            ratio_h = (in_h - 1.0) / (out_h - 1.0)
        else:
            ratio_h = 1.0 * in_h / out_h
    if out_w > 1:
        if (align_corners):
            ratio_w = (in_w - 1.0) / (out_w - 1.0)
        else:
            ratio_w = 1.0 * in_w / out_w
56 57

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

59
    for i in range(out_h):
60 61 62 63 64
        if (align_mode == 0 and not align_corners):
            h = int(ratio_h * (i + 0.5) - 0.5)
        else:
            h = int(ratio_h * i)

T
tink2123 已提交
65
        h = max(0, h)
66
        hid = 1 if h < in_h - 1 else 0
67
        if (align_mode == 0 and not align_corners):
68 69
            idx_src_h = max(ratio_h * (i + 0.5) - 0.5, 0)
            h1lambda = idx_src_h - h
70 71
        else:
            h1lambda = ratio_h * i - h
72 73
        h2lambda = 1.0 - h1lambda
        for j in range(out_w):
74 75 76 77
            if (align_mode == 0 and not align_corners):
                w = int(ratio_w * (j + 0.5) - 0.5)
            else:
                w = int(ratio_w * j)
T
tink2123 已提交
78
            w = max(0, w)
79
            wid = 1 if w < in_w - 1 else 0
80
            if (align_mode == 0 and not align_corners):
81 82
                idx_src_w = max(ratio_w * (j + 0.5) - 0.5, 0)
                w1lambda = idx_src_w - w
83 84
            else:
                w1lambda = ratio_w * j - w
85 86 87 88 89 90
            w2lambda = 1.0 - w1lambda

            out[:, :, i, j] = h2lambda*(w2lambda*input[:, :, h, w] +
                                        w1lambda*input[:, :, h, w+wid]) + \
                h1lambda*(w2lambda*input[:, :, h+hid, w] +
                          w1lambda*input[:, :, h+hid, w+wid])
91 92 93 94

    if data_layout == "NHWC":
        out = np.transpose(out, (0, 2, 3, 1))  # NCHW => NHWC

95 96 97
    return out.astype(input.dtype)


98
class TestBilinearInterpOp(OpTest):
99 100
    def setUp(self):
        self.out_size = None
101
        self.actual_shape = None
102
        self.data_layout = 'NCHW'
103
        self.init_test_case()
104
        self.op_type = "bilinear_interp"
105
        input_np = np.random.random(self.input_shape).astype("float64")
106

107 108 109 110 111 112 113
        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]

D
dengkaipeng 已提交
114
        if self.scale > 0:
115 116
            out_h = int(in_h * self.scale)
            out_w = int(in_w * self.scale)
D
dengkaipeng 已提交
117 118 119 120
        else:
            out_h = self.out_h
            out_w = self.out_w

D
dengkaipeng 已提交
121 122
        output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,
                                       self.actual_shape, self.align_corners,
123
                                       self.align_mode, self.data_layout)
124 125 126
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
127 128
        if self.actual_shape is not None:
            self.inputs['OutSize'] = self.actual_shape
D
dengkaipeng 已提交
129

130 131 132
        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
D
dengkaipeng 已提交
133
            'scale': self.scale,
134 135
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
136 137
            'align_mode': self.align_mode,
            'data_layout': self.data_layout
138 139 140 141 142 143 144 145 146 147 148
        }
        self.outputs = {'Out': output_np}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', in_place=True)

    def init_test_case(self):
        self.interp_method = 'bilinear'
Z
zhupengyang 已提交
149
        self.input_shape = [2, 3, 5, 5]
150 151
        self.out_h = 2
        self.out_w = 2
D
dengkaipeng 已提交
152
        self.scale = 0.
153
        self.out_size = np.array([3, 3]).astype("int32")
T
tink2123 已提交
154 155
        self.align_corners = True
        self.align_mode = 1
156 157


158
class TestBilinearInterpCase1(TestBilinearInterpOp):
159 160 161 162 163
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
D
dengkaipeng 已提交
164
        self.scale = 0.
T
tink2123 已提交
165 166
        self.align_corners = True
        self.align_mode = 1
167 168


169
class TestBilinearInterpCase2(TestBilinearInterpOp):
170 171 172 173 174
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 12
        self.out_w = 12
D
dengkaipeng 已提交
175
        self.scale = 0.
T
tink2123 已提交
176 177
        self.align_corners = True
        self.align_mode = 1
178 179


180
class TestBilinearInterpCase3(TestBilinearInterpOp):
181 182
    def init_test_case(self):
        self.interp_method = 'bilinear'
183
        self.input_shape = [1, 1, 32, 64]
184
        self.out_h = 64
185
        self.out_w = 32
D
dengkaipeng 已提交
186
        self.scale = 0.
T
tink2123 已提交
187 188
        self.align_corners = True
        self.align_mode = 1
189 190


191
class TestBilinearInterpCase4(TestBilinearInterpOp):
192 193 194 195 196
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
D
dengkaipeng 已提交
197
        self.scale = 0.
198
        self.out_size = np.array([2, 2]).astype("int32")
T
tink2123 已提交
199 200
        self.align_corners = True
        self.align_mode = 1
201 202


203
class TestBilinearInterpCase5(TestBilinearInterpOp):
204 205 206 207 208
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 12
        self.out_w = 12
D
dengkaipeng 已提交
209
        self.scale = 0.
210
        self.out_size = np.array([11, 11]).astype("int32")
T
tink2123 已提交
211 212
        self.align_corners = True
        self.align_mode = 1
213 214


215
class TestBilinearInterpCase6(TestBilinearInterpOp):
216 217
    def init_test_case(self):
        self.interp_method = 'bilinear'
218
        self.input_shape = [1, 1, 32, 64]
219
        self.out_h = 64
220
        self.out_w = 32
D
dengkaipeng 已提交
221
        self.scale = 0.
222
        self.out_size = np.array([65, 33]).astype("int32")
T
tink2123 已提交
223 224
        self.align_corners = True
        self.align_mode = 1
225 226


K
Kaipeng Deng 已提交
227 228 229
class TestBilinearInterpSame(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
230 231
        self.input_shape = [2, 3, 32, 64]
        self.out_h = 32
K
Kaipeng Deng 已提交
232 233 234 235 236 237
        self.out_w = 64
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


238
class TestBilinearInterpActualShape(TestBilinearInterpOp):
239 240 241 242 243
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 2, 32, 16]
        self.out_h = 64
        self.out_w = 32
D
dengkaipeng 已提交
244
        self.scale = 0.
245
        self.out_size = np.array([66, 40]).astype("int32")
T
tink2123 已提交
246 247
        self.align_corners = True
        self.align_mode = 1
248 249


250 251 252
class TestBilinearInterpDataLayout(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
Z
zhupengyang 已提交
253
        self.input_shape = [2, 5, 5, 3]
254 255 256 257 258 259 260 261 262
        self.out_h = 2
        self.out_w = 2
        self.scale = 0.
        self.out_size = np.array([3, 3]).astype("int32")
        self.align_corners = True
        self.align_mode = 1
        self.data_layout = "NHWC"


263
class TestBilinearInterpOpUint8(OpTest):
264 265
    def setUp(self):
        self.out_size = None
266
        self.actual_shape = None
267
        self.init_test_case()
268
        self.op_type = "bilinear_interp"
269 270
        input_np = np.random.randint(
            low=0, high=256, size=self.input_shape).astype("uint8")
D
dengkaipeng 已提交
271 272 273 274 275 276 277 278

        if self.scale > 0:
            out_h = int(self.input_shape[2] * self.scale)
            out_w = int(self.input_shape[3] * self.scale)
        else:
            out_h = self.out_h
            out_w = self.out_w

D
dengkaipeng 已提交
279 280 281
        output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,
                                       self.actual_shape, self.align_corners,
                                       self.align_mode)
282 283 284
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
D
dengkaipeng 已提交
285

286 287 288
        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
D
dengkaipeng 已提交
289
            'scale': self.scale,
290 291 292
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
            'align_mode': self.align_mode
293 294 295 296 297 298 299 300 301 302 303
        }
        self.outputs = {'Out': output_np}

    def test_check_output(self):
        self.check_output_with_place(place=core.CPUPlace(), atol=1)

    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [1, 3, 9, 6]
        self.out_h = 10
        self.out_w = 9
D
dengkaipeng 已提交
304
        self.scale = 0.
T
tink2123 已提交
305 306
        self.align_corners = True
        self.align_mode = 1
307 308


309
class TestBilinearInterpCase1Uint8(TestBilinearInterpOpUint8):
310 311
    def init_test_case(self):
        self.interp_method = 'bilinear'
312 313 314
        self.input_shape = [2, 3, 32, 64]
        self.out_h = 64
        self.out_w = 32
D
dengkaipeng 已提交
315
        self.scale = 0.
T
tink2123 已提交
316 317
        self.align_corners = True
        self.align_mode = 1
318 319


320
class TestBilinearInterpCase2Uint8(TestBilinearInterpOpUint8):
321 322 323 324 325
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 5
        self.out_w = 13
D
dengkaipeng 已提交
326
        self.scale = 0.
327
        self.out_size = np.array([6, 15]).astype("int32")
T
tink2123 已提交
328 329
        self.align_corners = True
        self.align_mode = 1
330 331 332 333 334


class TestBilinearInterpOtherMethod1(TestBilinearInterpOp):
    def set_align_mode(self):
        self.align_corners = False
T
tink2123 已提交
335
        self.align_mode = 1
336 337 338 339


class TestBilinearInterpWithMethod2(TestBilinearInterpOp):
    def set_align_mode(self):
T
tink2123 已提交
340 341
        self.align_corners = False
        self.align_mode = 0
342 343 344 345 346 347


class TestBilinearInterpWithMethod3(TestBilinearInterpOp):
    def set_align_mode(self):
        self.align_corners = True
        self.align_mode = 0
348 349


D
dengkaipeng 已提交
350 351 352
class TestBilinearInterpScale1(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
353
        self.input_shape = [2, 3, 5, 7]
D
dengkaipeng 已提交
354 355 356 357 358 359 360 361 362 363
        self.out_h = 60
        self.out_w = 25
        self.scale = 2.
        self.align_corners = True
        self.align_mode = 1


class TestBilinearInterpScale2(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
364
        self.input_shape = [2, 3, 5, 7]
D
dengkaipeng 已提交
365 366 367 368 369 370 371 372 373 374
        self.out_h = 60
        self.out_w = 25
        self.scale = 1.
        self.align_corners = True
        self.align_mode = 1


class TestBilinearInterpScale3(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
375
        self.input_shape = [2, 3, 5, 7]
D
dengkaipeng 已提交
376 377 378 379 380 381 382
        self.out_h = 60
        self.out_w = 25
        self.scale = 1.5
        self.align_corners = True
        self.align_mode = 1


383 384 385 386 387 388 389 390 391 392 393
class TestBilinearInterpZero(TestBilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [2, 3, 5, 7]
        self.out_h = 60
        self.out_w = 25
        self.scale = 0.2
        self.align_corners = False
        self.align_mode = 0


394 395 396 397 398 399 400 401 402 403 404 405 406
class TestBilinearInterpOp_attr_tensor(OpTest):
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
        self.init_test_case()
        self.op_type = "bilinear_interp"
        self.shape_by_1Dtensor = False
        self.scale_by_1Dtensor = False
        self.attrs = {
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
        }

407
        input_np = np.random.random(self.input_shape).astype("float64")
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 436 437 438 439 440 441 442
        self.inputs = {'X': input_np}

        if self.scale_by_1Dtensor:
            self.inputs['Scale'] = np.array([self.scale]).astype("float32")
        elif self.scale > 0:
            out_h = int(self.input_shape[2] * self.scale)
            out_w = int(self.input_shape[3] * self.scale)
            self.attrs['scale'] = self.scale
        else:
            out_h = self.out_h
            out_w = self.out_w

        if self.shape_by_1Dtensor:
            self.inputs['OutSize'] = self.out_size
        elif self.out_size is not None:
            size_tensor = []
            for index, ele in enumerate(self.out_size):
                size_tensor.append(("x" + str(index), np.ones(
                    (1)).astype('int32') * ele))
            self.inputs['SizeTensor'] = size_tensor

        self.attrs['out_h'] = self.out_h
        self.attrs['out_w'] = self.out_w
        output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,
                                       self.actual_shape, self.align_corners)
        self.outputs = {'Out': output_np}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', in_place=True)

    def init_test_case(self):
        self.interp_method = 'bilinear'
Z
zhupengyang 已提交
443
        self.input_shape = [2, 3, 5, 5]
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        self.out_h = 3
        self.out_w = 3
        self.scale = 0.
        self.out_size = [3, 3]
        self.align_corners = True


# out_size is a 1-D tensor
class TestBilinearInterp_attr_tensor_Case1(TestBilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 12
        self.out_w = 12
        self.scale = 0.
        self.out_size = [8, 12]
        self.align_corners = True


# scale is a 1-D tensor
class TestBilinearInterp_attr_tensor_Case2(TestBilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 2, 32, 16]
        self.out_h = 64
        self.out_w = 32
        self.scale = 0.
        self.out_size = np.array([66, 40]).astype("int32")
        self.align_corners = True
        self.shape_by_1Dtensor = True


# scale is a 1-D tensor
class TestBilinearInterp_attr_tensor_Case3(TestBilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'bilinear'
        self.input_shape = [3, 2, 32, 16]
        self.out_h = 64
        self.out_w = 32
        self.scale = 2.0
        self.out_size = None
        self.align_corners = True
        self.scale_by_1Dtensor = True


489
class TestBilinearInterpOpAPI(unittest.TestCase):
490
    def test_case(self):
491 492 493 494 495 496 497
        x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")

        dim = fluid.data(name="dim", shape=[1], dtype="int32")
        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")
498 499 500 501 502 503 504 505

        out1 = fluid.layers.resize_bilinear(x, out_shape=[12, 12])
        out2 = fluid.layers.resize_bilinear(x, out_shape=[12, dim])
        out3 = fluid.layers.resize_bilinear(x, out_shape=shape_tensor)
        out4 = fluid.layers.resize_bilinear(
            x, out_shape=[4, 4], actual_shape=actual_size)
        out5 = fluid.layers.resize_bilinear(x, scale=scale_tensor)

506
        x_data = np.random.random((2, 3, 6, 6)).astype("float32")
507 508 509 510 511
        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")

512 513 514 515
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
516
        exe = fluid.Executor(place)
517
        exe.run(fluid.default_startup_program())
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
        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 = bilinear_interp_np(
            x_data, out_h=12, out_w=12, align_corners=True)
        for res in results:
            self.assertTrue(np.allclose(res, expect_res))


535 536
if __name__ == "__main__":
    unittest.main()