test_pad3d_op.py 29.9 KB
Newer Older
L
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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
16

L
littletomatodonkey 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest
19

L
littletomatodonkey 已提交
20
import paddle
21
import paddle.fluid.core as core
L
littletomatodonkey 已提交
22 23
import paddle.nn as nn
import paddle.nn.functional as F
24
from paddle.fluid import Executor, Program, default_main_program, program_guard
L
littletomatodonkey 已提交
25 26 27 28 29 30 31 32


class TestPad3dOp(OpTest):
    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 40
            self.inputs['Paddings'] = (
                np.array(self.paddings).flatten().astype("int32")
            )
L
littletomatodonkey 已提交
41
        else:
42 43 44
            self.attrs['paddings'] = (
                np.array(self.paddings).flatten().astype("int32")
            )
L
littletomatodonkey 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
        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":
65 66 67 68 69 70
            out = np.pad(
                self.inputs['X'],
                paddings,
                mode=self.mode,
                constant_values=self.value,
            )
L
littletomatodonkey 已提交
71 72 73 74 75 76 77 78 79
        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):
W
wanghuancoder 已提交
80
        self.check_output()
L
littletomatodonkey 已提交
81 82

    def test_check_grad_normal(self):
W
wanghuancoder 已提交
83
        self.check_grad(['X'], 'Out')
L
littletomatodonkey 已提交
84 85 86 87 88 89 90

    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
91
        self.variable_paddings = False
L
littletomatodonkey 已提交
92 93 94 95 96 97 98 99 100


class TestCase1(TestPad3dOp):
    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
101
        self.variable_paddings = False
L
littletomatodonkey 已提交
102 103 104 105 106 107 108 109 110


class TestCase2(TestPad3dOp):
    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
111
        self.variable_paddings = False
L
littletomatodonkey 已提交
112 113 114 115 116 117 118 119


class TestCase3(TestPad3dOp):
    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"
120
        self.variable_paddings = False
L
littletomatodonkey 已提交
121 122 123 124 125 126 127 128


class TestCase4(TestPad3dOp):
    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 133 134 135 136 137


class TestCase5(TestPad3dOp):
    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"
138
        self.variable_paddings = False
L
littletomatodonkey 已提交
139 140 141 142 143 144 145 146


class TestCase6(TestPad3dOp):
    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"
147
        self.variable_paddings = False
L
littletomatodonkey 已提交
148 149 150 151 152 153 154 155


class TestCase7(TestPad3dOp):
    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"
156
        self.variable_paddings = False
L
littletomatodonkey 已提交
157 158 159 160 161 162 163 164


class TestCase8(TestPad3dOp):
    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"
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        self.variable_paddings = False


class TestCase9(TestPad3dOp):
    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):
    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 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201


class TestPadAPI(unittest.TestCase):
    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)
202
            x = paddle.static.data(name="x", shape=input_shape)
203 204 205
            result = F.pad(
                x=x, pad=pad, value=value, mode=mode, data_format="NCDHW"
            )
L
littletomatodonkey 已提交
206
            exe = Executor(place)
207 208 209 210 211
            fetches = exe.run(
                default_main_program(),
                feed={"x": input_data},
                fetch_list=[result],
            )
L
littletomatodonkey 已提交
212 213

            np_out = self._get_numpy_out(input_data, pad, mode, value)
214
            np.testing.assert_allclose(fetches[0], np_out, rtol=1e-05)
L
littletomatodonkey 已提交
215 216 217 218 219 220 221 222

    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)
223
            x = paddle.static.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
224 225 226
            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)
227 228 229 230 231 232 233 234 235 236 237 238
            fetches = exe.run(
                default_main_program(),
                feed={"x": input_data},
                fetch_list=[result1, result2],
            )

            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"
            )
239 240
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
241 242 243 244 245 246 247 248

    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)
249
            x = paddle.static.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
250 251 252
            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)
253 254 255 256 257 258 259 260 261 262 263 264
            fetches = exe.run(
                default_main_program(),
                feed={"x": input_data},
                fetch_list=[result1, result2],
            )

            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"
            )
