test_pad3d_op.py 34.0 KB
Newer Older
L
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#   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
import numpy as np
from op_test import OpTest
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddle.fluid.core as core

from paddle.fluid import Program, program_guard, Executor, default_main_program


class TestPad3dOp(OpTest):
27

L
littletomatodonkey 已提交
28 29 30 31 32
    def setUp(self):
        paddle.enable_static()
        self.value = 0.0
        self.initTestCase()
        self.op_type = "pad3d"
33
        self.python_api = paddle.nn.functional.pad
L
littletomatodonkey 已提交
34 35 36 37
        self.inputs = {'X': np.random.random(self.shape).astype("float64")}
        self.attrs = {}
        if self.variable_paddings:
            self.attrs['paddings'] = []
38 39
            self.inputs['Paddings'] = np.array(
                self.paddings).flatten().astype("int32")
L
littletomatodonkey 已提交
40
        else:
41 42
            self.attrs['paddings'] = np.array(
                self.paddings).flatten().astype("int32")
L
littletomatodonkey 已提交
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
        self.attrs['value'] = self.value
        self.attrs['mode'] = self.mode
        self.attrs['data_format'] = self.data_format
        if self.data_format == "NCDHW":
            paddings = [
                (0, 0),
                (0, 0),
                (self.paddings[4], self.paddings[5]),
                (self.paddings[2], self.paddings[3]),
                (self.paddings[0], self.paddings[1]),
            ]
        else:
            paddings = [
                (0, 0),
                (self.paddings[4], self.paddings[5]),
                (self.paddings[2], self.paddings[3]),
                (self.paddings[0], self.paddings[1]),
                (0, 0),
            ]
        if self.mode == "constant":
            out = np.pad(self.inputs['X'],
                         paddings,
                         mode=self.mode,
                         constant_values=self.value)
        elif self.mode == "reflect":
            out = np.pad(self.inputs['X'], paddings, mode=self.mode)
        elif self.mode == "replicate":
            out = np.pad(self.inputs['X'], paddings, mode="edge")
        elif self.mode == "circular":
            out = np.pad(self.inputs['X'], paddings, mode="wrap")
        self.outputs = {'Out': out}

    def test_check_output(self):
76
        self.check_output(check_eager=True)
L
littletomatodonkey 已提交
77 78

    def test_check_grad_normal(self):
79
        self.check_grad(['X'], 'Out', check_eager=True)
L
littletomatodonkey 已提交
80 81 82 83 84 85 86

    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 0, 0, 0, 0, 0]
        self.mode = "constant"
        self.data_format = "NCDHW"
        self.pad_value = 0.0
87
        self.variable_paddings = False
L
littletomatodonkey 已提交
88 89 90


class TestCase1(TestPad3dOp):
91

L
littletomatodonkey 已提交
92 93 94 95 96 97
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 2, 3, 4, 5]
        self.mode = "constant"
        self.data_format = "NCDHW"
        self.value = 1.0
98
        self.variable_paddings = False
L
littletomatodonkey 已提交
99 100 101


class TestCase2(TestPad3dOp):
102

L
littletomatodonkey 已提交
103 104 105 106 107 108
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [1, 1, 1, 1, 1, 1]
        self.mode = "constant"
        self.data_format = "NDHWC"
        self.value = 1.0
109
        self.variable_paddings = False
L
littletomatodonkey 已提交
110 111 112


class TestCase3(TestPad3dOp):
113

L
littletomatodonkey 已提交
114 115 116 117 118
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 1, 0, 2, 3]
        self.mode = "reflect"
        self.data_format = "NCDHW"
119
        self.variable_paddings = False
L
littletomatodonkey 已提交
120 121 122


class TestCase4(TestPad3dOp):
123

L
littletomatodonkey 已提交
124 125 126 127 128
    def initTestCase(self):
        self.shape = (4, 4, 4, 4, 4)
        self.paddings = [0, 1, 2, 1, 2, 3]
        self.mode = "reflect"
        self.data_format = "NDHWC"
129
        self.variable_paddings = False
L
littletomatodonkey 已提交
130 131 132


