test_if_else_op.py 8.9 KB
Newer Older
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 17 18
import unittest

import numpy as np

19
import paddle
20 21
import paddle.fluid as fluid
import paddle.fluid.core as core
22 23
import paddle.fluid.layers as layers
from paddle.fluid.executor import Executor
24 25 26 27 28 29
from paddle.fluid.framework import Program, program_guard
from paddle.fluid.layers.control_flow import (
    ConditionalBlock,
    merge_lod_tensor,
    split_lod_tensor,
)
30
from paddle.fluid.optimizer import MomentumOptimizer
Y
Yu Yang 已提交
31

P
pangyoki 已提交
32 33
paddle.enable_static()

Y
Yu Yang 已提交
34 35

class TestMNISTIfElseOp(unittest.TestCase):
36 37
    # FIXME: https://github.com/PaddlePaddle/Paddle/issues/12245#issuecomment-406462379
    def not_test_raw_api(self):
38 39 40 41
        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            image = layers.data(name='x', shape=[784], dtype='float32')
Y
Yu Yang 已提交
42

43
            label = layers.data(name='y', shape=[1], dtype='int64')
Y
Yu Yang 已提交
44

45
            limit = layers.fill_constant(shape=[1], dtype='int64', value=5)
L
LiYuRio 已提交
46
            cond = paddle.less_than(x=label, y=limit)
47
            true_image, false_image = split_lod_tensor(input=image, mask=cond)
Y
Yu Yang 已提交
48

49
            true_out = layers.create_tensor(dtype='float32')
50
            true_cond = ConditionalBlock([cond])
Y
Yu Yang 已提交
51