265 266
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
267 268 269 270 271 272 273 274

    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)
275
            x = paddle.static.data(name="x", shape=input_shape)
L
littletomatodonkey 已提交
276 277 278
            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)
279 280 281 282 283 284 285 286 287 288 289 290
            fetches = exe.run(
                default_main_program(),
                feed={"x": input_data},
                fetch_list=[result1, result2],
            )

            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"
            )
291 292
            np.testing.assert_allclose(fetches[0], np_out1, rtol=1e-05)
            np.testing.assert_allclose(fetches[1], np_out2, rtol=1e-05)
L
littletomatodonkey 已提交
293

294 295 296
    def _get_numpy_out(
        self, input_data, pad, mode, value=0, data_format="NCDHW"
    ):
L
littletomatodonkey 已提交
297 298 299
        if mode == "constant" and len(pad) == len(input_data.shape) * 2:
            pad = np.reshape(pad, (-1, 2)).tolist()
        elif data_format == "NCDHW":
L
littletomatodonkey 已提交
300 301 302 303 304 305 306 307 308 309 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
            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 已提交
364
        pad_3 = [1, 2, 1, 1, 3, 4, 5, 6, 7, 8]
L
littletomatodonkey 已提交
365 366 367
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
368 369 370 371 372 373 374 375 376
        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 已提交
377 378
        tensor_data = paddle.to_tensor(input_data)

379 380 381 382 383 384 385 386 387
        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"
        )
        y3 = F.pad(
            tensor_data, pad=pad_3, mode=mode, value=value, data_format="NCDHW"
        )
L
littletomatodonkey 已提交
388

389 390 391
        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 已提交
392 393 394 395 396

    def test_dygraph_2(self):
        paddle.disable_static()
        input_shape = (2, 3, 4, 5)
        pad = [1, 1, 3, 4]
L
littletomatodonkey 已提交
397
        pad_3 = [1, 2, 1, 1, 3, 4, 5, 6]
L
littletomatodonkey 已提交
398 399 400
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
401 402 403 404 405 406 407 408 409
        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 已提交
410 411 412 413

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

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        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",
        )
        y3 = F.pad(
            tensor_data, pad=pad_3, mode=mode, value=value, data_format="NCHW"
        )
L
littletomatodonkey 已提交
431

432 433 434
        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 已提交
435 436 437 438 439

    def test_dygraph_3(self):
        paddle.disable_static()
        input_shape = (3, 4, 5)
        pad = [3, 4]
L
littletomatodonkey 已提交
440
        pad_3 = [3, 4, 5, 6, 7, 8]
L
littletomatodonkey 已提交
441 442 443
        mode = "constant"
        value = 100
        input_data = np.random.rand(*input_shape).astype(np.float32)
444 445 446 447 448 449 450 451 452
        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 已提交
453 454 455
        tensor_data = paddle.to_tensor(input_data)
        tensor_pad = paddle.to_tensor(pad, dtype="int32")

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        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",
        )
        y3 = F.pad(
            tensor_data, pad=pad_3, mode=mode, value=value, data_format="NCL"
        )
L
littletomatodonkey 已提交
473

474 475 476
        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 已提交
477 478 479


class TestPad1dAPI(unittest.TestCase):
480 481 482
    def _get_numpy_out(
        self, input_data, pad, mode, value=0.0, data_format="NCL"
    ):
L
littletomatodonkey 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        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 已提交
502 503
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516

        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]
517
            pad_int = 1
L
littletomatodonkey 已提交
518 519 520
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
521 522 523
            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)
524 525 526
            pad_constant_int = nn.Pad1D(
                padding=pad_int, mode="constant", value=value
            )
L
littletomatodonkey 已提交
527
            pad_circular = nn.Pad1D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
528 529 530 531

            data = paddle.to_tensor(input_data)

            output = pad_reflection(data)
532 533 534
            np_out = self._get_numpy_out(
                input_data, pad, "reflect", data_format="NCL"
            )
535
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
536 537

            output = pad_replication(data)
538 539 540
            np_out = self._get_numpy_out(
                input_data, pad, "replicate", data_format="NCL"
            )