class TestCase5(TestPad3dOp):
133

L
littletomatodonkey 已提交
134 135 136 137 138
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 2, 3, 2, 1]
        self.mode = "replicate"
        self.data_format = "NCDHW"
139
        self.variable_paddings = False
L
littletomatodonkey 已提交
140 141 142


class TestCase6(TestPad3dOp):
143

L
littletomatodonkey 已提交
144 145 146 147 148
    def initTestCase(self):
        self.shape = (4, 4, 4, 4, 4)
        self.paddings = [5, 4, 2, 1, 2, 3]
        self.mode = "replicate"
        self.data_format = "NDHWC"
149
        self.variable_paddings = False
L
littletomatodonkey 已提交
150 151 152


class TestCase7(TestPad3dOp):
153

L
littletomatodonkey 已提交
154 155 156 157 158
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 2, 3, 2, 1]
        self.mode = "circular"
        self.data_format = "NCDHW"
159
        self.variable_paddings = False
L
littletomatodonkey 已提交
160 161 162


class TestCase8(TestPad3dOp):
163

L
littletomatodonkey 已提交
164 165 166 167 168
    def initTestCase(self):
        self.shape = (4, 4, 4, 4, 4)
        self.paddings = [0, 1, 2, 1, 2, 3]
        self.mode = "circular"
        self.data_format = "NDHWC"
169 170 171 172
        self.variable_paddings = False


class TestCase9(TestPad3dOp):
173

174 175 176 177 178 179 180 181 182 183
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 2, 3, 4, 5]
        self.mode = "constant"
        self.data_format = "NCDHW"
        self.value = 1.0
        self.variable_paddings = True


class TestCase10(TestPad3dOp):
184

185 186 187 188 189 190 191
    def initTestCase(self):
        self.shape = (2, 3, 4, 5, 6)
        self.paddings = [0, 1, 2, 3, 4, 5]
        self.mode = "constant"
        self.data_format = "NDHWC"
        self.value = 1.0
        self.variable_paddings = True
L
littletomatodonkey 已提交
192 193 194


class TestPadAPI(unittest.TestCase):
195

L
littletomatodonkey 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208
    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

    def check_static_result_1(self, place):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            input_shape = (1, 2, 3, 4, 5)
            pad = [1, 2, 1, 1, 3, 4]
            mode = "constant"
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)
209
            x = paddle.fluid.data(name="x", shape=input_shape)
210 211 212 213 214
            result = F.pad(x=x,
                           pad=pad,
                           value=value,
                           mode=mode,
                           data_format="NCDHW")
L
littletomatodonkey 已提交
215 216 217 218 219 220
            exe = Executor(place)
            fetches = exe.run(default_main_program(),
                              feed={"x": input_data},
                              fetch_list=[result])

            np_out = self._get_numpy_out(input_data, pad, mode, value)
221
            np.testing.assert_allclose(fetches[0], np_out, rtol=1e-05)
L
littletomatodonkey 已提交
222 223 224 225 226 227 228 229

    def check_static_result_2(self, place):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            input_shape = (2, 3, 4, 5, 6)
            pad = [1, 2, 1, 1, 1, 2]
            mode = "reflect"
            input_data = np.random.rand(*input_shape).astype(np.float32)
230
            x = paddle.fluid.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
231 232 233 234 235 236 237
            result1 = F.pad(x=x, pad=pad, mode=mode, data_format="NCDHW")
            result2 = F.pad(x=x, pad=pad, mode=mode, data_format="NDHWC")
            exe = Executor(place)
            fetches = exe.run(default_main_program(),
                              feed={"x": input_data},
                              fetch_list=[result1, result2])

238 239 240 241 242 243 244 245
            np_out1 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NCDHW")
            np_out2 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NDHWC")
246 247
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
248 249 250 251 252 253 254 255

    def check_static_result_3(self, place):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            input_shape = (2, 3, 4, 5, 6)
            pad = [1, 2, 1, 1, 3, 4]
            mode = "replicate"
            input_data = np.random.rand(*input_shape).astype(np.float32)
256
            x = paddle.fluid.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
