test_while_op.py 8.3 KB
Newer Older
C
chengduoZH 已提交
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.

Y
Yang Yang(Tony) 已提交
15
import unittest
16 17 18

import numpy

L
Leo Chen 已提交
19
import paddle
20
import paddle.fluid as fluid
21 22
import paddle.fluid.core as core
import paddle.fluid.layers as layers
23
from paddle.fluid.backward import append_backward
24
from paddle.fluid.executor import Executor
Y
Yang Yang(Tony) 已提交
25

26 27
paddle.enable_static()

Y
Yang Yang(Tony) 已提交
28 29

class TestWhileOp(unittest.TestCase):
30
    def simple_net(self):
G
GGBond8488 已提交
31 32 33
        d0 = paddle.static.data("d0", shape=[10], dtype='float32')
        d1 = paddle.static.data("d1", shape=[10], dtype='float32')
        d2 = paddle.static.data("d2", shape=[10], dtype='float32')
Y
Yang Yang(Tony) 已提交
34 35 36
        i = layers.zeros(shape=[1], dtype='int64')
        i.stop_gradient = True
        init = layers.zeros(shape=[10], dtype='float32')
37 38
        mem_array = paddle.tensor.array_write(x=init, i=i)
        data_array = paddle.tensor.array_write(x=d0, i=i)
39
        i = paddle.increment(i)
40
        paddle.tensor.array_write(d1, i, array=data_array)
41
        i = paddle.increment(i)
42
        paddle.tensor.array_write(d2, i, array=data_array)
Y
Yang Yang(Tony) 已提交
43 44
        i = layers.zeros(shape=[1], dtype='int64')
        i.stop_gradient = True
45 46 47
        array_len = paddle.tensor.fill_constant(
            shape=[1], dtype='int64', value=1
        )
Y
Yang Yang(Tony) 已提交
48
        array_len.stop_gradient = True
L
LiYuRio 已提交
49
        cond = paddle.less_than(x=i, y=array_len)
50
        j = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
C
chengduoZH 已提交
51
        j.stop_gradient = True
52 53 54
        array_len2 = paddle.tensor.fill_constant(
            shape=[1], dtype='int64', value=3
        )
C
chengduoZH 已提交
55
        array_len2.stop_gradient = True
L
LiYuRio 已提交
56
        cond2 = paddle.less_than(x=j, y=array_len2)
57 58
        while_op = paddle.static.nn.control_flow.While(cond=cond)
        while_op2 = paddle.static.nn.control_flow.While(cond=cond2)
Y
Yang Yang(Tony) 已提交
59
        with while_op.block():
60 61
            d = paddle.tensor.array_read(array=data_array, i=i)
            prev = paddle.tensor.array_read(array=mem_array, i=i)
62
            result = paddle.add_n([d, prev])
Y
Yang Yang(Tony) 已提交
63

64
            i = paddle.increment(x=i)
65
            paddle.tensor.array_write(result, i=i, array=mem_array)
L
LiYuRio 已提交
66
            paddle.assign(paddle.less_than(x=i, y=array_len), cond)
Y
Yang Yang(Tony) 已提交
67

C
chengduoZH 已提交
68
            with while_op2.block():
69 70
                d2 = paddle.tensor.array_read(array=data_array, i=j)
                prev2 = paddle.tensor.array_read(array=mem_array, i=j)
71
                result2 = paddle.add_n([d2, prev2])
C
chengduoZH 已提交
72

73
                j = paddle.increment(x=j)
74
                paddle.tensor.array_write(result2, i=j, array=mem_array)
L
LiYuRio 已提交
75
                paddle.assign(paddle.less_than(x=j, y=array_len2), cond2)
76
        sum_result = paddle.tensor.array_read(array=mem_array, i=j)
77
        loss = paddle.mean(sum_result)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        return loss, sum_result

    def test_simple_net(self):
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            loss, sum_result = self.simple_net()

            append_backward(loss)

            cpu = core.CPUPlace()
            exe = Executor(cpu)
            d = []

            for i in range(3):
                d.append(numpy.random.random(size=[10]).astype('float32'))

95 96 97 98
            outs = exe.run(
                feed={'d0': d[0], 'd1': d[1], 'd2': d[2]},
                fetch_list=[sum_result],
            )
99
            self.assertAlmostEqual(numpy.sum(d), numpy.sum(outs[0]), delta=0.01)
Y
Yang Yang(Tony) 已提交
100

101 102 103 104 105 106
    def test_simple_net_forward(self):
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            self.simple_net()
            binary = fluid.compiler.CompiledProgram(main_program)
Y
Yang Yang(Tony) 已提交
107