541
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
542 543

            output = pad_constant(data)
544 545 546
            np_out = self._get_numpy_out(
                input_data, pad, "constant", value=value, data_format="NCL"
            )
547
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
548

549
            output = pad_constant_int(data)
550 551 552 553 554 555 556
            np_out = self._get_numpy_out(
                input_data,
                [pad_int] * 2,
                "constant",
                value=value,
                data_format="NCL",
            )
557
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
558

L
littletomatodonkey 已提交
559
            output = pad_circular(data)
560 561 562
            np_out = self._get_numpy_out(
                input_data, pad, "circular", value=value, data_format="NCL"
            )
563
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
564

L
littletomatodonkey 已提交
565 566

class TestPad2dAPI(unittest.TestCase):
567 568 569
    def _get_numpy_out(
        self, input_data, pad, mode, value=0.0, data_format="NCHW"
    ):
L
littletomatodonkey 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        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 已提交
591 592
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605

        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]
606
            pad_int = 1
L
littletomatodonkey 已提交
607 608 609
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
610 611 612
            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)
613 614 615
            pad_constant_int = nn.Pad2D(
                padding=pad_int, mode="constant", value=value
            )
L
littletomatodonkey 已提交
616
            pad_circular = nn.Pad2D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
617 618 619 620

            data = paddle.to_tensor(input_data)

            output = pad_reflection(data)
621 622 623
            np_out = self._get_numpy_out(
                input_data, pad, "reflect", data_format="NCHW"
            )
624
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
625 626

            output = pad_replication(data)
627 628 629
            np_out = self._get_numpy_out(
                input_data, pad, "replicate", data_format="NCHW"
            )
630
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
631 632

            output = pad_constant(data)
633 634 635
            np_out = self._get_numpy_out(
                input_data, pad, "constant", value=value, data_format="NCHW"
            )
636
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
637

638
            output = pad_constant_int(data)
639 640 641 642 643 644 645
            np_out = self._get_numpy_out(
                input_data,
                [pad_int] * 4,
                "constant",
                value=value,
                data_format="NCHW",
            )
646
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
647

L
littletomatodonkey 已提交
648
            output = pad_circular(data)
649 650 651
            np_out = self._get_numpy_out(
                input_data, pad, "circular", data_format="NCHW"
            )
652
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
653 654 655


class TestPad3dAPI(unittest.TestCase):
656 657 658
    def _get_numpy_out(
        self, input_data, pad, mode, value=0.0, data_format="NCDHW"
    ):
L
littletomatodonkey 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        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 已提交
682 683
        elif mode == "circular":
            out = np.pad(input_data, pad, mode="wrap")
L
littletomatodonkey 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696

        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]
697
            pad_int = 1
L
littletomatodonkey 已提交
698 699 700
            value = 100
            input_data = np.random.rand(*input_shape).astype(np.float32)

L
littletomatodonkey 已提交
701 702 703
            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)
704 705 706
            pad_constant_int = nn.Pad3D(
                padding=pad_int, mode="constant", value=value
            )
L
littletomatodonkey 已提交
707
            pad_circular = nn.Pad3D(padding=pad, mode="circular")
L
littletomatodonkey 已提交
708 709 710

            data = paddle.to_tensor(input_data)

L
littletomatodonkey 已提交
711
            output = pad_reflection(data)
712 713 714
            np_out = self._get_numpy_out(
                input_data, pad, "reflect", data_format="NCDHW"
            )
715
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
716

L
littletomatodonkey 已提交
717
            output = pad_replication(data)
718 719 720
            np_out = self._get_numpy_out(
                input_data, pad, "replicate", data_format="NCDHW"
            )
721
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
722 723

            output = pad_constant(data)
724 725 726
            np_out = self._get_numpy_out(
                input_data, pad, "constant", value=value, data_format="NCDHW"
            )
727
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
728

729
            output = pad_constant_int(data)
730 731 732 733 734 735 736
            np_out = self._get_numpy_out(
                input_data,
                [pad_int] * 6,
                "constant",
                value=value,
                data_format="NCDHW",
            )
737
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
738