257 258 259 260 261 262 263
            result1 = F.pad(x=x, pad=pad, mode=mode, data_format="NCDHW")
            result2 = F.pad(x=x, pad=pad, mode=mode, data_format="NDHWC")
            exe = Executor(place)
            fetches = exe.run(default_main_program(),
                              feed={"x": input_data},
                              fetch_list=[result1, result2])

264 265 266 267 268 269 270 271
            np_out1 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NCDHW")
            np_out2 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NDHWC")
272 273
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
274 275 276 277 278 279 280 281

    def check_static_result_4(self, place):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            input_shape = (2, 3, 4, 5, 6)
            pad = [1, 2, 1, 1, 3, 4]
            mode = "circular"
            input_data = np.random.rand(*input_shape).astype(np.float32)
282
            x = paddle.fluid.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
283 284 285 286 287 288 289
            result1 = F.pad(x=x, pad=pad, mode=mode, data_format="NCDHW")
            result2 = F.pad(x=x, pad=pad, mode=mode, data_format="NDHWC")
            exe = Executor(place)
            fetches = exe.run(default_main_program(),
                              feed={"x": input_data},
                              fetch_list=[result1, result2])

290 291 292 293 294 295 296 297
            np_out1 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NCDHW")
            np_out2 = self._get_numpy_out(input_data,
                                          pad,
                                          mode,
                                          data_format="NDHWC")
298 299
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
300 301 302 303 304 305 306

    def _get_numpy_out(self,
                       input_data,
                       pad,
                       mode,
                       value=0,
                       data_format="NCDHW"):
L
littletomatodonkey 已提交
307 308 309
        if mode == "constant" and len(pad) == len(input_data.shape) * 2:
            pad = np.reshape(pad, (-1, 2)).tolist()
        elif data_format == "NCDHW":
L
littletomatodonkey 已提交
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 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
            pad = [
                (0, 0),
                (0, 0),
                (pad[4], pad[5]),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
            ]
        elif data_format == "NDHWC":
            pad = [
                (0, 0),
                (pad[4], pad[5]),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
                (0, 0),
            ]
        elif data_format == "NCHW":
            pad = [
                (0, 0),
                (0, 0),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
            ]
        elif data_format == "NHWC":
            pad = [
                (0, 0),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
                (0, 0),
            ]
        elif data_format == "NCL":
            pad = [
                (0, 0),
                (0, 0),
                (pad[0], pad[1]),
            ]
        elif data_format == "NLC":
            pad = [
                (0, 0),
                (pad[0], pad[1]),
                (0, 0),
            ]

        if mode == "constant":
            out = np.pad(input_data, pad, mode=mode, constant_values=value)
        elif mode == "reflect":
            out = np.pad(input_data, pad, mode=mode)
        elif mode == "replicate":
            out = np.pad(input_data, pad, mode="edge")
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")

        return out

    def test_static(self):
        for place in self.places:
            self.check_static_result_1(place=place)
            self.check_static_result_2(place=place)
            self.check_static_result_3(place=place)
            self.check_static_result_4(place=place)

    def test_dygraph_1(self):
        paddle.disable_static()
        input_shape = (1, 2, 3, 4, 5)
        pad = [1, 2, 1, 1, 3, 4]
L
littletomatodonkey 已提交
374
        pad_3 = [1, 2, 1, 1, 3, 4, 5, 6, 7, 8]
L
littletomatodonkey 已提交
375 376 377
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
        np_out1 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NCDHW")
        np_out2 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NDHWC")
        np_out3 = self._get_numpy_out(input_data,
                                      pad_3,
                                      mode,
                                      value,
                                      data_format="NCDHW")
L
littletomatodonkey 已提交
393 394 395 396 397 398 399 400 401 402 403 404
        tensor_data = paddle.to_tensor(input_data)

        y1 = F.pad(tensor_data,
                   pad=pad,
                   mode=mode,
                   value=value,
                   data_format="NCDHW")
        y2 = F.pad(tensor_data,
                   pad=pad,
                   mode=mode,
                   value=value,
                   data_format="NDHWC")
