test_dropout_op.py 44.0 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
W
wanghuancoder 已提交
18
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
19

20
import paddle
21
import paddle.fluid as fluid
22 23
import paddle.fluid.core as core
import paddle.static as static
24
from paddle import _C_ops
25
from paddle.fluid import Program, program_guard
H
hong 已提交
26

27

W
wanghuancoder 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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,
    )


48
class TestDropoutOp(OpTest):
49
    def setUp(self):
50
        self.op_type = "dropout"
W
wanghuancoder 已提交
51
        self.python_api = dropout_wapper
52
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
53
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
54 55
        self.outputs = {
            'Out': self.inputs['X'],
56
            'Mask': np.ones((32, 64)).astype('uint8'),
Y
Yu Yang 已提交
57
        }
58

59 60 61 62
    def test_check_output(self):
        self.check_output()

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


66 67 68
class TestDropoutOpInput1d(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
69
        self.python_api = dropout_wapper
70
        self.inputs = {'X': np.random.random((2000,)).astype("float32")}
71 72 73
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
        self.outputs = {
            'Out': self.inputs['X'],
74
            'Mask': np.ones((2000)).astype('uint8'),
75 76 77 78 79 80 81 82 83
        }

    def test_check_output(self):
        self.check_output()

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


84
class TestDropoutOp2(TestDropoutOp):
85
    def setUp(self):
86
        self.op_type = "dropout"
W
wanghuancoder 已提交
87
        self.python_api = dropout_wapper
88
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
89
        self.attrs = {'dropout_prob': 1.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
90 91
        self.outputs = {
            'Out': np.zeros((32, 64)).astype('float32'),
92
            'Mask': np.zeros((32, 64)).astype('uint8'),
Y
Yu Yang 已提交
93
        }
94 95


96
class TestDropoutOp3(TestDropoutOp):
97
    def setUp(self):
98
        self.op_type = "dropout"
W
wanghuancoder 已提交
99
        self.python_api = dropout_wapper
100
        self.inputs = {'X': np.random.random((32, 64, 2)).astype("float32")}
101
        self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}
Y
Yu Yang 已提交
102 103
        self.outputs = {
            'Out': self.inputs['X'],
104
            'Mask': np.ones((32, 64, 2)).astype('uint8'),
Y
Yu Yang 已提交
105
        }
106 107


108
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
109 110 111
class TestDropoutOp4(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
112
        self.python_api = dropout_wapper
113
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
114
        self.attrs = {'dropout_prob': 0.35, 'fix_seed': True, 'is_test': True}
115 116 117
        self.outputs = {
            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])
        }
118 119 120 121 122

    def test_check_output(self):
        self.check_output()