108 109 110
            cpu = core.CPUPlace()
            exe = Executor(cpu)
            d = []
Y
Yang Yang(Tony) 已提交
111

112 113
            for i in range(3):
                d.append(numpy.random.random(size=[10]).astype('float32'))
Y
Yang Yang(Tony) 已提交
114

115 116
            for _ in range(2):
                exe.run(binary, feed={'d0': d[0], 'd1': d[1], 'd2': d[2]})
Y
Yang Yang(Tony) 已提交
117

118 119
    def test_exceptions(self):
        i = layers.zeros(shape=[2], dtype='int64')
120 121 122
        array_len = paddle.tensor.fill_constant(
            shape=[2], dtype='int64', value=1
        )
L
LiYuRio 已提交
123
        cond = paddle.less_than(x=i, y=array_len)
124
        with self.assertRaises(TypeError):
125
            paddle.static.nn.control_flow.While(cond=cond)
126
        cond = paddle.cast(cond, dtype='float64')
127
        with self.assertRaises(TypeError):
128
            paddle.static.nn.control_flow.While(cond=cond)
129

Y
Yang Yang(Tony) 已提交
130

131 132 133 134 135 136
class BadInputTest(unittest.TestCase):
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

            def test_bad_x():
                x = [1, 2, 3]
137
                paddle.increment(x)
138 139 140 141

            self.assertRaises(TypeError, test_bad_x)


142 143 144 145 146 147 148 149 150 151 152 153
class TestIgnoreVarNameInWhile(unittest.TestCase):
    def test_ignore_var(self):
        def cond(i, ten, temp, y):
            return i < ten

        def body_func(i, ten, batch_info, origin_seq):
            print(batch_info)
            batch_info = fluid.contrib.layers.shuffle_batch(batch_info)
            print(batch_info)
            i = i + 1
            return [i, ten, batch_info, origin_seq]

G
GGBond8488 已提交
154 155 156 157
        x = paddle.static.data(name='x', shape=[-1, 1, 4], dtype='float32')
        y = paddle.static.data(name='y', shape=[-1, 1, 1], dtype='float32')
        x.desc.set_need_check_feed(False)
        y.desc.set_need_check_feed(False)
158 159
        temp = paddle.concat([x, y], axis=-1)

160 161
        i = paddle.tensor.fill_constant(shape=[1], value=0, dtype='int32')
        num = paddle.tensor.fill_constant(shape=[1], value=5, dtype='int32')
162

163
        i, ten, shuffle_temp, y = paddle.static.nn.while_loop(
164 165
            cond, body_func, [i, num, temp, y]
        )
166 167 168 169 170 171 172 173 174 175 176

        output = shuffle_temp

        exe = fluid.Executor(fluid.CPUPlace())
        exe.run(fluid.default_startup_program())

        input_x = numpy.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
        input_x = input_x.reshape(3, 1, 4)
        input_y = numpy.array([[10], [12], [33]])
        input_y = input_y.reshape(3, 1, 1)

177 178 179 180 181
        (res,) = exe.run(
            fluid.default_main_program(),
            feed={'x': input_x, 'y': input_y},
            fetch_list=[output],
        )
182 183 184 185

        self.assertListEqual(list(res.shape), [3, 1, 5])


186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
class TestOutputsMustExistsInputs(unittest.TestCase):
    def test_outputs_exists_inputs(self):
        """
        We guarantee that the output tensor must be in the input tensor, so that the output and input can correspond to each other, but the input can be greater than the number of outputs. It's required in paddle2onnx.
        """
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):

            def func(x):
                s = paddle.zeros([1])
                i = paddle.ones([1])
                max_len = paddle.shape(x)[0]

                def cond(i, s, x):
                    return i < max_len

                def body(i, s, x):
                    iter = x[i]
                    s += iter
                    i += 1
                    return i, s, x

                [i, s, x] = paddle.static.nn.while_loop(cond, body, [i, s, x])
                return s

            paddle.enable_static()
G
GGBond8488 已提交
213
            x = paddle.static.data(shape=[-1], name='x', dtype='float32')
214 215 216 217
            func(x)
        for op in main_program.block(0).ops:
            if op.type == "while":
                for out_name in op.output("Out"):
218 219
                    if out_name in op.input("Condition"):
                        continue
220 221
                    self.assertTrue(
                        out_name in op.input("X"),
222 223 224 225
                        "In while op, the variable in output(`Out`) must exists in inputs(`X`), but the variable with name `{}` not meet the precondition.".format(
                            out_name
                        ),
                    )
226 227


Y
Yang Yang(Tony) 已提交
228 229
if __name__ == '__main__':
    unittest.main()