test_seed_op.py 2.5 KB
Newer Older
M
mapingshuo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
16

M
mapingshuo 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest
19

20
import paddle
21
from paddle import static
22 23

paddle.enable_static()
M
mapingshuo 已提交
24 25 26 27 28 29 30


class TestSeedOpFixSeed(OpTest):
    def setUp(self):
        self.op_type = "seed"
        self.inputs = {}
        self.attrs = {"seed": 123}
31
        self.outputs = {"Out": np.array([123]).astype('int')}
M
mapingshuo 已提交
32 33 34 35 36 37 38 39 40 41

    def test_check_output(self):
        self.check_output()


class TestSeedOpDiffSeed(OpTest):
    def setUp(self):
        self.op_type = "seed"
        self.inputs = {}
        self.attrs = {"seed": 0}
42
        self.outputs = {"Out": np.array([123]).astype('int')}
M
mapingshuo 已提交
43 44 45 46 47

    def test_check_output(self):
        self.check_output(no_check_set=["Out"])


48 49 50 51 52 53 54 55 56 57 58
class TestDropoutWithRandomSeedGenerator(unittest.TestCase):
    def setUp(self):
        paddle.framework.random.set_random_seed_generator('seed0', 123)
        paddle.framework.random.set_random_seed_generator('seed1', 123)
        self.rng0 = paddle.framework.random.get_random_seed_generator('seed0')
        self.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):
59 60 61
        from paddle.distributed.fleet.meta_parallel.parallel_layers import (
            random,
        )
62

63 64 65 66 67 68
        with static.program_guard(static.Program(), static.Program()):
            res1 = random.determinate_seed('seed0')

            exe = static.Executor(place)
            res_list = [res1]
            for i in range(2):
69 70 71
                (out1,) = exe.run(
                    static.default_main_program(), fetch_list=res_list
                )
72 73 74 75 76 77 78
                self.assertEqual(out1, np.cast['int32'](self.rng1.random()))

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


M
mapingshuo 已提交
79 80
if __name__ == '__main__':
    unittest.main()