test_dropout_op.py 57.4 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15
import unittest
16

17
import numpy as np
18
import parameterized as param
W
wanghuancoder 已提交
19
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
20

21
import paddle
22 23
from paddle import _C_ops, fluid, static
from paddle.fluid import Program, core, program_guard
24
from paddle.incubate.autograd import primapi
H
hong 已提交
25

26

W
wanghuancoder 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
def dropout_wapper(
    X,
    Seed=None,
    dropout_prob=0.5,
    is_test=False,
    dropout_implementation="downgrade_in_infer",
    seed=0,
    fix_seed=False,
):
    return paddle._C_ops.dropout(
        X,
        Seed,
        dropout_prob,
        is_test,
        dropout_implementation,
        seed,
        fix_seed,
    )


47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
def prim_dropout_wrapper(
    x,
    Seed=None,
    dropout_prob=0.5,
    is_test=False,
    dropout_implementation='upscale_in_train',
    seed=None,
    fix_seed=None,
):
    return paddle.nn.functional.dropout(
        x,
        p=dropout_prob,
        axis=None,
        training=not is_test,
        mode=dropout_implementation,
    )


65
class TestDropoutOp(OpTest):
66
    def setUp(self):
67
        self.op_type = "dropout"
68
        self.prim_op_type = "comp"
W
wanghuancoder 已提交
69
        self.python_api = dropout_wapper
70
        self.public_python_api = prim_dropout_wrapper
71
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
72
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
73 74
        self.outputs = {
            'Out': self.inputs['X'],
75
            'Mask': np.ones((32, 64)).astype('uint8'),
Y
Yu Yang 已提交
76
        }
77 78 79 80
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
81

82
    def test_check_output(self):
83
        self.check_output(check_prim=True)
84 85

    def test_check_grad_normal(self):
86 87
        # Now in dy2st mode x_grad = [], so set check_prim=False
        self.check_grad(['X'], 'Out', check_prim=False)
88 89


90 91 92
class TestDropoutOpInput1d(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
93
        self.python_api = dropout_wapper
94 95
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
96
        self.inputs = {'X': np.random.random((2000,)).astype("float32")}
97 98 99
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
        self.outputs = {
            'Out': self.inputs['X'],
100
            'Mask': np.ones(2000).astype('uint8'),
101
        }
102 103 104 105
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
106 107

    def test_check_output(self):
108
        self.check_output(check_prim=True)
109 110

    def test_check_grad_normal(self):
111 112
        # Now in dy2st mode x_grad = [], so set check_prim=False
        self.check_grad(['X'], 'Out', check_prim=False)
113 114


115
class TestDropoutOp2(TestDropoutOp):
116
    def setUp(self):
117
        self.op_type = "dropout"
W
wanghuancoder 已提交
118
        self.python_api = dropout_wapper
119 120
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
121
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
122
        self.attrs = {'dropout_prob': 1.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
123 124
        self.outputs = {
            'Out': np.zeros((32, 64)).astype('float32'),
125
            'Mask': np.zeros((32, 64)).astype('uint8'),
Y
Yu Yang 已提交
126
        }
127 128


129
class TestDropoutOp3(TestDropoutOp):
130
    def setUp(self):
131
        self.op_type = "dropout"
W
wanghuancoder 已提交
132
        self.python_api = dropout_wapper
133 134
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
135
        self.inputs = {'X': np.random.random((32, 64, 2)).astype("float32")}
136
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
137 138
        self.outputs = {
            'Out': self.inputs['X'],
139
            'Mask': np.ones((32, 64, 2)).astype('uint8'),
Y
Yu Yang 已提交
140
        }
141 142 143 144
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
145 146


147
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
148 149 150
class TestDropoutOp4(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
151
        self.python_api = dropout_wapper
152 153
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
154
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
155
        self.attrs = {'dropout_prob': 0.35, 'fix_seed': True, 'is_test': True}
156 157 158
        self.outputs = {
            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])
        }
159 160

    def test_check_output(self):
161
        self.check_output(check_prim=True)
162 163


164
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
165 166 167
class TestDropoutOp5(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
168
        self.python_api = dropout_wapper
169 170
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
171
        self.inputs = {'X': np.random.random((32, 64, 3)).astype("float32")}
172
        self.attrs = {'dropout_prob': 0.75, 'is_test': True}
173 174 175
        self.outputs = {
            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])
        }
176 177

    def test_check_output(self):
178
        self.check_output(check_prim=True)
P
phlrain 已提交
179 180 181 182 183


class TestDropoutOp6(TestDropoutOp):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
184
        self.python_api = dropout_wapper
185 186
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
P
phlrain 已提交
187 188 189 190 191
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
        self.attrs = {
            'dropout_prob': 1.0,
            'fix_seed': True,
            'is_test': False,
192
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
193 194 195
        }
        self.outputs = {
            'Out': np.zeros((32, 64)).astype('float32'),
196
            'Mask': np.zeros((32, 64)).astype('uint8'),
P
phlrain 已提交
197 198 199 200 201 202
        }


class TestDropoutOp7(TestDropoutOp):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
203
        self.python_api = dropout_wapper