L
littletomatodonkey 已提交
405 406 407 408 409
        y3 = F.pad(tensor_data,
                   pad=pad_3,
                   mode=mode,
                   value=value,
                   data_format="NCDHW")
L
littletomatodonkey 已提交
410

411 412 413
        np.testing.assert_allclose(y1.numpy(), np_out1, rtol=1e-05)
        np.testing.assert_allclose(y2.numpy(), np_out2, rtol=1e-05)
        np.testing.assert_allclose(y3.numpy(), np_out3, rtol=1e-05)
L
littletomatodonkey 已提交
414 415 416 417 418

    def test_dygraph_2(self):
        paddle.disable_static()
        input_shape = (2, 3, 4, 5)
        pad = [1, 1, 3, 4]
L
littletomatodonkey 已提交
419
        pad_3 = [1, 2, 1, 1, 3, 4, 5, 6]
L
littletomatodonkey 已提交
420 421 422
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        np_out1 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NCHW")
        np_out2 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NHWC")
        np_out3 = self._get_numpy_out(input_data,
                                      pad_3,
                                      mode,
                                      value,
                                      data_format="NCHW")
L
littletomatodonkey 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451

        tensor_data = paddle.to_tensor(input_data)
        tensor_pad = paddle.to_tensor(pad, dtype="int32")

        y1 = F.pad(tensor_data,
                   pad=tensor_pad,
                   mode=mode,
                   value=value,
                   data_format="NCHW")
        y2 = F.pad(tensor_data,
                   pad=tensor_pad,
                   mode=mode,
                   value=value,
                   data_format="NHWC")
L
littletomatodonkey 已提交
452 453 454 455 456
        y3 = F.pad(tensor_data,
                   pad=pad_3,
                   mode=mode,
                   value=value,
                   data_format="NCHW")
L
littletomatodonkey 已提交
457

458 459 460
        np.testing.assert_allclose(y1.numpy(), np_out1, rtol=1e-05)
        np.testing.assert_allclose(y2.numpy(), np_out2, rtol=1e-05)
        np.testing.assert_allclose(y3.numpy(), np_out3, rtol=1e-05)
L
littletomatodonkey 已提交
461 462 463 464 465

    def test_dygraph_3(self):
        paddle.disable_static()
        input_shape = (3, 4, 5)
        pad = [3, 4]
L
littletomatodonkey 已提交
466
        pad_3 = [3, 4, 5, 6, 7, 8]
L
littletomatodonkey 已提交
467 468 469
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        np_out1 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NCL")
        np_out2 = self._get_numpy_out(input_data,
                                      pad,
                                      mode,
                                      value,
                                      data_format="NLC")
        np_out3 = self._get_numpy_out(input_data,
                                      pad_3,
                                      mode,
                                      value,
                                      data_format="NCL")
L
littletomatodonkey 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497
        tensor_data = paddle.to_tensor(input_data)
        tensor_pad = paddle.to_tensor(pad, dtype="int32")

        y1 = F.pad(tensor_data,
                   pad=tensor_pad,
                   mode=mode,
                   value=value,
                   data_format="NCL")
        y2 = F.pad(tensor_data,
                   pad=tensor_pad,
                   mode=mode,
                   value=value,
                   data_format="NLC")
L
littletomatodonkey 已提交
498 499 500 501 502
        y3 = F.pad(tensor_data,
                   pad=pad_3,
                   mode=mode,
                   value=value,
                   data_format="NCL")
L
littletomatodonkey 已提交
503

504 505 506
        np.testing.assert_allclose(y1.numpy(), np_out1, rtol=1e-05)
        np.testing.assert_allclose(y2.numpy(), np_out2, rtol=1e-05)
        np.testing.assert_allclose(y3.numpy(), np_out3, rtol=1e-05)
L
littletomatodonkey 已提交
507 508 509


class TestPad1dAPI(unittest.TestCase):
510

