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

import unittest
import numpy as np
17
from op_test import OpTest
18
import paddle.fluid.core as core
19
import paddle.fluid as fluid
20 21


22 23 24 25
def nearest_neighbor_interp_np(X,
                               out_h,
                               out_w,
                               out_size=None,
26
                               actual_shape=None,
27 28
                               align_corners=True,
                               data_layout='NCHW'):
29
    """nearest neighbor interpolation implement in shape [N, C, H, W]"""
30 31
    if data_layout == "NHWC":
        X = np.transpose(X, (0, 3, 1, 2))  # NHWC => NCHW
32 33 34
    if out_size is not None:
        out_h = out_size[0]
        out_w = out_size[1]
35 36 37
    if actual_shape is not None:
        out_h = actual_shape[0]
        out_w = actual_shape[1]
38 39 40
    n, c, in_h, in_w = X.shape

    ratio_h = ratio_w = 0.0
T
tink2123 已提交
41 42 43 44 45 46 47 48 49 50
    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
51 52

    out = np.zeros((n, c, out_h, out_w))
53 54 55 56 57 58 59 60 61 62 63 64 65

    if align_corners:
        for i in range(out_h):
            in_i = int(ratio_h * i + 0.5)
            for j in range(out_w):
                in_j = int(ratio_w * j + 0.5)
                out[:, :, i, j] = X[:, :, in_i, in_j]
    else:
        for i in range(out_h):
            in_i = int(ratio_h * i)
            for j in range(out_w):
                in_j = int(ratio_w * j)
                out[:, :, i, j] = X[:, :, in_i, in_j]
66

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

70 71 72
    return out.astype(X.dtype)


73
class TestNearestInterpOp(OpTest):
74

75 76
    def setUp(self):
        self.out_size = None
77
        self.actual_shape = None
78
        self.data_layout = 'NCHW'
79
        self.init_test_case()
80
        self.op_type = "nearest_interp"
81
        self.check_eager = True
82
        input_np = np.random.random(self.input_shape).astype("float64")
83

84 85 86 87 88 89 90
        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 已提交
91
        if self.scale > 0:
92 93
            out_h = int(in_h * self.scale)
            out_w = int(in_w * self.scale)
D
dengkaipeng 已提交
94 95 96 97
        else:
            out_h = self.out_h
            out_w = self.out_w

98 99 100 101
        output_np = nearest_neighbor_interp_np(input_np, out_h, out_w,
                                               self.out_size, self.actual_shape,
                                               self.align_corners,
                                               self.data_layout)
102 103 104
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
105
            self.check_eager = False
106 107
        if self.actual_shape is not None:
            self.inputs['OutSize'] = self.actual_shape
108
            self.check_eager = False
109 110 111
        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
D
dengkaipeng 已提交
112
            'scale': self.scale,
113 114
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
115
            'data_layout': self.data_layout
116 117 118 119
        }
        self.outputs = {'Out': output_np}

    def test_check_output(self):
120
        self.check_output(check_eager=self.check_eager)
121 122

    def test_check_grad(self):
123 124 125 126
        self.check_grad(['X'],
                        'Out',
                        in_place=True,
                        check_eager=self.check_eager)
127 128

    def init_test_case(self):
129
        self.interp_method = 'nearest'
130
        self.input_shape = [2, 3, 4, 5]
131 132
        self.out_h = 2
        self.out_w = 2
D
dengkaipeng 已提交
133
        self.scale = 0.
134
        self.out_size = np.array([3, 3]).astype("int32")
135
        self.align_corners = True
136 137


138
class TestNearestNeighborInterpCase1(TestNearestInterpOp):
139

140
    def init_test_case(self):
141
        self.interp_method = 'nearest'
142 143 144
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
D
dengkaipeng 已提交
145
        self.scale = 0.
T
tink2123 已提交
146
        self.align_corners = True
147 148


149
class TestNearestNeighborInterpCase2(TestNearestInterpOp):
150

151
    def init_test_case(self):
152
        self.interp_method = 'nearest'
153 154 155
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 12
        self.out_w = 12
D
dengkaipeng 已提交
156
        self.scale = 0.