204 205
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
P
phlrain 已提交
206 207 208 209 210
        self.inputs = {'X': np.random.random((32, 64, 2)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.0,
            'fix_seed': True,
            'is_test': False,
211
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
212 213 214
        }
        self.outputs = {
            'Out': self.inputs['X'],
215
            'Mask': np.ones((32, 64, 2)).astype('uint8'),
P
phlrain 已提交
216
        }
217 218 219 220
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
P
phlrain 已提交
221 222


223
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
P
phlrain 已提交
224 225 226
class TestDropoutOp8(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
227
        self.python_api = dropout_wapper
228 229
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
P
phlrain 已提交
230 231 232 233 234
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.35,
            'fix_seed': True,
            'is_test': True,
235
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
236 237 238 239
        }
        self.outputs = {'Out': self.inputs['X']}

    def test_check_output(self):
240
        self.check_output(check_prim=True)
P
phlrain 已提交
241 242


243
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
P
phlrain 已提交
244 245 246
class TestDropoutOp9(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
247
        self.python_api = dropout_wapper
248 249
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
P
phlrain 已提交
250 251 252 253
        self.inputs = {'X': np.random.random((32, 64, 3)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.75,
            'is_test': True,
254
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
255 256 257 258
        }
        self.outputs = {'Out': self.inputs['X']}

    def test_check_output(self):
259
        self.check_output(check_prim=True)
260 261


M
mapingshuo 已提交
262 263 264
class TestDropoutOpWithSeed(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
265
        self.python_api = dropout_wapper
266 267
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
M
mapingshuo 已提交
268 269
        self.inputs = {
            "X": np.random.random((32, 64)).astype("float32"),
270
            "Seed": np.asarray([125], dtype="int32"),
271 272 273
        }
        self.attrs = {
            'dropout_prob': 0.0,
M
mapingshuo 已提交
274 275 276
        }
        self.outputs = {
            'Out': self.inputs['X'],
277
            'Mask': np.ones((32, 64)).astype('uint8'),
M
mapingshuo 已提交
278
        }
279 280 281 282
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
M
mapingshuo 已提交
283 284

    def test_check_output(self):
285
        self.check_output(check_prim=True)
M
mapingshuo 已提交
286 287

    def test_check_grad_normal(self):
288 289
        # Now in dy2st mode x_grad = [], so set check_prim=False
        self.check_grad(['X'], 'Out', max_relative_error=0.05, check_prim=False)
M
mapingshuo 已提交
290 291


292 293 294 295
@unittest.skipIf(
    not core.is_compiled_with_cuda() or not core.op_support_gpu("dropout"),
    "core is not compiled with CUDA or core is not support dropout",
)
296
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
K
Kexin Zhao 已提交
297
class TestFP16DropoutOp(OpTest):
K
Kexin Zhao 已提交
298 299
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
300
        self.python_api = dropout_wapper
301 302
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
K
Kexin Zhao 已提交
303 304 305 306
        self.init_test_case()

        x = np.random.random(self.input_size).astype("float16")
        out = x * (1.0 - self.prob)
K
Kexin Zhao 已提交
307
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
K
Kexin Zhao 已提交
308 309 310
        self.attrs = {
            'dropout_prob': self.prob,
            'fix_seed': self.fix_seed,
311
            'is_test': True,
K
Kexin Zhao 已提交
312
        }
313
        self.outputs = {'Out': out}
314 315 316 317
        # Because prim op compare res with dygraph
        # when p = 0 dropout api return x,in dygraph mode x_grad = out_grad,
        # but in static mode x_grad = []
        self.enable_check_static_comp = False
K
Kexin Zhao 已提交
318

K
Kexin Zhao 已提交
319 320 321 322 323
    def init_test_case(self):
        self.input_size = [32, 64]
        self.prob = 0.35
        self.fix_seed = True

K
Kexin Zhao 已提交
324
    def test_check_output(self):
325 326 327
        self.check_output_with_place(
            core.CUDAPlace(0), atol=1e-3, check_prim=True
        )
K
Kexin Zhao 已提交
328

329 330 331
    def test_check_grad_normal(self):
        self.check_grad(['X'], 'Out')

K
Kexin Zhao 已提交
332

333 334 335 336
@unittest.skipIf(
    not core.is_compiled_with_cuda() or not core.op_support_gpu("dropout"),
    "core is not compiled with CUDA or core is not support dropout",
)
337
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
K
Kexin Zhao 已提交
338 339 340 341 342
class TestFP16DropoutOp2(TestFP16DropoutOp):
    def init_test_case(self):
        self.input_size = [32, 64, 3]
        self.prob = 0.75
        self.fix_seed = False
K
Kexin Zhao 已提交
343 344


345 346 347
class TestBF16DropoutOp(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
348
        self.python_api = dropout_wapper
349 350
        self.public_python_api = prim_dropout_wrapper
        self.prim_op_type = "comp"
351
        self.dtype = np.uint16
352
        self.enable_cinn = False
353 354 355 356 357

        x = np.random.random((32, 64)).astype("float32")
        self.inputs = {'X': convert_float_to_uint16(x)}
        self.attrs = {'dropout_prob': 1.0, 'fix_seed': True, 'is_test': False}
        self.outputs = {
358 359 360 361
            'Out': convert_float_to_uint16(
                np.zeros((32, 64)).astype('float32')
            ),
            'Mask': np.zeros((32, 64)).astype('uint8'),
362 363 364 365 366 367 368 369
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
        self.check_grad(['X'], 'Out')

370 371 372 373 374 375 376 377 378 379 380 381
    def test_check_output_for_prim(self):
        # greater_equal does't support bfloat16 in cpu
        if core.is_compiled_with_cuda():
            self.check_output_with_place(core.CUDAPlace(0))

    def test_check_grad_for_prim(self):
        # greater_equal does't support bfloat16 in cpu
        if core.is_compiled_with_cuda():
            self.check_grad_with_place(
                core.CUDAPlace(0), ['X'], 'Out', only_check_prim=True
            )

382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
class TestDropoutOpWithSeedOnCPUPlace(unittest.TestCase):
    def test_seed_cpu_place(self):
        paddle.enable_static()
        main_program = Program()
        with program_guard(main_program):
            seed_input_name = "tensor@SeedInput"
            x_var_name = "tensor@X"
            x_out_var = "tensor@XOut"

            mask_var_name = "tensor@Mask"
            seed_input_var = main_program.global_block().create_var(
                name=seed_input_name,
                shape=[1],
                dtype='int32',
                persistable=False,
398 399
                stop_gradient=True,
            )
400 401 402 403 404
            x_out_var = main_program.global_block().create_var(
                name=x_out_var,
                shape=[40, 40],
                dtype='float32',
                persistable=False,
405 406 407 408 409 410 411 412 413
                stop_gradient=True,
            )
            x_var = main_program.global_block().create_var(
                name=x_var_name,
                shape=[40, 40],
                dtype='float32',
                persistable=False,
                stop_gradient=True,
            )
414 415 416 417 418
            mask_var = main_program.global_block().create_var(
                name=mask_var_name,
                shape=[1],
                dtype='int',
                persistable=False,
419 420 421 422 423 424 425 426 427 428 429 430 431
                stop_gradient=True,
            )

            main_program.global_block().append_op(
                type="fill_constant",
                outputs={"Out": x_var_name},
                attrs={
                    "shape": [40, 40],
                    "dtype": x_var.dtype,
                    "value": 1.0,
                    "place_type": 0,
                },
            )
432 433 434 435
            main_program.global_block().append_op(
                type='seed',
                inputs={},
                outputs={'Out': seed_input_var},
436 437 438 439 440 441 442 443
                attrs={'seed': 1, 'force_cpu': True},
            )
            main_program.global_block().append_op(
                type='dropout',
                inputs={'X': x_var, 'Seed': seed_input_var},
                attrs={'dropout_prob': 0.0},
                outputs={'Out': x_out_var, 'Mask': mask_var},
            )
444 445 446 447 448 449 450
            place = fluid.CPUPlace()
            if core.is_compiled_with_cuda():
                place = fluid.CUDAPlace(0)
            exe = fluid.Executor(place)
            x_out, mask_out = exe.run(
                main_program,
                feed={},
451 452
                fetch_list=[x_out_var.name, mask_var.name],
            )
453
            x_in_np = np.ones([40, 40]).astype("float32")
454
            np.testing.assert_allclose(x_out, x_in_np, rtol=1e-05)
455 456


457
class TestDropoutOpError(unittest.TestCase):
458 459
    def test_errors(self):
        with program_guard(Program(), Program()):
460
            paddle.enable_static()
461 462 463

            def test_Variable():
                # the input of dropout must be Variable.
464 465 466
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
C
ccrrong 已提交
467
                paddle.nn.functional.dropout(x1, p=0.5)
468 469 470 471 472 473

            self.assertRaises(TypeError, test_Variable)

            def test_dtype():
                # the input dtype of dropout must be float16 or float32 or float64
                # float16 only can be set on GPU place
G
GGBond8488 已提交
474 475
                x2 = paddle.static.data(
                    name='x2', shape=[-1, 3, 4, 5, 6], dtype="int32"
476
                )
C
ccrrong 已提交
477
                paddle.nn.functional.dropout(x2, p=0.5)
478 479 480 481

            self.assertRaises(TypeError, test_dtype)


482 483 484 485 486 487 488 489
class TestDropoutFAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
490
        paddle.enable_static()
491
        with fluid.program_guard(fluid.Program(), fluid.Program()):
492 493 494
            input = paddle.static.data(
                name="input", shape=[-1, -1], dtype="float32"
            )
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
            res1 = paddle.nn.functional.dropout(x=input, p=0.0, training=False)
            res2 = paddle.nn.functional.dropout(
                x=input, p=0.0, axis=0, training=True, mode='upscale_in_train'
            )
            res3 = paddle.nn.functional.dropout(
                x=input, p=0.0, axis=0, training=True, mode='downscale_in_infer'
            )
            res4 = paddle.nn.functional.dropout(
                x=input, p=0.0, axis=0, training=False, mode='upscale_in_train'
            )
            res5 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=0,
                training=False,
                mode='downscale_in_infer',
            )
            res6 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=[0, 1],
                training=True,
                mode='upscale_in_train',
            )
            res7 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=[0, 1],
                training=True,
                mode='downscale_in_infer',
            )
            res8 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=[0, 1],
                training=False,
                mode='upscale_in_train',
            )
            res9 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=[0, 1],
                training=False,
                mode='downscale_in_infer',
            )
            res10 = paddle.nn.functional.dropout(x=input, p=1.0, training=True)
C
ccrrong 已提交
541
            res11 = paddle.nn.functional.dropout(x=input, p=0.0)
542 543 544 545 546 547 548 549 550 551 552
            res12 = paddle.nn.functional.dropout(
                x=input,
                p=0.0,
                axis=(0, 1),
                training=False,
                mode='upscale_in_train',
            )

            res13 = paddle.nn.functional.dropout(
                x=input, p=0.7, axis=1, training=True, mode='upscale_in_train'
            )
553 554

            in_np = np.ones([40, 40]).astype("float32")
555 556 557 558
            res_np = in_np
            res_np2 = np.zeros_like(in_np)

            exe = fluid.Executor(place)
559
            res_list = [
560 561 562 563 564 565 566 567 568 569 570
                res1,
                res2,
                res3,
                res4,
                res5,
                res6,
                res7,
                res8,
                res9,
                res11,
                res12,
571
            ]
572
            for res in res_list:
573 574 575 576 577
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
578
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
579 580 581 582 583
            fetches2 = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res10],
            )