L
littletomatodonkey 已提交
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
    def _get_numpy_out(self,
                       input_data,
                       pad,
                       mode,
                       value=0.0,
                       data_format="NCL"):
        if data_format == "NCL":
            pad = [
                (0, 0),
                (0, 0),
                (pad[0], pad[1]),
            ]
        else:
            pad = [
                (0, 0),
                (pad[0], pad[1]),
                (0, 0),
            ]

        if mode == "constant":
            out = np.pad(input_data, pad, mode=mode, constant_values=value)
        elif mode == "reflect":
            out = np.pad(input_data, pad, mode=mode)
        elif mode == "replicate":
            out = np.pad(input_data, pad, mode="edge")
L
littletomatodonkey 已提交
536 537
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550

        return out

    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

    def test_class(self):
        paddle.disable_static()
        for place in self.places:
            input_shape = (3, 4, 5)
            pad = [1, 2]
551
            pad_int = 1
L
littletomatodonkey 已提交
552 553 554
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
555 556 557
            pad_reflection = nn.Pad1D(padding=pad, mode="reflect")
            pad_replication = nn.Pad1D(padding=pad, mode="replicate")
            pad_constant = nn.Pad1D(padding=pad, mode="constant", value=value)
558 559 560
            pad_constant_int = nn.Pad1D(padding=pad_int,
                                        mode="constant",
                                        value=value)
L
littletomatodonkey 已提交
561
            pad_circular = nn.Pad1D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
562 563 564 565

            data = paddle.to_tensor(input_data)

            output = pad_reflection(data)
566 567 568 569
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "reflect",
                                         data_format="NCL")
570
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
571 572

            output = pad_replication(data)
573 574 575 576
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "replicate",
                                         data_format="NCL")
577
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
578 579

            output = pad_constant(data)
580 581 582 583 584
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "constant",
                                         value=value,
                                         data_format="NCL")
585
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
586

587
            output = pad_constant_int(data)
588 589 590 591
            np_out = self._get_numpy_out(input_data, [pad_int] * 2,
                                         "constant",
                                         value=value,
                                         data_format="NCL")
592
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
593

L
littletomatodonkey 已提交
594
            output = pad_circular(data)
595 596 597 598 599
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "circular",
                                         value=value,
                                         data_format="NCL")
600
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
601

L
littletomatodonkey 已提交
602 603

class TestPad2dAPI(unittest.TestCase):
604

L
littletomatodonkey 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    def _get_numpy_out(self,
                       input_data,
                       pad,
                       mode,
                       value=0.0,
                       data_format="NCHW"):
        if data_format == "NCHW":
            pad = [
                (0, 0),
                (0, 0),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
            ]
        else:
            pad = [
                (0, 0),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
                (0, 0),
            ]

        if mode == "constant":
            out = np.pad(input_data, pad, mode=mode, constant_values=value)
        elif mode == "reflect":
            out = np.pad(input_data, pad, mode=mode)
        elif mode == "replicate":
            out = np.pad(input_data, pad, mode="edge")
L
littletomatodonkey 已提交
632 633
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646

        return out

    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

    def test_class(self):
        paddle.disable_static()
        for place in self.places:
            input_shape = (3, 4, 5, 6)
            pad = [1, 2, 2, 1]
647
            pad_int = 1
L
littletomatodonkey 已提交
648 649 650
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
651 652 653
            pad_reflection = nn.Pad2D(padding=pad, mode="reflect")
            pad_replication = nn.Pad2D(padding=pad, mode="replicate")
            pad_constant = nn.Pad2D(padding=pad, mode="constant", value=value)
654 655 656
            pad_constant_int = nn.Pad2D(padding=pad_int,
                                        mode="constant",
                                        value=value)
L
littletomatodonkey 已提交
657
            pad_circular = nn.Pad2D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
658 659 660 661

            data = paddle.to_tensor(input_data)

            output = pad_reflection(data)
662 663 664 665
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "reflect",
                                         data_format="NCHW")
666
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
667 668

            output = pad_replication(data)
669 670 671 672
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "replicate",
                                         data_format="NCHW")
673
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
674 675

            output = pad_constant(data)
676 677 678 679 680
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "constant",
                                         value=value,
                                         data_format="NCHW")
681
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
682

683
            output = pad_constant_int(data)
684 685 686 687
            np_out = self._get_numpy_out(input_data, [pad_int] * 4,
                                         "constant",
                                         value=value,
                                         data_format="NCHW")
