test_while_op.py 5.1 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.

15 16
from __future__ import print_function

Y
Yang Yang(Tony) 已提交
17
import unittest
18 19 20
import paddle.fluid.layers as layers
from paddle.fluid.executor import Executor
import paddle.fluid.core as core
21
import paddle.fluid as fluid
22
from paddle.fluid.backward import append_backward
Y
Yang Yang(Tony) 已提交
23
import numpy
24
from paddle.fluid import compiler, Program, program_guard
Y
Yang Yang(Tony) 已提交
25 26 27


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

            i = layers.increment(x=i, in_place=True)
Y
Yang Yang(Tony) 已提交
62 63
            layers.array_write(result, i=i, array=mem_array)
            layers.less_than(x=i, y=array_len, cond=cond)
Y
Yang Yang(Tony) 已提交
64

C
chengduoZH 已提交
65 66 67 68 69 70 71 72 73
            with while_op2.block():
                d2 = layers.array_read(array=data_array, i=j)
                prev2 = layers.array_read(array=mem_array, i=j)
                result2 = layers.sums(input=[d2, prev2])

                j = layers.increment(x=j, in_place=True)
                layers.array_write(result2, i=j, array=mem_array)
                layers.less_than(x=j, y=array_len2, cond=cond2)
        sum_result = layers.array_read(array=mem_array, i=j)
Y
Yu Yang 已提交
74
        loss = layers.mean(sum_result)
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
        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'))

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

98 99 100 101 102 103
    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) 已提交
104

105 106 107
            cpu = core.CPUPlace()
            exe = Executor(cpu)
            d = []
Y
Yang Yang(Tony) 已提交
108

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

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

115 116 117 118 119 120 121 122 123 124
    def test_exceptions(self):
        i = layers.zeros(shape=[2], dtype='int64')
        array_len = layers.fill_constant(shape=[2], dtype='int64', value=1)
        cond = layers.less_than(x=i, y=array_len)
        with self.assertRaises(TypeError):
            layers.While(cond=cond)
        cond = layers.cast(cond, dtype='float64')
        with self.assertRaises(TypeError):
            layers.While(cond=cond)

Y
Yang Yang(Tony) 已提交
125

126 127 128 129 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]
                fluid.layers.increment(x)

            self.assertRaises(TypeError, test_bad_x)


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