584
            np.testing.assert_allclose(fetches2[0], res_np2, rtol=1e-05)
585 586 587 588 589
            fetches3 = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res13],
            )
590 591 592 593 594 595 596 597 598 599 600 601 602

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                in_np = np.random.random([40, 40]).astype("float32")
                res_np = in_np
                res_np2 = np.zeros_like(in_np)
                input = fluid.dygraph.to_variable(in_np)

603 604 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 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                res1 = paddle.nn.functional.dropout(
                    x=input, p=0.0, training=False
                )
                res2 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=0,
                    training=True,
                    mode='upscale_in_train',
                )
                res3 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=0,
                    training=True,
                    mode='downscale_in_infer',
                )
                res4 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=0,
                    training=False,
                    mode='upscale_in_train',
                )
                res5 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=0,
                    training=False,
                    mode='downscale_in_infer',
                )
                res6 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=[0, 1],
                    training=True,
                    mode='upscale_in_train',
                )
                res7 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=[0, 1],
                    training=True,
                    mode='downscale_in_infer',
                )
                res8 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=[0, 1],
                    training=False,
                    mode='upscale_in_train',
                )
                res9 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=[0, 1],
                    training=False,
                    mode='downscale_in_infer',
                )
                res10 = paddle.nn.functional.dropout(
                    x=input, p=1.0, training=True
                )
