test_standalone_controlflow.py 5.2 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15
# 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 17 18

import numpy as np

19
import paddle
20
from paddle.fluid import core
21 22 23 24 25 26 27
from paddle.fluid.framework import Program, program_guard

paddle.enable_static()


#  test the compatibility of new executor: run old
#  and new executor twice and check the result.
28
#  please override the _get_feeds() and build_prgram(), run_dygraph_once()
29 30
class TestCompatibility(unittest.TestCase):
    def setUp(self):
31 32 33 34 35
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
36 37 38
        self.iter_run = 4

    def _get_feed(self):
39
        """return the feeds"""
40 41 42 43
        return None

    def build_program(self):
        def true_func():
44
            return paddle.tensor.fill_constant(
45
                shape=[1, 2], dtype='int32', value=1
46 47 48
            ), paddle.tensor.fill_constant(
                shape=[2, 3], dtype='bool', value=True
            )
49 50

        def false_func():
51
            return paddle.tensor.fill_constant(
52
                shape=[3, 4], dtype='float32', value=3
53
            ), paddle.tensor.fill_constant(shape=[4, 5], dtype='int64', value=2)
54 55 56 57

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
58 59 60 61 62 63
            x = paddle.tensor.fill_constant(
                shape=[1], dtype='float32', value=0.1
            )
            y = paddle.tensor.fill_constant(
                shape=[1], dtype='float32', value=0.23
            )
L
LiYuRio 已提交
64
            pred = paddle.less_than(x, y)
65
            out = paddle.static.nn.cond(pred, true_func, false_func)
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
            # out is a tuple containing 2 tensors
            return main_program, startup_program, out

    def _run(self, feed):
        paddle.seed(2020)

        main_program, startup_program, fetch_vars = self.build_program()

        exe = paddle.static.Executor(self.place)
        exe.run(startup_program)
        ret = []
        for i in range(self.iter_run):
            ret.append(exe.run(main_program, feed=feed, fetch_list=fetch_vars))
        return ret

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    def run_dygraph_once(self, feed):
        x = paddle.tensor.fill_constant(shape=[1], dtype='float32', value=0.1)
        y = paddle.tensor.fill_constant(shape=[1], dtype='float32', value=0.23)
        if x < y:
            out = [
                paddle.tensor.fill_constant(
                    shape=[1, 2], dtype='int32', value=1
                ).numpy(),
                paddle.tensor.fill_constant(
                    shape=[2, 3], dtype='bool', value=True
                ).numpy(),
            ]
        else:
            out = [
                paddle.tensor.fill_constant(
                    shape=[3, 4], dtype='float32', value=3
                ).numpy(),
                paddle.tensor.fill_constant(
                    shape=[4, 5], dtype='int64', value=2
                ).numpy(),
            ]
102 103
        return out

104 105 106 107 108 109
    def run_dygraph(self, feed):
        ret = []
        for _ in range(self.iter_run):
            ret.append(self.run_dygraph_once(feed))
        return ret

110
    def run_new_executor(self, feed):
111
        out = self._run(feed)
112 113 114 115
        return out

    def test_with_feed(self):
        feed = self._get_feed()
116
        paddle.enable_static()
117
        res = self.run_new_executor(feed)
118 119 120 121
        paddle.disable_static()

        gt = self.run_dygraph(feed)

122 123 124
        for x, y in zip(gt, res):
            if isinstance(x, list):
                for tx, ty in zip(x, y):
125
                    np.testing.assert_array_equal(tx, ty)
126
            elif isinstance(x, np.ndarray):
127
                np.testing.assert_array_equal(x, y)
128 129 130 131 132 133
            else:
                raise Exception("Not Implement!")


class TestWhile(TestCompatibility):
    def _get_feed(self):
134
        """return the feeds"""
135 136 137 138 139 140 141 142 143 144 145 146 147
        return None

    def build_program(self):
        def cond(i, ten):
            return i < ten

        def body(i, ten):
            i = i + 1
            return [i, ten]

        main_program = paddle.static.default_main_program()
        startup_program = paddle.static.default_startup_program()
        with paddle.static.program_guard(main_program, startup_program):
148 149 150 151 152 153
            i = paddle.full(
                shape=[1], fill_value=0, dtype='int64'
            )  # loop counter
            ten = paddle.full(
                shape=[1], fill_value=10, dtype='int64'
            )  # loop length
154 155 156 157 158
            i, ten = paddle.static.nn.while_loop(cond, body, [i, ten])

            exe = paddle.static.Executor(paddle.CPUPlace())
        return main_program, startup_program, i

159 160 161 162 163 164
    def run_dygraph_once(self, feed):
        i = 1
        while i < 10:
            i = i + 1
        return [i]

165 166 167

if __name__ == "__main__":
    unittest.main()