688
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
689

L
littletomatodonkey 已提交
690
            output = pad_circular(data)
691 692 693 694
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "circular",
                                         data_format="NCHW")
695
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
696 697 698


class TestPad3dAPI(unittest.TestCase):
699

L
littletomatodonkey 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    def _get_numpy_out(self,
                       input_data,
                       pad,
                       mode,
                       value=0.0,
                       data_format="NCDHW"):
        if data_format == "NCDHW":
            pad = [
                (0, 0),
                (0, 0),
                (pad[4], pad[5]),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
            ]
        else:
            pad = [
                (0, 0),
                (pad[4], pad[5]),
                (pad[2], pad[3]),
                (pad[0], pad[1]),
                (0, 0),
            ]

        if mode == "constant":
            out = np.pad(input_data, pad, mode=mode, constant_values=value)
        elif mode == "reflect":
            out = np.pad(input_data, pad, mode=mode)
        elif mode == "replicate":
            out = np.pad(input_data, pad, mode="edge")
L
littletomatodonkey 已提交
729 730
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743

        return out

    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

    def test_class(self):
        paddle.disable_static()
        for place in self.places:
            input_shape = (3, 4, 5, 6, 7)
            pad = [1, 2, 2, 1, 1, 0]
744
            pad_int = 1
L
littletomatodonkey 已提交
745 746 747
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
748 749 750
            pad_reflection = nn.Pad3D(padding=pad, mode="reflect")
            pad_replication = nn.Pad3D(padding=pad, mode="replicate")
            pad_constant = nn.Pad3D(padding=pad, mode="constant", value=value)
751 752 753
            pad_constant_int = nn.Pad3D(padding=pad_int,
                                        mode="constant",
                                        value=value)
L
littletomatodonkey 已提交
754
            pad_circular = nn.Pad3D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
755 756 757

            data = paddle.to_tensor(input_data)

L
littletomatodonkey 已提交
758
            output = pad_reflection(data)
759 760 761 762
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "reflect",
                                         data_format="NCDHW")
763
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
764

L
littletomatodonkey 已提交
765
            output = pad_replication(data)
766 767 768 769
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "replicate",
                                         data_format="NCDHW")
770
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
771 772

            output = pad_constant(data)
773 774 775 776 777
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "constant",
                                         value=value,
                                         data_format="NCDHW")
778
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
779

780
            output = pad_constant_int(data)
781 782 783 784
            np_out = self._get_numpy_out(input_data, [pad_int] * 6,
                                         "constant",
                                         value=value,
                                         data_format="NCDHW")
785
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
786

L
littletomatodonkey 已提交
787
            output = pad_circular(data)
788 789 790 791
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "circular",
                                         data_format="NCDHW")
792
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
793

794 795 796 797 798 799 800 801
    def test_pad_tensor(self):
        paddle.disable_static()
        for place in self.places:
            input_shape = (3, 4, 5, 6, 7)
            pad = [1, 2, 2, 1, 1, 0]
            pad_tensor = paddle.to_tensor(pad)
            input_data = np.random.rand(*input_shape).astype(np.float32)

802 803 804 805 806 807
            pad_reflection_ncdhw = nn.Pad3D(padding=pad_tensor,
                                            mode="reflect",
                                            data_format="NCDHW")
            pad_reflection_ndhwc = nn.Pad3D(padding=pad_tensor,
                                            mode="reflect",
                                            data_format="NDHWC")
808 809 810
            data = paddle.to_tensor(input_data)

            output = pad_reflection_ncdhw(data)
811 812 813 814
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "reflect",
                                         data_format="NCDHW")
815
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
816 817

            output = pad_reflection_ndhwc(data)
818 819 820 821
            np_out = self._get_numpy_out(input_data,
                                         pad,
                                         "reflect",
                                         data_format="NDHWC")
822
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
823

L
littletomatodonkey 已提交
824 825

class TestPad3dOpError(unittest.TestCase):
826

827 828 829 830 831
    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

L
littletomatodonkey 已提交
832
    def test_errors(self):
833

L
littletomatodonkey 已提交
834 835 836
        def test_variable():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