W
wangzhen38 已提交
665
                dropout = paddle.nn.Dropout(
666 667
                    p=0,
                )
668
                res11 = dropout(input)
669 670 671 672 673 674 675 676 677 678 679 680 681 682
                res12 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.0,
                    axis=(0, 1),
                    training=False,
                    mode='upscale_in_train',
                )
                res13 = paddle.nn.functional.dropout(
                    x=input,
                    p=0.5,
                    axis=1,
                    training=True,
                    mode='upscale_in_train',
                )
683

684
            res_list = [
685 686 687 688 689 690 691 692 693 694 695
                res1,
                res2,
                res3,
                res4,
                res5,
                res6,
                res7,
                res8,
                res9,
                res11,
                res12,
696
            ]
697
            for res in res_list:
698 699
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
            np.testing.assert_allclose(res10.numpy(), res_np2, rtol=1e-05)
700 701 702 703


class TestDropoutFAPIError(unittest.TestCase):
    def test_errors(self):
704
        paddle.enable_static()
705 706 707 708
        with program_guard(Program(), Program()):

            def test_Variable():
                # the input of dropout must be Variable.
709 710 711
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
712 713 714 715 716 717
                paddle.nn.functional.dropout(x1, p=0.5)

            self.assertRaises(TypeError, test_Variable)

            def test_Variable2():
                # the input of dropout must be Variable.
718 719 720
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
721 722 723 724 725 726 727
                paddle.nn.functional.dropout(x1, p=0.5, axis=0)

            self.assertRaises(TypeError, test_Variable2)

            def test_dtype():
                # the input dtype of dropout must be float32 or float64
                # float16 only can be set on GPU place
728 729 730
                xr = paddle.static.data(
                    name='xr', shape=[3, 4, 5, 6], dtype="int32"
                )
731 732 733 734 735 736
                paddle.nn.functional.dropout(xr, p=0.5)

            self.assertRaises(TypeError, test_dtype)

            def test_pdtype():
                # p should be int or float
737 738 739
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
740 741 742 743 744 745
                paddle.nn.functional.dropout(x2, p='0.5')

            self.assertRaises(TypeError, test_pdtype)

            def test_pvalue():
                # p should be 0.<=p<=1.
746 747 748
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
749 750 751 752 753 754
                paddle.nn.functional.dropout(x2, p=1.2)

            self.assertRaises(ValueError, test_pvalue)

            def test_mode():
                # mode should be 'downscale_in_infer' or 'upscale_in_train'
755 756 757
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
758 759 760 761 762 763
                paddle.nn.functional.dropout(x2, mode='abc')

            self.assertRaises(ValueError, test_mode)

            def test_axis():
                # axis should be int or list
764 765 766
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
767 768 769 770 771 772
                paddle.nn.functional.dropout(x2, axis=1.2)

            self.assertRaises(TypeError, test_axis)

            def test_axis_max():
                # maximum of axis should less than dimensions of x
773 774 775
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
776 777 778 779
                paddle.nn.functional.dropout(x2, axis=[0, 5])

            self.assertRaises(ValueError, test_axis_max)

780 781
            def test_axis_min():
                # minimum of axis should greater equal than 0
782 783 784
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
785 786 787 788
                paddle.nn.functional.dropout(x2, axis=[0, -1])

            self.assertRaises(ValueError, test_axis_min)

789 790
            def test_axis_len():
                # length of axis should not greater than dimensions of x
791 792 793
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
                paddle.nn.functional.dropout(x2, axis=[0, 1, 2, 3, 4])

            self.assertRaises(ValueError, test_axis_len)


class TestDropoutCAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.random.random([40, 40]).astype("float32")
                result_np = input_np
                input = fluid.dygraph.to_variable(input_np)
812
                m = paddle.nn.Dropout(p=0.0)
813 814
                m.eval()
                result = m(input)
815 816 817
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
818 819


C
cnn 已提交
820
class TestDropout2DFAPI(unittest.TestCase):
821 822 823 824 825 826 827
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
828
        paddle.enable_static()
829
        with fluid.program_guard(fluid.Program(), fluid.Program()):
830
            input = paddle.static.data(
831 832 833 834 835 836 837 838
                name="input", shape=[2, 3, 4, 5], dtype="float32"
            )
            res1 = paddle.nn.functional.dropout2d(
                x=input, p=0.0, training=False, data_format='NCHW'
            )
            res2 = paddle.nn.functional.dropout2d(
                x=input, p=0.0, training=False, data_format='NHWC'
            )
839 840 841 842 843 844 845

            in_np = np.random.random([2, 3, 4, 5]).astype("float32")
            res_np = in_np

            exe = fluid.Executor(place)
            res_list = [res1, res2]
            for res in res_list:
846 847 848 849 850
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
851
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
852 853 854 855 856 857 858 859 860 861 862 863

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                in_np = np.random.random([2, 3, 4, 5]).astype("float32")
                res_np = in_np
                input = fluid.dygraph.to_variable(in_np)

864 865 866 867 868 869
                res1 = paddle.nn.functional.dropout2d(
                    x=input, p=0.0, training=False, data_format='NCHW'
                )
                res2 = paddle.nn.functional.dropout2d(
                    x=input, p=0.0, training=False, data_format='NHWC'
                )
870 871 872

            res_list = [res1, res2]
            for res in res_list:
873
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
874 875


C
cnn 已提交
876
class TestDropout2DFAPIError(unittest.TestCase):
877
    def test_errors(self):
878
        paddle.enable_static()
879 880 881 882
        with program_guard(Program(), Program()):

            def test_xdim():
                # dimentions of x should be 4
883 884 885
                x = paddle.static.data(
                    name='x1', shape=[2, 3, 4, 5, 6], dtype="int32"
                )
886 887 888 889 890 891
                paddle.nn.functional.dropout2d(x)

            self.assertRaises(ValueError, test_xdim)

            def test_dataformat():
                # data_format should be 'NCHW' or 'NHWC'
892 893 894
                x = paddle.static.data(
                    name='x2', shape=[2, 3, 4, 5], dtype="int32"
                )