123
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
124 125 126
class TestDropoutOp5(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
127
        self.python_api = dropout_wapper
128
        self.inputs = {'X': np.random.random((32, 64, 3)).astype("float32")}
129
        self.attrs = {'dropout_prob': 0.75, 'is_test': True}
130 131 132
        self.outputs = {
            'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])
        }
133 134

    def test_check_output(self):
P
phlrain 已提交
135 136 137 138 139 140
        self.check_output()


class TestDropoutOp6(TestDropoutOp):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
141
        self.python_api = dropout_wapper
P
phlrain 已提交
142 143 144 145 146
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
        self.attrs = {
            'dropout_prob': 1.0,
            'fix_seed': True,
            'is_test': False,
147
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
148 149 150
        }
        self.outputs = {
            'Out': np.zeros((32, 64)).astype('float32'),
151
            'Mask': np.zeros((32, 64)).astype('uint8'),
P
phlrain 已提交
152 153 154 155 156 157
        }


class TestDropoutOp7(TestDropoutOp):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
158
        self.python_api = dropout_wapper
P
phlrain 已提交
159 160 161 162 163
        self.inputs = {'X': np.random.random((32, 64, 2)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.0,
            'fix_seed': True,
            'is_test': False,
164
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
165 166 167
        }
        self.outputs = {
            'Out': self.inputs['X'],
168
            'Mask': np.ones((32, 64, 2)).astype('uint8'),
P
phlrain 已提交
169 170 171
        }


172
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
P
phlrain 已提交
173 174 175
class TestDropoutOp8(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
176
        self.python_api = dropout_wapper
P
phlrain 已提交
177 178 179 180 181
        self.inputs = {'X': np.random.random((32, 64)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.35,
            'fix_seed': True,
            'is_test': True,
182
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
183 184 185 186 187 188 189
        }
        self.outputs = {'Out': self.inputs['X']}

    def test_check_output(self):
        self.check_output()


190
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
P
phlrain 已提交
191 192 193
class TestDropoutOp9(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
194
        self.python_api = dropout_wapper
P
phlrain 已提交
195 196 197 198
        self.inputs = {'X': np.random.random((32, 64, 3)).astype("float32")}
        self.attrs = {
            'dropout_prob': 0.75,
            'is_test': True,
199
            'dropout_implementation': 'upscale_in_train',
P
phlrain 已提交
200 201 202 203
        }
        self.outputs = {'Out': self.inputs['X']}

    def test_check_output(self):
204 205 206
        self.check_output()


M
mapingshuo 已提交
207 208 209
class TestDropoutOpWithSeed(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
210
        self.python_api = dropout_wapper
M
mapingshuo 已提交
211 212
        self.inputs = {
            "X": np.random.random((32, 64)).astype("float32"),
213
            "Seed": np.asarray([125], dtype="int32"),
214 215 216
        }
        self.attrs = {
            'dropout_prob': 0.0,
M
mapingshuo 已提交
217 218 219
        }
        self.outputs = {
            'Out': self.inputs['X'],
220
            'Mask': np.ones((32, 64)).astype('uint8'),
M
mapingshuo 已提交
221 222 223 224 225 226 227 228 229
        }

    def test_check_output(self):
        self.check_output()

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


230 231 232 233
@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",
)
234
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
K
Kexin Zhao 已提交
235
class TestFP16DropoutOp(OpTest):
K
Kexin Zhao 已提交
236 237
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
238
        self.python_api = dropout_wapper
K
Kexin Zhao 已提交
239 240 241 242
        self.init_test_case()

        x = np.random.random(self.input_size).astype("float16")
        out = x * (1.0 - self.prob)
K
Kexin Zhao 已提交
243
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
K
Kexin Zhao 已提交
244 245 246
        self.attrs = {
            'dropout_prob': self.prob,
            'fix_seed': self.fix_seed,
247
            'is_test': True,
K
Kexin Zhao 已提交
248
        }
249
        self.outputs = {'Out': out}
K
Kexin Zhao 已提交
250

K
Kexin Zhao 已提交
251 252 253 254 255
    def init_test_case(self):
        self.input_size = [32, 64]
        self.prob = 0.35
        self.fix_seed = True

K
Kexin Zhao 已提交
256
    def test_check_output(self):
257
        self.check_output_with_place(core.CUDAPlace(0), atol=1e-3)
K
Kexin Zhao 已提交
258 259


260 261 262 263
@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",
)
264
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
K
Kexin Zhao 已提交
265 266 267 268 269
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 已提交
270 271


272 273 274
class TestBF16DropoutOp(OpTest):
    def setUp(self):
        self.op_type = "dropout"
W
wanghuancoder 已提交
275
        self.python_api = dropout_wapper
276 277 278 279 280 281
        self.dtype = np.uint16

        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 = {
282 283 284 285
            'Out': convert_float_to_uint16(
                np.zeros((32, 64)).astype('float32')
            ),
            'Mask': np.zeros((32, 64)).astype('uint8'),
286 287 288 289 290 291 292 293 294
        }

    def test_check_output(self):
        self.check_output()

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


295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
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,
310 311
                stop_gradient=True,
            )
312 313 314 315 316
            x_out_var = main_program.global_block().create_var(
                name=x_out_var,
                shape=[40, 40],
                dtype='float32',
                persistable=False,
317 318 319 320 321 322 323 324 325
                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,
            )
326 327 328 329 330
            mask_var = main_program.global_block().create_var(
                name=mask_var_name,
                shape=[1],
                dtype='int',
                persistable=False,
331 332 333 334 335 336 337 338 339 340 341 342 343
                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,
                },
            )
344 345 346 347
            main_program.global_block().append_op(
                type='seed',
                inputs={},
                outputs={'Out': seed_input_var},
348 349 350 351 352 353 354 355
                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},
            )
356 357 358 359 360 361 362
            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={},
363 364
                fetch_list=[x_out_var.name, mask_var.name],
            )
365
            x_in_np = np.ones([40, 40]).astype("float32")
366
            np.testing.assert_allclose(x_out, x_in_np, rtol=1e-05)
367 368


369
class TestDropoutOpError(unittest.TestCase):
370 371 372 373 374
    def test_errors(self):
        with program_guard(Program(), Program()):

            def test_Variable():
                # the input of dropout must be Variable.
