test_trilinear_interp_op.py 20.6 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#   Copyright (c) 2019 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
from op_test import OpTest
import paddle.fluid.core as core
21
import paddle.fluid as fluid
K
Kaipeng Deng 已提交
22 23 24 25 26 27 28 29 30


def trilinear_interp_np(input,
                        out_d,
                        out_h,
                        out_w,
                        out_size=None,
                        actual_shape=None,
                        align_corners=True,
31 32
                        align_mode=0,
                        data_layout='NCDHW'):
K
Kaipeng Deng 已提交
33
    """trilinear interpolation implement in shape [N, C, D, H, W]"""
34 35
    if data_layout == "NDHWC":
        input = np.transpose(input, (0, 4, 1, 2, 3))  # NDHWC => NCDHW
K
Kaipeng Deng 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    if out_size is not None:
        out_d = out_size[0]
        out_h = out_size[1]
        out_w = out_size[2]
    if actual_shape is not None:
        out_d = actual_shape[0]
        out_h = actual_shape[1]
        out_w = actual_shape[2]
    batch_size, channel, in_d, in_h, in_w = input.shape

    ratio_d = ratio_h = ratio_w = 0.0
    if out_d > 1:
        if (align_corners):
            ratio_d = (in_d - 1.0) / (out_d - 1.0)
        else:
            ratio_d = 1.0 * in_d / out_d
    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

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

    for i in range(out_d):
        if (align_mode == 0 and not align_corners):
            d = int(ratio_d * (i + 0.5) - 0.5)
        else:
            d = int(ratio_d * i)

        d = max(0, d)
        did = 1 if d < in_d - 1 else 0
        if (align_mode == 0 and not align_corners):
            idx_src_d = max(ratio_d * (i + 0.5) - 0.5, 0)
            d1lambda = idx_src_d - d
        else:
            d1lambda = ratio_d * i - d
        d2lambda = 1.0 - d1lambda

        for j in range(out_h):
            if (align_mode == 0 and not align_corners):
                h = int(ratio_h * (j + 0.5) - 0.5)
            else:
                h = int(ratio_h * j)

            h = max(0, h)
            hid = 1 if h < in_h - 1 else 0
            if (align_mode == 0 and not align_corners):
                idx_src_h = max(ratio_h * (j + 0.5) - 0.5, 0)
                h1lambda = idx_src_h - h
            else:
                h1lambda = ratio_h * j - h
            h2lambda = 1.0 - h1lambda

            for k in range(out_w):
                if (align_mode == 0 and not align_corners):
                    w = int(ratio_w * (k + 0.5) - 0.5)
                else:
                    w = int(ratio_w * k)
                w = max(0, w)
                wid = 1 if w < in_w - 1 else 0
                if (align_mode == 0 and not align_corners):
                    idx_src_w = max(ratio_w * (k + 0.5) - 0.5, 0)
                    w1lambda = idx_src_w - w
                else:
                    w1lambda = ratio_w * k - w
                w2lambda = 1.0 - w1lambda

                out[:, :, i, j, k] = \
                    d2lambda * \
                    (h2lambda * (w2lambda * input[:, :, d, h, w] + \
                              w1lambda * input[:, :, d, h, w+wid]) + \
                    h1lambda * (w2lambda * input[:, :, d, h+hid, w] + \
                              w1lambda * input[:, :, d, h+hid, w+wid])) + \
                    d1lambda * \
                    (h2lambda * (w2lambda * input[:, :, d+did, h, w] + \
                              w1lambda * input[:, :, d+did, h, w+wid]) + \
                    h1lambda * (w2lambda * input[:, :, d+did, h+hid, w] + \
                              w1lambda * input[:, :, d+did, h+hid, w+wid]))
120 121 122
    if data_layout == "NDHWC":
        out = np.transpose(out, (0, 2, 3, 4, 1))  # NCDHW => NDHWC

K
Kaipeng Deng 已提交
123 124 125 126 127 128 129
    return out.astype(input.dtype)


class TestTrilinearInterpOp(OpTest):
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
130
        self.data_layout = 'NCDHW'