895 896 897 898 899
                paddle.nn.functional.dropout2d(x, data_format='CNHW')

            self.assertRaises(ValueError, test_dataformat)


C
cnn 已提交
900
class TestDropout2DCAPI(unittest.TestCase):
901 902 903 904 905 906 907 908 909 910 911 912
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.random.random([2, 3, 4, 5]).astype("float32")
                result_np = input_np
                input = fluid.dygraph.to_variable(input_np)
913
                m = paddle.nn.Dropout2D(p=0.0)
914 915
                m.eval()
                result = m(input)
916 917 918
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
919

920 921 922
    def test_static_fp16_with_gpu(self):
        if paddle.fluid.core.is_compiled_with_cuda():
            place = paddle.CUDAPlace(0)
923
            paddle.enable_static()
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
            with paddle.static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                input = paddle.static.data(
                    name="input", shape=[2, 3, 4, 5], dtype="float16"
                )

                m = paddle.nn.Dropout2D(p=0.5)
                res1 = m(input)

                in_np = np.random.random([2, 3, 4, 5]).astype("float16")
                res_np = in_np

                exe = paddle.static.Executor(place)
                fetches = exe.run(
                    paddle.static.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res1],
                )

944

C
cnn 已提交
945
class TestDropout3DFAPI(unittest.TestCase):
946 947 948 949 950 951 952
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
953
        paddle.enable_static()
954
        with fluid.program_guard(fluid.Program(), fluid.Program()):
955
            input = paddle.static.data(
956 957 958 959 960 961 962 963
                name="input", shape=[2, 3, 4, 5, 6], dtype="float32"
            )
            res1 = paddle.nn.functional.dropout3d(
                x=input, p=0.0, training=False, data_format='NCDHW'
            )
            res2 = paddle.nn.functional.dropout3d(
                x=input, p=0.0, training=False, data_format='NDHWC'
            )
964 965 966 967 968 969 970

            in_np = np.random.random([2, 3, 4, 5, 6]).astype("float32")
            res_np = in_np

            exe = fluid.Executor(place)
            res_list = [res1, res2]
            for res in res_list:
971 972 973 974 975
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
976
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
977 978 979 980 981 982 983 984 985 986 987 988

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                in_np = np.random.random([2, 3, 4, 5, 6]).astype("float32")
                res_np = in_np
                input = fluid.dygraph.to_variable(in_np)

989 990 991 992 993 994
                res1 = paddle.nn.functional.dropout3d(
                    x=input, p=0.0, training=False, data_format='NCDHW'
                )
                res2 = paddle.nn.functional.dropout3d(
                    x=input, p=0.0, training=False, data_format='NDHWC'
                )
995 996 997

            res_list = [res1, res2]
            for res in res_list:
998
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
999 1000


C
cnn 已提交
1001
class TestDropout3DFAPIError(unittest.TestCase):
1002
    def test_errors(self):
1003
        paddle.enable_static()
1004 1005 1006 1007
        with program_guard(Program(), Program()):

            def test_xdim():
                # dimentions of x should be 5
1008 1009 1010
                x = paddle.static.data(
                    name='x1', shape=[2, 3, 4, 5], dtype="int32"
                )
1011 1012 1013 1014 1015 1016
                paddle.nn.functional.dropout3d(x)

            self.assertRaises(ValueError, test_xdim)

            def test_dataformat():
                # data_format should be 'NCDHW' or 'NDHWC'
1017 1018 1019
                x = paddle.static.data(
                    name='x2', shape=[2, 3, 4, 5, 6], dtype="int32"
                )
1020 1021 1022 1023 1024
                paddle.nn.functional.dropout3d(x, data_format='CNDHW')

            self.assertRaises(ValueError, test_dataformat)


C
cnn 已提交
1025
class TestDropout3DCAPI(unittest.TestCase):
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.random.random([2, 3, 4, 5, 6]).astype("float32")
                result_np = input_np
                input = fluid.dygraph.to_variable(input_np)
1038
                m = paddle.nn.Dropout3D(p=0.0)
1039 1040
                m.eval()
                result = m(input)
1041 1042 1043
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
1044 1045


1046 1047 1048 1049 1050 1051 1052 1053 1054
class TestAlphaDropoutFAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
1055 1056 1057
            input = paddle.static.data(
                name="input", shape=[40, 40], dtype="float32"
            )
1058 1059 1060 1061 1062
            res1 = paddle.nn.functional.alpha_dropout(x=input, p=0.0)
            res2 = paddle.nn.functional.alpha_dropout(
                x=input, p=0.0, training=False
            )
            res3 = paddle.nn.functional.alpha_dropout(x=input, p=1.0)
1063 1064 1065

            in_np = np.random.random([40, 40]).astype("float32")
            res_np = in_np
1066
            res_np3 = np.zeros_like(in_np)
1067 1068 1069 1070

            exe = fluid.Executor(place)
            res_list = [res1, res2]
            for res in res_list:
1071 1072 1073 1074 1075
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
1076
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
1077 1078 1079 1080 1081
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res3],
            )
1082
            np.testing.assert_allclose(fetches[0], res_np3, rtol=1e-05)
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                in_np = np.random.random([40, 40]).astype("float32")
                res_np = in_np
1093
                res_np3 = np.zeros_like(in_np)
1094 1095
                input = fluid.dygraph.to_variable(in_np)

1096 1097 1098 1099 1100
                res1 = paddle.nn.functional.alpha_dropout(x=input, p=0.0)
                res2 = paddle.nn.functional.alpha_dropout(
                    x=input, p=0.0, training=False
                )
                res3 = paddle.nn.functional.alpha_dropout(x=input, p=1.0)
1101 1102 1103

            res_list = [res1, res2]
            for res in res_list:
1104 1105
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
            np.testing.assert_allclose(res3.numpy(), res_np3, rtol=1e-05)
1106 1107 1108 1109 1110 1111 1112 1113


class TestAlphaDropoutFAPIError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):

            def test_Variable():
                # the input of dropout must be Variable.