L
littletomatodonkey 已提交
739
            output = pad_circular(data)
740 741 742
            np_out = self._get_numpy_out(
                input_data, pad, "circular", data_format="NCDHW"
            )
743
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
L
littletomatodonkey 已提交
744

745 746 747 748 749 750 751 752
    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)

753 754 755 756 757 758
            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"
            )
759 760 761
            data = paddle.to_tensor(input_data)

            output = pad_reflection_ncdhw(data)
762 763 764
            np_out = self._get_numpy_out(
                input_data, pad, "reflect", data_format="NCDHW"
            )
765
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
766 767

            output = pad_reflection_ndhwc(data)
768 769 770
            np_out = self._get_numpy_out(
                input_data, pad, "reflect", data_format="NDHWC"
            )
771
            np.testing.assert_allclose(output.numpy(), np_out, rtol=1e-05)
772

L
littletomatodonkey 已提交
773 774

class TestPad3dOpError(unittest.TestCase):
775 776 777 778 779
    def setUp(self):
        self.places = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

L
littletomatodonkey 已提交
780 781 782 783
    def test_errors(self):
        def test_variable():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
784
            y = F.pad(x=data, pad=[1, 1, 1, 1, 1, 1], data_format="NCDHW")
L
littletomatodonkey 已提交
785 786 787 788

        def test_reflect_1():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
789
            x = paddle.to_tensor(data)
790 791 792 793 794 795 796
            y = F.pad(
                x,
                pad=[5, 6, 1, 1, 1, 1],
                value=1,
                mode='reflect',
                data_format="NCDHW",
            )
L
littletomatodonkey 已提交
797 798 799 800

        def test_reflect_2():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
801
            x = paddle.to_tensor(data)
802 803 804 805 806 807 808
            y = F.pad(
                x,
                pad=[1, 1, 4, 3, 1, 1],
                value=1,
                mode='reflect',
                data_format="NCDHW",
            )
L
littletomatodonkey 已提交
809 810 811 812

        def test_reflect_3():
            input_shape = (1, 2, 3, 4, 5)
            data = np.random.rand(*input_shape).astype(np.float32)
813
            x = paddle.to_tensor(data)
814 815 816 817 818 819 820
            y = F.pad(
                x,
                pad=[1, 1, 1, 1, 2, 3],
                value=1,
                mode='reflect',
                data_format="NCDHW",
            )
821 822 823 824 825

        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)
826 827 828
            y = F.pad(
                x, pad=[1, 1, 1, 1, 2, 3], mode='circular', data_format="NCDHW"
            )
L
littletomatodonkey 已提交
829

830 831 832 833
        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)
834 835 836
            y = F.pad(
                x, pad=[1, 1, 1, 1, 2, 3], mode='replicate', data_format="NCDHW"
            )
837

838 839 840 841 842 843 844
        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)
845
            self.assertRaises(Exception, test_replicate_1)
846
        paddle.enable_static()
L
littletomatodonkey 已提交
847 848


849 850 851 852 853
class TestPadDataformatError(unittest.TestCase):
    def test_errors(self):
        def test_ncl():
            input_shape = (1, 2, 3, 4)
            pad = paddle.to_tensor(np.array([2, 1, 2, 1]).astype('int32'))
854 855 856 857 858 859
            data = (
                np.arange(np.prod(input_shape), dtype=np.float64).reshape(
                    input_shape
                )
                + 1
            )
L
littletomatodonkey 已提交
860
            my_pad = nn.Pad1D(padding=pad, mode="replicate", data_format="NCL")
861 862 863 864 865 866
            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'))
867 868 869 870 871 872
            data = (
                np.arange(np.prod(input_shape), dtype=np.float64).reshape(
                    input_shape
                )
                + 1
            )
L
littletomatodonkey 已提交
873
            my_pad = nn.Pad1D(padding=pad, mode="replicate", data_format="NCHW")
874 875 876 877 878 879
            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'))
880 881 882 883 884 885 886 887 888
            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"
            )
889 890 891 892 893 894 895 896 897 898
            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 已提交
899 900
if __name__ == '__main__':
    unittest.main()