157
        self.align_corners = True
158 159


160
class TestNearestNeighborInterpCase3(TestNearestInterpOp):
161

162
    def init_test_case(self):
163
        self.interp_method = 'nearest'
164
        self.input_shape = [1, 1, 32, 64]
165
        self.out_h = 64
166
        self.out_w = 32
D
dengkaipeng 已提交
167
        self.scale = 0.
168
        self.align_corners = True
169 170


171
class TestNearestNeighborInterpCase4(TestNearestInterpOp):
172

173
    def init_test_case(self):
174
        self.interp_method = 'nearest'
175 176 177
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 1
        self.out_w = 1
D
dengkaipeng 已提交
178
        self.scale = 0.
179
        self.out_size = np.array([2, 2]).astype("int32")
180
        self.align_corners = True
181 182


183
class TestNearestNeighborInterpCase5(TestNearestInterpOp):
184

185
    def init_test_case(self):
186
        self.interp_method = 'nearest'
187 188 189
        self.input_shape = [3, 3, 9, 6]
        self.out_h = 12
        self.out_w = 12
D
dengkaipeng 已提交
190
        self.scale = 0.
191
        self.out_size = np.array([11, 11]).astype("int32")
192
        self.align_corners = True
193 194


195
class TestNearestNeighborInterpCase6(TestNearestInterpOp):
196

197
    def init_test_case(self):
198
        self.interp_method = 'nearest'
199
        self.input_shape = [1, 1, 32, 64]
200
        self.out_h = 64
201
        self.out_w = 32
D
dengkaipeng 已提交
202
        self.scale = 0.
203
        self.out_size = np.array([65, 129]).astype("int32")
204
        self.align_corners = True
205 206


K
Kaipeng Deng 已提交
207
class TestNearestNeighborInterpSame(TestNearestInterpOp):
208

K
Kaipeng Deng 已提交
209 210
    def init_test_case(self):
        self.interp_method = 'nearest'
211 212
        self.input_shape = [2, 3, 32, 64]
        self.out_h = 32
K
Kaipeng Deng 已提交
213 214 215 216 217
        self.out_w = 64
        self.scale = 0.
        self.align_corners = True


218
class TestNearestNeighborInterpActualShape(TestNearestInterpOp):
219

220
    def init_test_case(self):
221
        self.interp_method = 'nearest'
222 223 224
        self.input_shape = [3, 2, 32, 16]
        self.out_h = 64
        self.out_w = 32
D
dengkaipeng 已提交
225
        self.scale = 0.
226
        self.out_size = np.array([66, 40]).astype("int32")
227
        self.align_corners = True
228 229


230
class TestNearestNeighborInterpDataLayout(TestNearestInterpOp):
231

232 233 234 235 236 237 238 239 240 241 242
    def init_test_case(self):
        self.interp_method = 'nearest'
        self.input_shape = [2, 4, 4, 5]
        self.out_h = 2
        self.out_w = 2
        self.scale = 0.
        self.out_size = np.array([3, 8]).astype("int32")
        self.align_corners = True
        self.data_layout = "NHWC"


243
class TestNearestInterpOpUint8(OpTest):
244

245 246
    def setUp(self):
        self.out_size = None
247
        self.actual_shape = None
248
        self.init_test_case()
249
        self.op_type = "nearest_interp"
250
        self.check_eager = True
251 252
        input_np = np.random.randint(low=0, high=256,
                                     size=self.input_shape).astype("uint8")
D
dengkaipeng 已提交
253 254 255 256 257 258 259 260 261

        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

        output_np = nearest_neighbor_interp_np(input_np, out_h, out_w,
262 263
                                               self.out_size, self.actual_shape,
                                               self.align_corners)
264 265 266
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
267
            self.check_eager = False
268 269 270
        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
D
dengkaipeng 已提交
271
            'scale': self.scale,
272 273
            'interp_method': self.interp_method,
            'align_corners': self.align_corners
274 275 276 277
        }
        self.outputs = {'Out': output_np}

    def test_check_output(self):
278 279 280
        self.check_output_with_place(place=core.CPUPlace(),
                                     atol=1,
                                     check_eager=self.check_eager)