375 376 377
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
C
ccrrong 已提交
378
                paddle.nn.functional.dropout(x1, p=0.5)
379 380 381 382 383 384

            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 已提交
385 386
                x2 = paddle.static.data(
                    name='x2', shape=[-1, 3, 4, 5, 6], dtype="int32"
387
                )
C
ccrrong 已提交
388
                paddle.nn.functional.dropout(x2, p=0.5)
389 390 391 392

            self.assertRaises(TypeError, test_dtype)


393 394 395 396 397 398 399 400 401
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):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
402
            input = fluid.data(name="input", shape=[-1, -1], dtype="float32")
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
            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 已提交
449
            res11 = paddle.nn.functional.dropout(x=input, p=0.0)
450 451 452 453 454 455 456 457 458 459 460
            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'
            )
461 462

            in_np = np.ones([40, 40]).astype("float32")
463 464 465 466
            res_np = in_np
            res_np2 = np.zeros_like(in_np)

            exe = fluid.Executor(place)
467
            res_list = [
468 469 470 471 472 473 474 475 476 477 478
                res1,
                res2,
                res3,
                res4,
                res5,
                res6,
                res7,
                res8,
                res9,
                res11,
                res12,
479
            ]
480
            for res in res_list:
481 482 483 484 485
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
486
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
487 488 489 490 491
            fetches2 = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res10],
            )
492
            np.testing.assert_allclose(fetches2[0], res_np2, rtol=1e-05)
493 494 495 496 497
            fetches3 = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res13],
            )
498 499 500 501 502 503 504 505 506 507 508 509 510

    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)

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
                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 已提交
573
                dropout = paddle.nn.Dropout(
574 575
                    p=0,
                )
576
                res11 = dropout(input)
577 578 579 580 581 582 583 584 585 586 587 588 589 590
                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',
                )
591

592
            res_list = [
593 594 595 596 597 598 599 600 601 602 603
                res1,
                res2,
                res3,
                res4,
                res5,
                res6,
                res7,
                res8,
                res9,
                res11,
                res12,
604
            ]
605
            for res in res_list:
606 607
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
            np.testing.assert_allclose(res10.numpy(), res_np2, rtol=1e-05)
608 609 610 611 612 613 614 615


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

            def test_Variable():
                # the input of dropout must be Variable.
616 617 618
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
619 620 621 622 623 624
                paddle.nn.functional.dropout(x1, p=0.5)

            self.assertRaises(TypeError, test_Variable)

            def test_Variable2():
                # the input of dropout must be Variable.
625 626 627
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
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 665 666 667 668 669 670 671 672 673 674
                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
                xr = fluid.data(name='xr', shape=[3, 4, 5, 6], dtype="int32")
                paddle.nn.functional.dropout(xr, p=0.5)

            self.assertRaises(TypeError, test_dtype)

            def test_pdtype():
                # p should be int or float
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                paddle.nn.functional.dropout(x2, p='0.5')

            self.assertRaises(TypeError, test_pdtype)

            def test_pvalue():
                # p should be 0.<=p<=1.
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                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'
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                paddle.nn.functional.dropout(x2, mode='abc')

            self.assertRaises(ValueError, test_mode)

            def test_axis():
                # axis should be int or list
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                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
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                paddle.nn.functional.dropout(x2, axis=[0, 5])

            self.assertRaises(ValueError, test_axis_max)

675 676 677 678 679 680 681
            def test_axis_min():
                # minimum of axis should greater equal than 0
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                paddle.nn.functional.dropout(x2, axis=[0, -1])

            self.assertRaises(ValueError, test_axis_min)

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
            def test_axis_len():
                # length of axis should not greater than dimensions of x
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                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)
703
                m = paddle.nn.Dropout(p=0.0)
704 705
                m.eval()
                result = m(input)
706 707 708
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
709 710


C
cnn 已提交
711
class TestDropout2DFAPI(unittest.TestCase):
712 713 714 715 716 717 718 719
    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()):
720 721 722 723 724 725 726 727 728
            input = fluid.data(
                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'
            )
729 730 731 732 733 734 735

            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:
736 737 738 739 740
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
741
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
742 743 744 745 746 747 748 749 750 751 752 753

    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)

754 755 756 757 758 759
                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'
                )
760 761 762

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