K
Kaipeng Deng 已提交
131 132 133 134
        self.init_test_case()
        self.op_type = "trilinear_interp"
        input_np = np.random.random(self.input_shape).astype("float32")

135 136 137 138 139 140 141 142 143
        if self.data_layout == "NCDHW":
            in_d = self.input_shape[2]
            in_h = self.input_shape[3]
            in_w = self.input_shape[4]
        else:
            in_d = self.input_shape[1]
            in_h = self.input_shape[2]
            in_w = self.input_shape[3]

K
Kaipeng Deng 已提交
144
        if self.scale > 0:
145 146 147
            out_d = int(in_d * self.scale)
            out_h = int(in_h * self.scale)
            out_w = int(in_w * self.scale)
K
Kaipeng Deng 已提交
148 149 150 151 152
        else:
            out_d = self.out_d
            out_h = self.out_h
            out_w = self.out_w

153 154 155
        output_np = trilinear_interp_np(
            input_np, out_d, out_h, out_w, self.out_size, self.actual_shape,
            self.align_corners, self.align_mode, self.data_layout)
K
Kaipeng Deng 已提交
156 157 158 159 160
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size
        if self.actual_shape is not None:
            self.inputs['OutSize'] = self.actual_shape
161 162 163 164 165
        # c++ end treat NCDHW the same way as NCHW
        if self.data_layout == 'NCDHW':
            data_layout = 'NCHW'
        else:
            data_layout = 'NHWC'