281 282

    def init_test_case(self):
283
        self.interp_method = 'nearest'
284 285 286
        self.input_shape = [1, 3, 9, 6]
        self.out_h = 10
        self.out_w = 9
D
dengkaipeng 已提交
287
        self.scale = 0.
288
        self.align_corners = True
289 290


291
class TestNearestNeighborInterpCase1Uint8(TestNearestInterpOpUint8):
292

293 294
    def init_test_case(self):
        self.interp_method = 'nearest'
295 296 297
        self.input_shape = [2, 3, 32, 64]
        self.out_h = 80
        self.out_w = 40
D
dengkaipeng 已提交
298
        self.scale = 0.
T
tink2123 已提交
299
        self.align_corners = True
300 301


302
class TestNearestNeighborInterpCase2Uint8(TestNearestInterpOpUint8):
303

304 305 306 307 308
    def init_test_case(self):
        self.interp_method = 'nearest'
        self.input_shape = [4, 1, 7, 8]
        self.out_h = 5
        self.out_w = 13
D
dengkaipeng 已提交
309
        self.scale = 0.
310
        self.out_size = np.array([6, 15]).astype("int32")
311 312 313 314
        self.align_corners = True


class TestNearestInterpWithoutCorners(TestNearestInterpOp):
315

316 317
    def set_align_corners(self):
        self.align_corners = False
318 319


D
dengkaipeng 已提交
320
class TestNearestNeighborInterpScale1(TestNearestInterpOp):
321

D
dengkaipeng 已提交
322 323
    def init_test_case(self):
        self.interp_method = 'nearest'
324
        self.input_shape = [3, 2, 7, 5]
D
dengkaipeng 已提交
325 326 327 328 329 330 331 332
        self.out_h = 64
        self.out_w = 32
        self.scale = 2.
        self.out_size = np.array([66, 40]).astype("int32")
        self.align_corners = True


class TestNearestNeighborInterpScale2(TestNearestInterpOp):
333

D
dengkaipeng 已提交
334 335
    def init_test_case(self):
        self.interp_method = 'nearest'
336
        self.input_shape = [3, 2, 5, 7]
D
dengkaipeng 已提交
337 338 339 340 341 342 343 344
        self.out_h = 64
        self.out_w = 32
        self.scale = 1.5
        self.out_size = np.array([66, 40]).astype("int32")
        self.align_corners = True


class TestNearestNeighborInterpScale3(TestNearestInterpOp):
345

D
dengkaipeng 已提交
346 347
    def init_test_case(self):
        self.interp_method = 'nearest'
348
        self.input_shape = [3, 2, 7, 5]
D
dengkaipeng 已提交
349 350 351 352 353 354 355
        self.out_h = 64
        self.out_w = 32
        self.scale = 1.
        self.out_size = np.array([66, 40]).astype("int32")
        self.align_corners = True


356
class TestNearestInterpOp_attr_tensor(OpTest):
357

358 359 360 361 362 363 364 365 366 367 368
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
        self.init_test_case()
        self.op_type = "nearest_interp"
        self.shape_by_1Dtensor = False
        self.scale_by_1Dtensor = False
        self.attrs = {
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
        }
369 370 371
        # NOTE(dev): some AsDispensible input is not used under imperative mode.
        # Skip check_eager while found them in Inputs.
        self.check_eager = True
372

373
        input_np = np.random.random(self.input_shape).astype("float64")
374 375 376
        self.inputs = {'X': input_np}

        if self.scale_by_1Dtensor:
377
            self.inputs['Scale'] = np.array([self.scale]).astype("float64")
378 379 380 381 382 383 384 385 386 387
        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
388
            self.check_eager = False
389 390 391 392 393 394
        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
395
            self.check_eager = False
396 397 398 399 400 401 402 403 404

        self.attrs['out_h'] = self.out_h
        self.attrs['out_w'] = self.out_w
        output_np = nearest_neighbor_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):
405
        self.check_output(check_eager=self.check_eager)
406 407

    def test_check_grad(self):