1114 1115 1116
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
1117 1118 1119 1120 1121 1122
                paddle.nn.functional.alpha_dropout(x1, p=0.5)

            self.assertRaises(TypeError, test_Variable)

            def test_dtype():
                # the input dtype of dropout must be float32 or float64
1123 1124 1125
                xr = paddle.static.data(
                    name='xr', shape=[3, 4, 5, 6], dtype="int32"
                )
1126 1127 1128 1129 1130 1131
                paddle.nn.functional.alpha_dropout(xr)

            self.assertRaises(TypeError, test_dtype)

            def test_pdtype():
                # p should be int or float
1132 1133 1134
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
1135 1136 1137 1138 1139 1140
                paddle.nn.functional.alpha_dropout(x2, p='0.5')

            self.assertRaises(TypeError, test_pdtype)

            def test_pvalue():
                # p should be 0.<=p<=1.
1141 1142 1143
                x2 = paddle.static.data(
                    name='x2', shape=[3, 4, 5, 6], dtype="float32"
                )
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
                paddle.nn.functional.alpha_dropout(x2, p=1.2)

            self.assertRaises(ValueError, test_pvalue)


class TestAlphaDropoutCAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.random.random([40, 40]).astype("float32")
                result_np = input_np
                input = fluid.dygraph.to_variable(input_np)
1162
                m = paddle.nn.AlphaDropout(p=0.0)
1163 1164
                m.eval()
                result = m(input)
1165 1166 1167
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
1168

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    def test_static_fp16_gpu(self):
        if paddle.fluid.core.is_compiled_with_cuda():
            place = paddle.CUDAPlace(0)
            with paddle.static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                input = np.random.random([2, 3]).astype("float16")

                x = paddle.static.data(name="x", shape=[2, 3], dtype="float16")

                m = paddle.nn.AlphaDropout(p=0.0)
                y = m(x)

                exe = paddle.static.Executor(place)
                res = exe.run(
                    paddle.static.default_main_program(),
                    feed={
                        "x": input,
                    },
                    fetch_list=[y],
                )

                np.testing.assert_allclose(res[0], input, rtol=1e-05)

1193

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
class TestDropoutWithDeterminateSeedGenerator(unittest.TestCase):
    def setUp(self):
        paddle.framework.random.set_random_seed_generator('seed0', 123)
        paddle.framework.random.set_random_seed_generator('seed1', 123)
        rng0 = paddle.framework.random.get_random_seed_generator('seed0')
        rng1 = paddle.framework.random.get_random_seed_generator('seed1')
        self.places = [paddle.CPUPlace()]
        if paddle.is_compiled_with_cuda():
            self.places.append(paddle.CUDAPlace(0))

    def check_static_result(self, place):
1205 1206 1207 1208
        from paddle.distributed.fleet.meta_parallel.parallel_layers.random import (
            dropout,
        )

1209 1210
        with static.program_guard(static.Program(), static.Program()):
            input = static.data(name="input", shape=[40, 40], dtype="float32")
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
            res1 = dropout(
                input,
                p=0.3,
                training=True,
                mode='upscale_in_train',
                rng_name='seed0',
            )
            res2 = dropout(
                input,
                p=0.3,
                training=True,
                mode='upscale_in_train',
                rng_name='seed1',
            )
1225 1226 1227 1228 1229 1230 1231
            res3 = dropout(input, p=0.3)

            in_np = np.random.random([40, 40]).astype("float32")

            exe = static.Executor(place)
            res_list = [res1, res2]
            for i in range(2):
1232 1233 1234 1235 1236
                out1, out2 = exe.run(
                    static.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=res_list,
                )
1237
                np.testing.assert_allclose(out1, out2, rtol=1e-05)
1238 1239 1240 1241 1242 1243

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)


H
hong 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
class TestDropoutBackward(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def cal_grad_upscale_train(self, mask, prob):
        return mask.astype("float32") / (1 - prob)

    def cal_grad_downscale_in_infer(self, mask):
        return mask.astype("float32")

    def test_backward_downscale_in_infer(self):
        for place in self.places:
            with fluid.dygraph.guard(place):

                input = paddle.uniform([40, 40], dtype="float32")
                input.stop_gradient = False
W
Weilong Wu 已提交
1263 1264 1265
                out, mask = _C_ops.dropout(
                    input, None, 0.5, False, "downgrade_in_infer", 0, False
                )
H
hong 已提交
1266 1267
                out.backward()

1268 1269
                np.testing.assert_array_equal(
                    input.gradient(),
1270 1271
                    self.cal_grad_downscale_in_infer(mask.numpy()),
                )
H
hong 已提交
1272 1273 1274 1275 1276 1277 1278 1279

    def test_backward_upscale_train(self):
        for place in self.places:
            with fluid.dygraph.guard(place):

                prob = 0.5
                input = paddle.uniform([40, 40], dtype="float32")
                input.stop_gradient = False
W
Weilong Wu 已提交
1280 1281
                out, mask = _C_ops.dropout(
                    input, None, 0.5, False, "upscale_in_train", 0, False
1282
                )
H
hong 已提交
1283 1284
                out.backward()

1285 1286 1287 1288 1289
                np.testing.assert_allclose(
                    input.gradient(),
                    self.cal_grad_upscale_train(mask.numpy(), prob),
                    rtol=1e-05,
                )
H
hong 已提交
1290

H
hong 已提交
1291 1292 1293 1294 1295 1296 1297
    def test_backward_upscale_train_2(self):
        for place in self.places:
            with fluid.dygraph.guard(place):

                prob = 0.3
                input = paddle.uniform([40, 40], dtype="float32")
                input.stop_gradient = False
W
Weilong Wu 已提交
1298 1299
                out, mask = _C_ops.dropout(
                    input, None, 0.3, False, "upscale_in_train", 0, False
1300
                )
H
hong 已提交
1301 1302
                out.backward()

1303 1304 1305 1306 1307
                np.testing.assert_allclose(
                    input.gradient(),
                    self.cal_grad_upscale_train(mask.numpy(), prob),
                    rtol=1e-05,
                )
H
hong 已提交
1308 1309


1310 1311
class TestDropOutWithProbTensor(unittest.TestCase):
    def setUp(self):
1312 1313
        self.init_info()
        self.input = np.random.random(self.shape).astype("float32")
1314 1315 1316 1317 1318
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
1319

1320 1321 1322 1323
    def init_info(self):
        self.shape = [10, 10]
        self.api = paddle.nn.functional.dropout

1324 1325
    def api_case(self, x):
        p = paddle.assign([0.5])
1326
        out = self.api(x=x, p=p, training=True)
1327 1328 1329 1330 1331
        return out

    def run_static(self, x):
        paddle.seed(2022)
        main_program = Program()
1332
        paddle.enable_static()
1333 1334 1335
        with program_guard(main_program):
            input = paddle.static.data(shape=x.shape, name='x', dtype='float32')
            out = self.api_case(input)
1336 1337
            sgd = paddle.optimizer.SGD(learning_rate=0.1)
            sgd.minimize(paddle.mean(out))
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'x': x}, fetch_list=[out])

        return res[0]

    def run_dygraph(self, x):
        paddle.seed(2022)
        with fluid.dygraph.guard(self.place):
            out = self.api_case(paddle.to_tensor(x))
        return out

    def test_p_tensor(self):
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        static_res = self.run_static(self.input)
        dygraph_res = self.run_dygraph(self.input)
        np.testing.assert_array_equal(static_res, dygraph_res)