52 53 54 55
            with true_cond.block():
                hidden = layers.fc(input=true_image, size=100, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                layers.assign(input=prob, output=true_out)
Y
Yu Yang 已提交
56

57
            false_out = layers.create_tensor(dtype='float32')
58
            false_cond = ConditionalBlock([cond])
Y
Yu Yang 已提交
59

60 61 62 63
            with false_cond.block():
                hidden = layers.fc(input=false_image, size=200, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                layers.assign(input=prob, output=false_out)
Y
Yu Yang 已提交
64

65 66 67
            prob = merge_lod_tensor(
                in_true=true_out, in_false=false_out, mask=cond, x=image
            )
68
            loss = layers.cross_entropy(input=prob, label=label)
69
            avg_loss = paddle.mean(loss)
Y
Yu Yang 已提交
70

71 72
            optimizer = MomentumOptimizer(learning_rate=0.001, momentum=0.9)
            optimizer.minimize(avg_loss, startup_prog)
Y
Yu Yang 已提交
73

74 75 76 77
        train_reader = paddle.batch(
            paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=8192),
            batch_size=10,
        )
Y
Yu Yang 已提交
78 79 80 81

        place = core.CPUPlace()
        exe = Executor(place)

82
        exe.run(startup_prog)
Y
Yu Yang 已提交
83 84 85
        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for data in train_reader():
86 87
                x_data = np.array([x[0] for x in data]).astype("float32")
                y_data = np.array([x[1] for x in data]).astype("int64")
Y
Yu Yang 已提交
88 89
                y_data = np.expand_dims(y_data, axis=1)

90 91 92
                outs = exe.run(
                    prog, feed={'x': x_data, 'y': y_data}, fetch_list=[avg_loss]
                )
93
                print(outs[0])
Y
Yu Yang 已提交
94 95 96 97
                if outs[0] < 1.0:
                    return
        self.assertFalse(True)

98 99
    # FIXME: https://github.com/PaddlePaddle/Paddle/issues/12245#issuecomment-406462379
    def not_test_ifelse(self):
100 101 102 103 104 105 106
        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            image = layers.data(name='x', shape=[784], dtype='float32')

            label = layers.data(name='y', shape=[1], dtype='int64')

107
            limit = layers.fill_constant(shape=[1], dtype='int64', value=5)
L
LiYuRio 已提交
108
            cond = paddle.less_than(x=label, y=limit)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
            ie = layers.IfElse(cond)

            with ie.true_block():
                true_image = ie.input(image)
                hidden = layers.fc(input=true_image, size=100, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                ie.output(prob)

            with ie.false_block():
                false_image = ie.input(image)
                hidden = layers.fc(input=false_image, size=200, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                ie.output(prob)

            prob = ie()
            loss = layers.cross_entropy(input=prob[0], label=label)
125
            avg_loss = paddle.mean(loss)
126 127 128

            optimizer = MomentumOptimizer(learning_rate=0.001, momentum=0.9)
            optimizer.minimize(avg_loss, startup_prog)
129 130 131 132
        train_reader = paddle.batch(
            paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=8192),
            batch_size=200,
        )
Y
Yu Yang 已提交
133 134 135 136

        place = core.CPUPlace()
        exe = Executor(place)

137
        exe.run(startup_prog)
Y
Yu Yang 已提交
138 139 140
        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for data in train_reader():
141 142
                x_data = np.array([x[0] for x in data]).astype("float32")
                y_data = np.array([x[1] for x in data]).astype("int64")
D
dzhwinter 已提交
143
                y_data = y_data.reshape((y_data.shape[0], 1))
Y
Yu Yang 已提交
144

145 146 147
                outs = exe.run(
                    prog, feed={'x': x_data, 'y': y_data}, fetch_list=[avg_loss]
                )
148
                print(outs[0])
Y
Yu Yang 已提交
149 150 151 152 153
                if outs[0] < 1.0:
                    return
        self.assertFalse(True)


154 155 156 157 158 159
class TestIfElse(unittest.TestCase):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
        self.cond_value = 0.5
        self.data = np.random.rand(25, 1).astype(np.float32)

160 161 162 163 164 165 166
    def numpy_cal(self):
        s1 = self.data[np.where(self.data < self.cond_value)]
        res = np.sum(np.exp(s1))
        s2 = self.data[np.where(self.data >= self.cond_value)]
        res += np.sum(np.tanh(s2))
        return res

167 168 169 170 171 172 173
    def compare_ifelse_op_and_numpy(self, place):
        self.set_test_case()

        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            src = layers.data(name='data', shape=[1], dtype='float32')
174 175 176
            cond = layers.fill_constant(
                [1], dtype='float32', value=self.cond_value
            )
L
LiYuRio 已提交
177
            ifcond = paddle.less_than(x=src, y=cond)
178 179 180
            ie = layers.IfElse(ifcond)
            with ie.true_block():
                true_target = ie.input(src)
181
                true_target = paddle.exp(true_target)
182 183 184 185
                ie.output(true_target)

            with ie.false_block():
                false_target = ie.input(src)
186
                false_target = paddle.tanh(false_target)
187 188
                ie.output(false_target)
            if_out = ie()
189
            out = paddle.sum(if_out[0])
190 191 192 193

            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
            fetch_list = [out]
194 195 196 197 198
            (o1,) = exe.run(
                fluid.default_main_program(),
                feed={'data': self.data},
                fetch_list=[out],
            )
199 200
            o2 = self.numpy_cal()

201 202 203 204 205 206
            np.testing.assert_allclose(
                o1,
                o2,
                rtol=1e-05,
                atol=1e-08,
            )
207 208 209 210 211 212 213 214 215 216 217 218 219

    def test_cpu(self):
        self.compare_ifelse_op_and_numpy(fluid.CPUPlace())

    def test_cuda(self):
        if not core.is_compiled_with_cuda():
            return
        self.compare_ifelse_op_and_numpy(fluid.CUDAPlace(0))


class TestIfElseTrueBranch(TestIfElse):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
220
        self.cond_value = 10.0
221 222 223 224 225 226
        self.data = np.random.rand(25, 1).astype(np.float32)


class TestIfElseFalseBranch(TestIfElse):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
227
        self.cond_value = -10.0
228 229 230
        self.data = np.random.rand(25, 1).astype(np.float32)


231 232 233 234 235 236
class TestIfElseError(unittest.TestCase):
    def test_input_type_error(self):
        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            src = layers.data(name='data', shape=[1], dtype='float32')
237 238 239
            const_value = layers.fill_constant(
                [1], dtype='float32', value=123.0
            )
L
LiYuRio 已提交
240
            ifcond = paddle.less_than(x=src, y=const_value)
241 242 243 244 245 246 247 248 249
            with self.assertRaises(TypeError):
                ie = layers.IfElse(set())
            with self.assertRaises(TypeError):
                ie = layers.IfElse(ifcond, set())

            with self.assertRaises(TypeError):
                ie = layers.IfElse(ifcond)
                with ie.true_block():
                    true_target = ie.input(src)
250
                    true_target = paddle.exp(true_target)
251 252 253
                    ie.output([])


Y
Yu Yang 已提交
254
if __name__ == '__main__':
255
    unittest.main()