408 409 410 411
        self.check_grad(['X'],
                        'Out',
                        in_place=True,
                        check_eager=self.check_eager)
412 413 414

    def init_test_case(self):
        self.interp_method = 'nearest'
Z
zhupengyang 已提交
415
        self.input_shape = [2, 5, 4, 4]
416 417 418 419 420 421 422 423 424
        self.out_h = 3
        self.out_w = 3
        self.scale = 0.
        self.out_size = [3, 3]
        self.align_corners = True


# out_size is a tensor list
class TestNearestInterp_attr_tensor_Case1(TestNearestInterpOp_attr_tensor):
425

426 427 428 429 430 431 432 433 434 435 436 437
    def init_test_case(self):
        self.interp_method = 'nearest'
        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


# out_size is a 1-D tensor
class TestNearestInterp_attr_tensor_Case2(TestNearestInterpOp_attr_tensor):
438

439 440 441 442 443 444 445 446 447 448 449 450 451
    def init_test_case(self):
        self.interp_method = 'nearest'
        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 TestNearestInterp_attr_tensor_Case3(TestNearestInterpOp_attr_tensor):
452

453 454 455 456 457 458 459 460 461 462 463
    def init_test_case(self):
        self.interp_method = 'nearest'
        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


464
class TestNearestAPI(unittest.TestCase):
465

466
    def test_case(self):
467 468
        x = fluid.data(name="x", shape=[2, 3, 6, 6], dtype="float32")
        y = fluid.data(name="y", shape=[2, 6, 6, 3], dtype="float32")
469 470 471 472

        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")
473 474 475
        scale_tensor = fluid.data(name="scale_tensor",
                                  shape=[1],
                                  dtype="float32")
476

477 478 479
        out1 = fluid.layers.resize_nearest(y,
                                           out_shape=[12, 12],
                                           data_format='NHWC')
480 481
        out2 = fluid.layers.resize_nearest(x, out_shape=[12, dim])
        out3 = fluid.layers.resize_nearest(x, out_shape=shape_tensor)
482 483 484
        out4 = fluid.layers.resize_nearest(x,
                                           out_shape=[4, 4],
                                           actual_shape=actual_size)
485 486
        out5 = fluid.layers.resize_nearest(x, scale=scale_tensor)

487
        x_data = np.random.random((2, 3, 6, 6)).astype("float32")
488 489 490 491 492
        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")

493 494 495 496
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
497
        exe = fluid.Executor(place)
498
        exe.run(fluid.default_startup_program())
499 500 501
        results = exe.run(fluid.default_main_program(),
                          feed={
                              "x": x_data,
502
                              "y": np.transpose(x_data, (0, 2, 3, 1)),
503 504 505 506 507 508 509 510
                              "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)

511 512 513 514
        expect_res = nearest_neighbor_interp_np(x_data,
                                                out_h=12,
                                                out_w=12,
                                                align_corners=True)
515 516 517
        np.testing.assert_allclose(results[0],
                                   np.transpose(expect_res, (0, 2, 3, 1)),
                                   rtol=1e-05)
518
        for i in range(len(results) - 1):
519
            np.testing.assert_allclose(results[i + 1], expect_res, rtol=1e-05)
520

521

522
class TestNearestInterpException(unittest.TestCase):
523

524
    def test_exception(self):
525 526 527 528
        input = fluid.data(name="input", shape=[1, 3, 6, 6], dtype="float32")

        def attr_data_format():
            # for 4-D input, data_format can only be NCHW or NHWC
529 530 531
            out = fluid.layers.resize_nearest(input,
                                              out_shape=[4, 8],
                                              data_format='NDHWC')
532 533 534 535 536 537 538 539 540 541

        def attr_scale_type():
            out = fluid.layers.resize_nearest(input, scale='scale')

        def attr_scale_value():
            out = fluid.layers.resize_nearest(input, scale=-0.3)

        self.assertRaises(ValueError, attr_data_format)
        self.assertRaises(TypeError, attr_scale_type)
        self.assertRaises(ValueError, attr_scale_value)
542 543


544
if __name__ == "__main__":
545 546
    import paddle
    paddle.enable_static()
547
    unittest.main()