test_standalone_controlflow.py 4.4 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 16
# 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
import paddle
L
Leo Chen 已提交
17
from paddle.fluid import core, framework
18 19 20 21 22 23 24 25 26 27 28 29
from paddle.fluid.framework import Program, program_guard
import paddle.fluid.layers as layers

import numpy as np

paddle.enable_static()


#  test the compatibility of new executor: run old
#  and new executor twice and check the result.
#  please override the _get_feeds() and build_prgram()
class TestCompatibility(unittest.TestCase):
30

31
    def setUp(self):
32 33
        self.place = paddle.CUDAPlace(
            0) if core.is_compiled_with_cuda() else paddle.CPUPlace()
34 35 36 37 38 39 40 41
        self.iter_run = 4

    def _get_feed(self):
        """ return the feeds
        """
        return None

    def build_program(self):
42

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

        def false_func():
51 52 53 54 55
            return layers.fill_constant(shape=[3, 4], dtype='float32',
                                        value=3), layers.fill_constant(
                                            shape=[4, 5],
                                            dtype='int64',
                                            value=2)
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = layers.fill_constant(shape=[1], dtype='float32', value=0.1)
            y = layers.fill_constant(shape=[1], dtype='float32', value=0.23)
            pred = layers.less_than(x, y)
            out = layers.cond(pred, true_func, false_func)
            # 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

    def run_raw_executor(self, feed):
L
Leo Chen 已提交
80 81
        with framework._enable_standalone_executor(False):
            out = self._run(feed)
82 83 84
        return out

    def run_new_executor(self, feed):
L
Leo Chen 已提交
85 86
        with framework._enable_standalone_executor(True):
            out = self._run(feed)
87 88 89 90 91 92 93 94 95
        return out

    def test_with_feed(self):
        feed = self._get_feed()
        res = self.run_new_executor(feed)
        gt = self.run_raw_executor(feed)
        for x, y in zip(gt, res):
            if isinstance(x, list):
                for tx, ty in zip(x, y):
96
                    np.testing.assert_array_equal(tx, ty)
97
            elif isinstance(x, np.ndarray):
98
                np.testing.assert_array_equal(tx, ty)
99 100 101 102 103
            else:
                raise Exception("Not Implement!")


class TestWhile(TestCompatibility):
104

105 106 107 108 109 110
    def _get_feed(self):
        """ return the feeds
        """
        return None

    def build_program(self):
111

112 113 114 115 116 117 118 119 120 121
        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):
122 123 124 125
            i = paddle.full(shape=[1], fill_value=0,
                            dtype='int64')  # loop counter
            ten = paddle.full(shape=[1], fill_value=10,
                              dtype='int64')  # loop length
126 127 128 129 130 131 132 133
            i, ten = paddle.static.nn.while_loop(cond, body, [i, ten])

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


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