class TestDropOut2DWithProbTensor(TestDropOutWithProbTensor):
    def init_info(self):
        self.shape = [2, 3, 10, 10]
        self.api = paddle.nn.functional.dropout2d


class TestDropOut3DWithProbTensor(TestDropOutWithProbTensor):
    def init_info(self):
        self.shape = [2, 3, 8, 8, 8]
        self.api = paddle.nn.functional.dropout3d
1366 1367


1368 1369 1370 1371 1372 1373 1374
class TestRandomValue(unittest.TestCase):
    def test_fixed_random_number(self):
        # Test GPU Fixed random number, which is generated by 'curandStatePhilox4_32_10_t'
        if not paddle.is_compiled_with_cuda():
            return

        # Different GPU generate different random value. Only test V100 here.
1375
        if "V100" not in paddle.device.cuda.get_device_name():
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
            return

        print("Test Fixed Random number on V100 GPU------>")
        paddle.disable_static()
        paddle.set_device('gpu')
        paddle.seed(100)

        x = paddle.rand([32, 1024, 1024], dtype='float32')
        out = paddle.nn.functional.dropout(x, 0.25).numpy()
        index0, index1, index2 = np.nonzero(out)
        self.assertEqual(np.sum(index0), 390094540)
        self.assertEqual(np.sum(index1), 12871475125)
        self.assertEqual(np.sum(index2), 12872777397)
        self.assertEqual(np.sum(out), 16778744.0)
        expect = [
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
            0.6914956,
            0.5294584,
            0.19032137,
            0.6996228,
            0.3338527,
            0.8442094,
            0.96965003,
            1.1726775,
            0.0,
            0.28037727,
1401
        ]
1402
        np.testing.assert_allclose(out[10, 100, 500:510], expect, rtol=1e-05)
1403 1404 1405 1406 1407 1408 1409 1410 1411

        x = paddle.rand([32, 1024, 1024], dtype='float64')
        out = paddle.nn.functional.dropout(x).numpy()
        index0, index1, index2 = np.nonzero(out)
        self.assertEqual(np.sum(index0), 260065137)
        self.assertEqual(np.sum(index1), 8582636095)
        self.assertEqual(np.sum(index2), 8582219962)
        self.assertEqual(np.sum(out), 16778396.563660286)
        expect = [
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            1.28587354,
            0.15563703,
            0.0,
            0.28799703,
            0.0,
            0.0,
            0.0,
            0.54964,
            0.51355682,
            0.33818988,
1422
        ]
1423
        np.testing.assert_allclose(out[20, 100, 500:510], expect, rtol=1e-05)
1424 1425 1426 1427 1428 1429 1430

        x = paddle.ones([32, 1024, 1024], dtype='float16')
        out = paddle.nn.functional.dropout(x, 0.75).numpy()
        index0, index1, index2 = np.nonzero(out)
        self.assertEqual(np.sum(index0), 130086900)
        self.assertEqual(np.sum(index1), 4291190105)
        self.assertEqual(np.sum(index2), 4292243807)
1431
        expect = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 4.0]
1432
        np.testing.assert_allclose(out[0, 100, 500:510], expect, rtol=1e-05)
1433 1434 1435 1436

        paddle.enable_static()


1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
places = [paddle.CPUPlace()]
if paddle.is_compiled_with_cuda():
    places.append(paddle.CUDAPlace(0))


class PrimNet(paddle.nn.Layer):
    def __init__(self):
        super().__init__()

    def forward(
        self,
        x,
        p=0.5,
        axis=None,
        training=True,
        mode="upscale_in_train",
    ):
        out = paddle.nn.functional.dropout(
            x=x, p=p, axis=axis, training=training, mode=mode
        )
        return out


def apply_to_static(net, use_cinn):
    build_strategy = paddle.static.BuildStrategy()
    build_strategy.build_cinn_pass = use_cinn
    return paddle.jit.to_static(net, build_strategy=build_strategy)


