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


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

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

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

    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]
68

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

72 73 74
    return out.astype(X.dtype)


75
class TestNearestInterpOp(OpTest):
76

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

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

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

    def test_check_output(self):
122
        self.check_output(check_eager=self.check_eager)
123 124

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

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


140
class TestNearestNeighborInterpCase1(TestNearestInterpOp):
141

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


151
class TestNearestNeighborInterpCase2(TestNearestInterpOp):
152

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


162
class TestNearestNeighborInterpCase3(TestNearestInterpOp):
163

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


173
class TestNearestNeighborInterpCase4(TestNearestInterpOp):
174

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


185
class TestNearestNeighborInterpCase5(TestNearestInterpOp):
186

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


197
class TestNearestNeighborInterpCase6(TestNearestInterpOp):
198

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


K
Kaipeng Deng 已提交
209
class TestNearestNeighborInterpSame(TestNearestInterpOp):
210

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


220
class TestNearestNeighborInterpActualShape(TestNearestInterpOp):
221

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


232
class TestNearestNeighborInterpDataLayout(TestNearestInterpOp):
233

234 235 236 237 238 239 240 241 242 243 244
    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"


245
class TestNearestInterpOpUint8(OpTest):
246

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

        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,
264 265
                                               self.out_size, self.actual_shape,
                                               self.align_corners)
266 267 268
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
269
            self.check_eager = False
270 271 272
        self.attrs = {
            'out_h': self.out_h,
            'out_w': self.out_w,
D
dengkaipeng 已提交
273
            'scale': self.scale,
274 275
            'interp_method': self.interp_method,
            'align_corners': self.align_corners
276 277 278 279
        }
        self.outputs = {'Out': output_np}

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

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


293
class TestNearestNeighborInterpCase1Uint8(TestNearestInterpOpUint8):
294

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


304
class TestNearestNeighborInterpCase2Uint8(TestNearestInterpOpUint8):
305

306 307 308 309 310
    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 已提交
311
        self.scale = 0.
312
        self.out_size = np.array([6, 15]).astype("int32")
313 314 315 316
        self.align_corners = True


class TestNearestInterpWithoutCorners(TestNearestInterpOp):
317

318 319
    def set_align_corners(self):
        self.align_corners = False
320 321


D
dengkaipeng 已提交
322
class TestNearestNeighborInterpScale1(TestNearestInterpOp):
323

D
dengkaipeng 已提交
324 325
    def init_test_case(self):
        self.interp_method = 'nearest'
326
        self.input_shape = [3, 2, 7, 5]
D
dengkaipeng 已提交
327 328 329 330 331 332 333 334
        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):
335

D
dengkaipeng 已提交
336 337
    def init_test_case(self):
        self.interp_method = 'nearest'
338
        self.input_shape = [3, 2, 5, 7]
D
dengkaipeng 已提交
339 340 341 342 343 344 345 346
        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):
347

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


358
class TestNearestInterpOp_attr_tensor(OpTest):
359

360 361 362 363 364 365 366 367 368 369 370
    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,
        }
371 372 373
        # NOTE(dev): some AsDispensible input is not used under imperative mode.
        # Skip check_eager while found them in Inputs.
        self.check_eager = True
374

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

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

        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):
407
        self.check_output(check_eager=self.check_eager)
408 409

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

    def init_test_case(self):
        self.interp_method = 'nearest'
Z
zhupengyang 已提交
417
        self.input_shape = [2, 5, 4, 4]
418 419 420 421 422 423 424 425 426
        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):
427

428 429 430 431 432 433 434 435 436 437 438 439
    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):
440

441 442 443 444 445 446 447 448 449 450 451 452 453
    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):
454

455 456 457 458 459 460 461 462 463 464 465
    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


466
class TestNearestAPI(unittest.TestCase):
467

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

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

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

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

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

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

523

524
class TestNearestInterpException(unittest.TestCase):
525

526
    def test_exception(self):
527 528 529 530
        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
531 532 533
            out = fluid.layers.resize_nearest(input,
                                              out_shape=[4, 8],
                                              data_format='NDHWC')
534 535 536 537 538 539 540 541 542 543

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


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