C
cnn 已提交
766
class TestDropout2DFAPIError(unittest.TestCase):
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    def test_errors(self):
        with program_guard(Program(), Program()):

            def test_xdim():
                # dimentions of x should be 4
                x = fluid.data(name='x1', shape=[2, 3, 4, 5, 6], dtype="int32")
                paddle.nn.functional.dropout2d(x)

            self.assertRaises(ValueError, test_xdim)

            def test_dataformat():
                # data_format should be 'NCHW' or 'NHWC'
                x = fluid.data(name='x2', shape=[2, 3, 4, 5], dtype="int32")
                paddle.nn.functional.dropout2d(x, data_format='CNHW')

            self.assertRaises(ValueError, test_dataformat)


C
cnn 已提交
785
class TestDropout2DCAPI(unittest.TestCase):
786 787 788 789 790 791 792 793 794 795 796 797
    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)
798
                m = paddle.nn.Dropout2D(p=0.0)
799 800
                m.eval()
                result = m(input)
801 802 803
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
804

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    def test_static_fp16_with_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 = 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],
                )

828

C
cnn 已提交
829
class TestDropout3DFAPI(unittest.TestCase):
830 831 832 833 834 835 836 837
    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()):
838 839 840 841 842 843 844 845 846
            input = fluid.data(
                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'
            )
847 848 849 850 851 852 853

            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:
854 855 856 857 858
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
859
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
860 861 862 863 864 865 866 867 868 869 870 871

    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)

872 873 874 875 876 877
                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'
                )
878 879 880

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


C
cnn 已提交
884
class TestDropout3DFAPIError(unittest.TestCase):
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    def test_errors(self):
        with program_guard(Program(), Program()):

            def test_xdim():
                # dimentions of x should be 5
                x = fluid.data(name='x1', shape=[2, 3, 4, 5], dtype="int32")
                paddle.nn.functional.dropout3d(x)

            self.assertRaises(ValueError, test_xdim)

            def test_dataformat():
                # data_format should be 'NCDHW' or 'NDHWC'
                x = fluid.data(name='x2', shape=[2, 3, 4, 5, 6], dtype="int32")
                paddle.nn.functional.dropout3d(x, data_format='CNDHW')

            self.assertRaises(ValueError, test_dataformat)


C
cnn 已提交
903
class TestDropout3DCAPI(unittest.TestCase):
904 905 906 907 908 909 910 911 912 913 914 915
    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)
916
                m = paddle.nn.Dropout3D(p=0.0)
917 918
                m.eval()
                result = m(input)
919 920 921
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
922 923


924 925 926 927 928 929 930 931 932 933
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()):
            input = fluid.data(name="input", shape=[40, 40], dtype="float32")
934 935 936 937 938
            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)
939 940 941

            in_np = np.random.random([40, 40]).astype("float32")
            res_np = in_np
942
            res_np3 = np.zeros_like(in_np)
943 944 945 946

            exe = fluid.Executor(place)
            res_list = [res1, res2]
            for res in res_list:
947 948 949 950 951
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=[res],
                )
952
                np.testing.assert_allclose(fetches[0], res_np, rtol=1e-05)
953 954 955 956 957
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": in_np},
                fetch_list=[res3],
            )
958
            np.testing.assert_allclose(fetches[0], res_np3, rtol=1e-05)
959 960 961 962 963 964 965 966 967 968

    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
969
                res_np3 = np.zeros_like(in_np)
970 971
                input = fluid.dygraph.to_variable(in_np)

972 973 974 975 976
                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)
977 978 979

            res_list = [res1, res2]
            for res in res_list:
980 981
                np.testing.assert_allclose(res.numpy(), res_np, rtol=1e-05)
            np.testing.assert_allclose(res3.numpy(), res_np3, rtol=1e-05)
982 983 984 985 986 987 988 989


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

            def test_Variable():
                # the input of dropout must be Variable.
990 991 992
                x1 = fluid.create_lod_tensor(
                    np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
                )
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                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
                xr = fluid.data(name='xr', shape=[3, 4, 5, 6], dtype="int32")
                paddle.nn.functional.alpha_dropout(xr)

            self.assertRaises(TypeError, test_dtype)

            def test_pdtype():
                # p should be int or float
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                paddle.nn.functional.alpha_dropout(x2, p='0.5')

            self.assertRaises(TypeError, test_pdtype)

            def test_pvalue():
                # p should be 0.<=p<=1.
                x2 = fluid.data(name='x2', shape=[3, 4, 5, 6], dtype="float32")
                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)
1032
                m = paddle.nn.AlphaDropout(p=0.0)
1033 1034
                m.eval()
                result = m(input)