@param.parameterized_class(
    ('name', 'x', 'p', 'is_test', 'mode', 'seed', 'dtype', 'places'),
    (
        (
            'fp32',
            np.random.rand(100000),
            0.3,
            False,
            'upscale_in_train',
            1002,
            'float32',
            places,
        ),
        (
            'fp64',
            np.random.rand(100000),
            0.7,
            False,
            'upscale_in_train',
            9999,
            'float64',
            places,
        ),
        (
            'is_test=True',
            np.random.rand(100000),
            0.5,
            True,
            'upscale_in_train',
            1002,
            'float32',
            places,
        ),
        (
            'p=1.0',
            np.random.rand(100000),
            1.0,
            True,
            'upscale_in_train',
            1002,
            'float32',
            places,
        ),
        (
            'p=1.0,test=False',
            np.random.rand(100000),
            1.0,
            False,
            'upscale_in_train',
            1002,
            'float32',
            places,
        ),
        (
            'p=0.0',
            np.random.rand(100000),
            1.0,
            True,
            'upscale_in_train',
            1002,
            'float32',
            places,
        ),
        (
            'downgrade_train',
            np.random.rand(100000),
            0.5,
            False,
            'downscale_in_infer',
            1002,
            'float32',
            places,
        ),
        (
            'fp32_cpu',
            np.random.rand(100000),
            0.6,
            False,
            'upscale_in_train',
            9899,
            'float64',
            [paddle.CPUPlace()],
        ),
        (
            'fp64_cpu',
            np.random.rand(100000),
            0.6,
            False,
            'upscale_in_train',
            9899,
            'float64',
            [paddle.CPUPlace()],
        ),
        (
            'downgrade_train_cpu',
            np.random.rand(100000),
            0.5,
            False,
            'downscale_in_infer',
            1002,
            'float32',
            [paddle.CPUPlace()],
        ),
    ),
)
class TestCompositeDropout(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.x = cls.x.astype(cls.dtype)
        core._set_prim_all_enabled(True)

    @classmethod
    def tearDownClass(cls):
        core._set_prim_all_enabled(False)

    def setUp(self):
        paddle.seed(self.seed)
        self.fwd_desire = []
        self.rev_desire = []
        for place in self.places:
            fwd_desire, rev_desire = self.get_eager_desire(place)
            self.fwd_desire.append(fwd_desire.numpy())
            self.rev_desire.append(rev_desire.numpy())

    def get_eager_desire(self, place):
        paddle.disable_static()
        paddle.seed(self.seed)
        if isinstance(place, fluid.CPUPlace):
            paddle.set_device("cpu")
        if isinstance(place, fluid.CUDAPlace):
            paddle.set_device("gpu")
        core.set_prim_eager_enabled(False)
        input_ = paddle.to_tensor(
            data=self.x, dtype=self.dtype, place=place, stop_gradient=False
        )
        output = paddle.nn.functional.dropout(
            input_, self.p, training=(not self.is_test), mode=self.mode
        )
        grad = paddle.grad(output, input_)
        return output, grad[0]

    def test_static_comp(self):
        fwd_actual = []
        rev_actual = []
        mps = []
        with paddle.fluid.framework._static_guard():
            for place in self.places:
                paddle.seed(self.seed)
                mp, sp = paddle.static.Program(), paddle.static.Program()
                with paddle.static.program_guard(mp, sp):
                    input_ = paddle.static.data(
                        'x', shape=self.x.shape, dtype=self.x.dtype
                    )
                    input_.stop_gradient = False
                    output = paddle.nn.functional.dropout(
                        input_,
                        self.p,
                        training=(not self.is_test),
                        mode=self.mode,
                    )
                    if core._is_fwd_prim_enabled():
                        primapi.to_prim(mp.blocks)
                    grad = paddle.static.gradients(output, input_)[0]
                exe = paddle.static.Executor(place)
                exe.run(sp)
                fwd, rev = exe.run(
                    mp, feed={input_.name: self.x}, fetch_list=[output, grad]
                )
                fwd_actual.append(fwd)
                rev_actual.append(rev)
                mps.append(mp)
        for i in range(len(self.places)):
            self.assertTrue(
                'dropout' not in [op.type for op in mps[i].block(0).ops]
            )
            np.testing.assert_allclose(
                self.fwd_desire[i].sum(),
                fwd_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )
            np.testing.assert_allclose(
                self.rev_desire[i].sum(),
                rev_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )

    def test_jit_comp(self):
        fwd_actual = []
        rev_actual = []
        paddle.disable_static()
        for place in self.places:
            if isinstance(place, fluid.CPUPlace):
                paddle.set_device("cpu")
            if isinstance(place, fluid.CUDAPlace):
                paddle.set_device("gpu")
            paddle.seed(self.seed)
            input_ = paddle.to_tensor(
                data=self.x, dtype=self.dtype, place=place, stop_gradient=False
            )
            net = PrimNet()
            net = apply_to_static(net, False)
            output = net(
                input_, self.p, training=(not self.is_test), mode=self.mode
            )
            grad = paddle.grad(output, input_)
            fwd_actual.append(output.numpy())
            rev_actual.append(grad[0].numpy())
        for i in range(len(self.places)):
            np.testing.assert_allclose(
                self.fwd_desire[i].sum(),
                fwd_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )
            np.testing.assert_allclose(
                self.rev_desire[i].sum(),
                rev_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )

    def test_jit_comp_with_cinn(self):
        fwd_actual = []
        rev_actual = []
        paddle.disable_static()
        for place in self.places:
1694 1695 1696
            if not isinstance(place, fluid.CUDAPlace):
                continue
            paddle.set_device("gpu")
1697 1698 1699 1700 1701
            paddle.seed(self.seed)
            input_ = paddle.to_tensor(
                data=self.x, dtype=self.dtype, place=place, stop_gradient=False
            )
            net = PrimNet()
1702
            net = apply_to_static(net, True)
1703 1704 1705 1706 1707 1708
            output = net(
                input_, self.p, training=(not self.is_test), mode=self.mode
            )
            grad = paddle.grad(output, input_)
            fwd_actual.append(output.numpy())
            rev_actual.append(grad[0].numpy())
1709 1710 1711 1712
        i = 0
        for place in self.places:
            if not isinstance(self.places[i], fluid.CUDAPlace):
                continue
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
            np.testing.assert_allclose(
                self.fwd_desire[i].sum(),
                fwd_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )
            np.testing.assert_allclose(
                self.rev_desire[i].sum(),
                rev_actual[i].sum(),
                rtol=1e-2,  # mean of uniform distribution, scale for avoid random failed
                atol=0,
            )
1725
            i += 1
1726 1727


1728
if __name__ == '__main__':
H
hong 已提交
1729
    paddle.enable_static()
1730
    unittest.main()