837
            y = F.pad(x=data, pad=[1, 1, 1, 1, 1, 1], data_format="NCDHW")
L
littletomatodonkey 已提交
838 839 840 841

        def test_reflect_1():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
842 843 844 845 846 847
            x = paddle.to_tensor(data)
            y = F.pad(x,
                      pad=[5, 6, 1, 1, 1, 1],
                      value=1,
                      mode='reflect',
                      data_format="NCDHW")
L
littletomatodonkey 已提交
848 849 850 851

        def test_reflect_2():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
852 853 854 855 856 857
            x = paddle.to_tensor(data)
            y = F.pad(x,
                      pad=[1, 1, 4, 3, 1, 1],
                      value=1,
                      mode='reflect',
                      data_format="NCDHW")
L
littletomatodonkey 已提交
858 859 860 861

        def test_reflect_3():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
            x = paddle.to_tensor(data)
            y = F.pad(x,
                      pad=[1, 1, 1, 1, 2, 3],
                      value=1,
                      mode='reflect',
                      data_format="NCDHW")

        def test_circular_1():
            input_shape = (1, 2, 0, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
            x = paddle.to_tensor(data)
            y = F.pad(x,
                      pad=[1, 1, 1, 1, 2, 3],
                      mode='circular',
                      data_format="NCDHW")
L
littletomatodonkey 已提交
877

878 879 880 881 882 883 884 885 886
        def test_replicate_1():
            input_shape = (1, 2, 0, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
            x = paddle.to_tensor(data)
            y = F.pad(x,
                      pad=[1, 1, 1, 1, 2, 3],
                      mode='replicate',
                      data_format="NCDHW")

887 888 889 890 891 892 893
        paddle.disable_static()
        for place in self.places:
            self.assertRaises(ValueError, test_variable)
            self.assertRaises(Exception, test_reflect_1)
            self.assertRaises(Exception, test_reflect_2)
            self.assertRaises(Exception, test_reflect_3)
            self.assertRaises(Exception, test_circular_1)
894
            self.assertRaises(Exception, test_replicate_1)
895
        paddle.enable_static()
L
littletomatodonkey 已提交
896 897


898
class TestPadDataformatError(unittest.TestCase):
899

900
    def test_errors(self):
901

902 903 904
        def test_ncl():
            input_shape = (1, 2, 3, 4)
            pad = paddle.to_tensor(np.array([2, 1, 2, 1]).astype('int32'))
905 906
            data = np.arange(np.prod(input_shape),
                             dtype=np.float64).reshape(input_shape) + 1
L
littletomatodonkey 已提交
907
            my_pad = nn.Pad1D(padding=pad, mode="replicate", data_format="NCL")
908 909 910 911 912 913
            data = paddle.to_tensor(data)
            result = my_pad(data)

        def test_nchw():
            input_shape = (1, 2, 4)
            pad = paddle.to_tensor(np.array([2, 1, 2, 1]).astype('int32'))
914 915
            data = np.arange(np.prod(input_shape),
                             dtype=np.float64).reshape(input_shape) + 1
L
littletomatodonkey 已提交
916
            my_pad = nn.Pad1D(padding=pad, mode="replicate", data_format="NCHW")
917 918 919 920 921 922
            data = paddle.to_tensor(data)
            result = my_pad(data)

        def test_ncdhw():
            input_shape = (1, 2, 3, 4)
            pad = paddle.to_tensor(np.array([2, 1, 2, 1]).astype('int32'))
923 924 925 926 927
            data = np.arange(np.prod(input_shape),
                             dtype=np.float64).reshape(input_shape) + 1
            my_pad = nn.Pad1D(padding=pad,
                              mode="replicate",
                              data_format="NCDHW")
928 929 930 931 932 933 934 935 936 937
            data = paddle.to_tensor(data)
            result = my_pad(data)

        self.assertRaises(AssertionError, test_ncl)

        self.assertRaises(AssertionError, test_nchw)

        self.assertRaises(AssertionError, test_ncdhw)


L
littletomatodonkey 已提交
938 939
if __name__ == '__main__':
    unittest.main()