1035 1036 1037
                np.testing.assert_allclose(
                    result.numpy(), result_np, rtol=1e-05
                )
1038

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    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)

1063

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
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):
1075 1076 1077 1078
        from paddle.distributed.fleet.meta_parallel.parallel_layers.random import (
            dropout,
        )

1079 1080
        with static.program_guard(static.Program(), static.Program()):
            input = static.data(name="input", shape=[40, 40], dtype="float32")
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
            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',
            )
1095 1096 1097 1098 1099 1100 1101
            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):
1102 1103 1104 1105 1106
                out1, out2 = exe.run(
                    static.default_main_program(),
                    feed={"input": in_np},
                    fetch_list=res_list,
                )
1107
                np.testing.assert_allclose(out1, out2, rtol=1e-05)
1108 1109 1110 1111 1112 1113

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


H
hong 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
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 已提交
1133 1134 1135
                out, mask = _C_ops.dropout(
                    input, None, 0.5, False, "downgrade_in_infer", 0, False
                )
H
hong 已提交
1136 1137
                out.backward()

1138 1139
                np.testing.assert_array_equal(
                    input.gradient(),
1140 1141
                    self.cal_grad_downscale_in_infer(mask.numpy()),
                )
H
hong 已提交
1142 1143 1144 1145 1146 1147 1148 1149

    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 已提交
1150 1151
                out, mask = _C_ops.dropout(
                    input, None, 0.5, False, "upscale_in_train", 0, False
1152
                )
H
hong 已提交
1153 1154
                out.backward()

1155 1156 1157 1158 1159
                np.testing.assert_allclose(
                    input.gradient(),
                    self.cal_grad_upscale_train(mask.numpy(), prob),
                    rtol=1e-05,
                )
H
hong 已提交
1160

H
hong 已提交
1161 1162 1163 1164 1165 1166 1167
    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 已提交
1168 1169
                out, mask = _C_ops.dropout(
                    input, None, 0.3, False, "upscale_in_train", 0, False
1170
                )
H
hong 已提交
1171 1172
                out.backward()

1173 1174 1175 1176 1177
                np.testing.assert_allclose(
                    input.gradient(),
                    self.cal_grad_upscale_train(mask.numpy(), prob),
                    rtol=1e-05,
                )
H
hong 已提交
1178 1179


1180 1181
class TestDropOutWithProbTensor(unittest.TestCase):
    def setUp(self):
1182 1183
        self.init_info()
        self.input = np.random.random(self.shape).astype("float32")
1184 1185 1186 1187 1188
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
1189

1190 1191 1192 1193
    def init_info(self):
        self.shape = [10, 10]
        self.api = paddle.nn.functional.dropout

1194 1195
    def api_case(self, x):
        p = paddle.assign([0.5])
1196
        out = self.api(x=x, p=p, training=True)
1197 1198 1199 1200 1201 1202 1203 1204 1205
        return out

    def run_static(self, x):
        paddle.seed(2022)
        main_program = Program()

        with program_guard(main_program):
            input = paddle.static.data(shape=x.shape, name='x', dtype='float32')
            out = self.api_case(input)
1206 1207
            sgd = paddle.optimizer.SGD(learning_rate=0.1)
            sgd.minimize(paddle.mean(out))
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

            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):
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
        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
1236 1237


1238 1239 1240 1241 1242 1243 1244
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.
1245
        if "V100" not in paddle.device.cuda.get_device_name():
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
            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 = [
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
            0.6914956,
            0.5294584,
            0.19032137,
            0.6996228,
            0.3338527,
            0.8442094,
            0.96965003,
            1.1726775,
            0.0,
            0.28037727,
1271
        ]
1272
        np.testing.assert_allclose(out[10, 100, 500:510], expect, rtol=1e-05)
1273 1274 1275 1276 1277 1278 1279 1280 1281

        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 = [
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
            1.28587354,
            0.15563703,
            0.0,
            0.28799703,
            0.0,
            0.0,
            0.0,
            0.54964,
            0.51355682,
            0.33818988,
1292
        ]
1293
        np.testing.assert_allclose(out[20, 100, 500:510], expect, rtol=1e-05)
1294 1295 1296 1297 1298 1299 1300

        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)
1301
        expect = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 4.0]
1302
        np.testing.assert_allclose(out[0, 100, 500:510], expect, rtol=1e-05)
1303 1304 1305 1306

        paddle.enable_static()


1307
if __name__ == '__main__':
H
hong 已提交
1308
    paddle.enable_static()
1309
    unittest.main()