K
Kaipeng Deng 已提交
166 167 168 169 170 171 172
        self.attrs = {
            'out_d': self.out_d,
            'out_h': self.out_h,
            'out_w': self.out_w,
            'scale': self.scale,
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
173 174
            'align_mode': self.align_mode,
            'data_layout': data_layout
K
Kaipeng Deng 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        }
        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 = 'trilinear'
        self.input_shape = [2, 3, 4, 4, 4]
        self.out_d = 2
        self.out_h = 2
        self.out_w = 2
        self.scale = 0.
        self.out_size = np.array([3, 3, 3]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase1(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 1, 7, 8, 9]
        self.out_d = 1
        self.out_h = 1
        self.out_w = 1
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase2(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 9, 6, 8]
        self.out_d = 12
        self.out_h = 12
        self.out_w = 12
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase3(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [3, 2, 16, 8, 4]
        self.out_d = 32
        self.out_h = 16
        self.out_w = 8
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase4(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [4, 1, 7, 8, 9]
        self.out_d = 1
        self.out_h = 1
        self.out_w = 1
        self.scale = 0.
        self.out_size = np.array([2, 2, 2]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase5(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [3, 3, 9, 6, 8]
        self.out_d = 12
        self.out_h = 12
        self.out_w = 12
        self.scale = 0.
        self.out_size = np.array([11, 11, 11]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase6(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [1, 1, 16, 8, 4]
        self.out_d = 8
        self.out_h = 32
        self.out_w = 16
        self.scale = 0.
        self.out_size = np.array([17, 9, 5]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpSame(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [1, 1, 16, 8, 4]
        self.out_d = 16
        self.out_h = 8
        self.out_w = 4
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpSameHW(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [1, 1, 16, 8, 4]
        self.out_d = 8
        self.out_h = 8
        self.out_w = 4
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpActualShape(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [3, 2, 16, 8, 4]
        self.out_d = 64
        self.out_h = 32
        self.out_w = 16
        self.scale = 0.
        self.out_size = np.array([33, 19, 7]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


308 309 310 311 312 313 314 315 316 317 318 319 320 321
class TestTrilinearInterpDatalayout(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 4, 4, 4, 3]
        self.out_d = 2
        self.out_h = 2
        self.out_w = 2
        self.scale = 0.
        self.out_size = np.array([3, 3, 3]).astype("int32")
        self.align_corners = True
        self.align_mode = 1
        self.data_layout = "NDHWC"


K
Kaipeng Deng 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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 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
class TestTrilinearInterpOpUint8(OpTest):
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
        self.init_test_case()
        self.op_type = "trilinear_interp"
        input_np = np.random.randint(
            low=0, high=256, size=self.input_shape).astype("uint8")

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

        output_np = trilinear_interp_np(input_np, out_d, out_h, out_w,
                                        self.out_size, self.actual_shape,
                                        self.align_corners, self.align_mode)
        self.inputs = {'X': input_np}
        if self.out_size is not None:
            self.inputs['OutSize'] = self.out_size

        self.attrs = {
            'out_d': self.out_d,
            'out_h': self.out_h,
            'out_w': self.out_w,
            'scale': self.scale,
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
            'align_mode': self.align_mode
        }
        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 = 'trilinear'
        self.input_shape = [1, 3, 9, 6, 8]
        self.out_d = 13
        self.out_h = 10
        self.out_w = 9
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase1Uint8(TestTrilinearInterpOpUint8):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 16, 8, 4]
        self.out_d = 13
        self.out_h = 7
        self.out_w = 2
        self.scale = 0.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpCase2Uint8(TestTrilinearInterpOpUint8):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [4, 1, 7, 8, 9]
        self.out_d = 3
        self.out_h = 5
        self.out_w = 13
        self.scale = 0.
        self.out_size = np.array([6, 15, 21]).astype("int32")
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpOtherMethod1(TestTrilinearInterpOp):
    def set_align_mode(self):
        self.align_corners = False
        self.align_mode = 1


class TestTrilinearInterpWithMethod2(TestTrilinearInterpOp):
    def set_align_mode(self):
        self.align_corners = False
        self.align_mode = 0


class TestTrilinearInterpWithMethod3(TestTrilinearInterpOp):
    def set_align_mode(self):
        self.align_corners = True
        self.align_mode = 0


class TestTrilinearInterpScale1(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 5, 7, 9]
        self.out_d = 82
        self.out_h = 60
        self.out_w = 25
        self.scale = 2.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpScale2(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 5, 7, 9]
        self.out_d = 82
        self.out_h = 60
        self.out_w = 25
        self.scale = 1.
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpScale3(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 5, 7, 9]
        self.out_d = 82
        self.out_h = 60
        self.out_w = 25
        self.scale = 1.5
        self.align_corners = True
        self.align_mode = 1


class TestTrilinearInterpZero(TestTrilinearInterpOp):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 5, 7, 11]
        self.out_d = 82
        self.out_h = 60
        self.out_w = 25
        self.scale = 0.2
        self.align_corners = False
        self.align_mode = 0


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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
class TestTrilinearInterpOp_attr_tensor(OpTest):
    def setUp(self):
        self.out_size = None
        self.actual_shape = None
        self.init_test_case()
        self.op_type = "trilinear_interp"
        self.shape_by_1Dtensor = False
        self.scale_by_1Dtensor = False
        self.attrs = {
            'interp_method': self.interp_method,
            'align_corners': self.align_corners,
            'align_mode': self.align_mode
        }

        input_np = np.random.random(self.input_shape).astype("float32")
        self.inputs = {'X': input_np}

        if self.scale_by_1Dtensor:
            self.inputs['Scale'] = np.array([self.scale]).astype("float32")
        elif self.scale > 0:
            out_d = int(self.input_shape[2] * self.scale)
            out_h = int(self.input_shape[3] * self.scale)
            out_w = int(self.input_shape[4] * self.scale)
            self.attrs['scale'] = self.scale
        else:
            out_d = self.out_d
            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_d'] = self.out_d
        self.attrs['out_h'] = self.out_h
        self.attrs['out_w'] = self.out_w
        output_np = trilinear_interp_np(input_np, out_d, out_h, out_w,
                                        self.out_size, self.actual_shape,
                                        self.align_corners, self.align_mode)
        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 = 'trilinear'
        self.input_shape = [2, 3, 4, 4, 4]
        self.out_d = 2
        self.out_h = 3
        self.out_w = 3
        self.scale = 0.
        self.out_size = [2, 3, 3]
        self.align_corners = True
        self.align_mode = 1


# out_size is a 1-D tensor
class TestTrilinearInterp_attr_tensor_Case1(TestTrilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [3, 2, 9, 6, 8]
        self.out_d = 32
        self.out_h = 16
        self.out_w = 8
        self.scale = 0.3
        self.out_size = [12, 4, 4]
        self.align_corners = True
        self.align_mode = 1


# scale is a 1-D tensor
class TestTrilinearInterp_attr_tensor_Case2(TestTrilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 8, 8, 4]
        self.out_d = 16
        self.out_h = 12
        self.out_w = 4
        self.scale = 0.
        self.out_size = [16, 4, 10]
        self.align_corners = True
        self.align_mode = 1
        self.shape_by_1Dtensor = True


# scale is a 1-D tensor
class TestTrilinearInterp_attr_tensor_Case3(TestTrilinearInterpOp_attr_tensor):
    def init_test_case(self):
        self.interp_method = 'trilinear'
        self.input_shape = [2, 3, 8, 8, 4]
        self.out_d = 16
        self.out_h = 16
        self.out_w = 8
        self.scale = 2.0
        self.out_size = None
        self.align_corners = True
        self.align_mode = 1
        self.scale_by_1Dtensor = True


class TestTrilinearInterpAPI(OpTest):
    def test_case(self):
573 574 575 576 577 578 579 580
        x = fluid.data(name="x", shape=[2, 3, 6, 9, 4], dtype="float32")
        y = fluid.data(name="y", shape=[2, 6, 9, 4, 3], dtype="float32")

        dim = fluid.data(name="dim", shape=[1], dtype="int32")
        shape_tensor = fluid.data(name="shape_tensor", shape=[3], dtype="int32")
        actual_size = fluid.data(name="actual_size", shape=[3], dtype="int32")
        scale_tensor = fluid.data(
            name="scale_tensor", shape=[1], dtype="float32")
581

582 583
        out1 = fluid.layers.resize_trilinear(
            y, out_shape=[12, 18, 8], data_format='NDHWC')
584 585 586 587 588 589
        out2 = fluid.layers.resize_trilinear(x, out_shape=[12, dim, 8])
        out3 = fluid.layers.resize_trilinear(x, out_shape=shape_tensor)
        out4 = fluid.layers.resize_trilinear(
            x, out_shape=[4, 4, 8], actual_shape=actual_size)
        out5 = fluid.layers.resize_trilinear(x, scale=scale_tensor)

590
        x_data = np.random.random((2, 3, 6, 9, 4)).astype("float32")
591 592 593 594 595
        dim_data = np.array([18]).astype("int32")
        shape_data = np.array([12, 18, 8]).astype("int32")
        actual_size_data = np.array([12, 18, 8]).astype("int32")
        scale_data = np.array([2.0]).astype("float32")

596 597 598 599
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()
600
        exe = fluid.Executor(place)
601
        exe.run(fluid.default_startup_program())
602 603 604
        results = exe.run(fluid.default_main_program(),
                          feed={
                              "x": x_data,
605
                              "y": np.transpose(x_data, (0, 2, 3, 4, 1)),
606 607 608 609 610 611 612 613 614 615
                              "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 = trilinear_interp_np(
            x_data, out_d=12, out_h=18, out_w=8, align_mode=1)
616 617 618 619 620
        self.assertTrue(
            np.allclose(results[0], np.transpose(expect_res, (0, 2, 3, 4, 1))))
        for i in range(len(results) - 1):
            self.assertTrue(np.allclose(results[i + 1], expect_res))

621 622

class TestTrilinearInterpOpException(OpTest):
623
    def test_exception(self):
624
        input = fluid.data(name="input", shape=[2, 3, 6, 9, 4], dtype="float32")
625 626

        def attr_data_format():
627 628 629
            # for 5-D input, data_format only can be NCDHW or NDHWC
            out = fluid.layers.resize_trilinear(
                input, out_shape=[4, 8, 4], data_format='NHWC')
630 631

        self.assertRaises(ValueError, attr_data_format)
632 633


K
Kaipeng Deng 已提交
634 635
if __name__ == "__main__":
    unittest.main()