test_case.py 11.4 KB
Newer Older
L
liym27 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import print_function

import numpy as np
import unittest

20
import paddle
L
liym27 已提交
21 22 23 24 25
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.layers as layers
from paddle.fluid.framework import Program, program_guard
from functools import partial
26
import paddle.fluid.optimizer as optimizer
L
liym27 已提交
27 28 29


class TestAPICase(unittest.TestCase):
30

L
liym27 已提交
31
    def test_return_single_var(self):
32

L
liym27 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
        def fn_1():
            return layers.fill_constant(shape=[4, 2], dtype='int32', value=1)

        def fn_2():
            return layers.fill_constant(shape=[4, 2], dtype='int32', value=2)

        def fn_3():
            return layers.fill_constant(shape=[4, 3], dtype='int32', value=3)

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = layers.fill_constant(shape=[1], dtype='float32', value=0.3)
            y = layers.fill_constant(shape=[1], dtype='float32', value=0.1)
            z = layers.fill_constant(shape=[1], dtype='float32', value=0.2)
            pred_2 = layers.less_than(x, y)  # false: 0.3 < 0.1
            pred_1 = layers.less_than(z, x)  # true: 0.2 < 0.3

            # call fn_1
52 53
            out_0 = layers.case(pred_fn_pairs=[(pred_1, fn_1), (pred_1, fn_2)],
                                default=fn_3)
L
liym27 已提交
54 55

            # call fn_2
56 57
            out_1 = layers.case(pred_fn_pairs=[(pred_2, fn_1), (pred_1, fn_2)],
                                default=fn_3)
L
liym27 已提交
58 59

            # call default fn_3
60 61
            out_2 = layers.case(pred_fn_pairs=((pred_2, fn_1), (pred_2, fn_2)),
                                default=fn_3)
L
liym27 已提交
62 63 64 65 66 67 68

            # no default, call fn_2
            out_3 = layers.case(pred_fn_pairs=[(pred_1, fn_2)])

            # no default, call fn_2. but pred_2 is false
            out_4 = layers.case(pred_fn_pairs=[(pred_2, fn_2)])

69 70
            place = fluid.CUDAPlace(
                0) if core.is_compiled_with_cuda() else fluid.CPUPlace()
L
liym27 已提交
71 72 73 74 75
            exe = fluid.Executor(place)

            res = exe.run(main_program,
                          fetch_list=[out_0, out_1, out_2, out_3, out_4])

76 77 78 79 80
            np.testing.assert_allclose(res[0], 1, rtol=1e-05)
            np.testing.assert_allclose(res[1], 2, rtol=1e-05)
            np.testing.assert_allclose(res[2], 3, rtol=1e-05)
            np.testing.assert_allclose(res[3], 2, rtol=1e-05)
            np.testing.assert_allclose(res[4], 2, rtol=1e-05)
L
liym27 已提交
81 82

    def test_return_var_tuple(self):
83

L
liym27 已提交
84
        def fn_1():
85 86 87 88 89
            return layers.fill_constant(shape=[1, 2], dtype='int32',
                                        value=1), layers.fill_constant(
                                            shape=[2, 3],
                                            dtype='float32',
                                            value=2)
L
liym27 已提交
90 91

        def fn_2():
92 93 94 95 96
            return layers.fill_constant(shape=[3, 4], dtype='int32',
                                        value=3), layers.fill_constant(
                                            shape=[4, 5],
                                            dtype='float32',
                                            value=4)
L
liym27 已提交
97 98

        def fn_3():
99 100 101 102 103
            return layers.fill_constant(shape=[5], dtype='int32',
                                        value=5), layers.fill_constant(
                                            shape=[5, 6],
                                            dtype='float32',
                                            value=6)
L
liym27 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = layers.fill_constant(shape=[1], dtype='float32', value=1)
            y = layers.fill_constant(shape=[1], dtype='float32', value=1)
            z = layers.fill_constant(shape=[1], dtype='float32', value=3)

            pred_1 = layers.equal(x, y)  # true
            pred_2 = layers.equal(x, z)  # false

            out = layers.case(((pred_1, fn_1), (pred_2, fn_2)), fn_3)

117 118
            place = fluid.CUDAPlace(
                0) if core.is_compiled_with_cuda() else fluid.CPUPlace()
L
liym27 已提交
119 120 121
            exe = fluid.Executor(place)
            ret = exe.run(main_program, fetch_list=out)

122 123 124 125 126 127
            np.testing.assert_allclose(np.asarray(ret[0]),
                                       np.full((1, 2), 1, np.int32),
                                       rtol=1e-05)
            np.testing.assert_allclose(np.asarray(ret[1]),
                                       np.full((2, 3), 2, np.float32),
                                       rtol=1e-05)
L
liym27 已提交
128 129 130


class TestAPICase_Nested(unittest.TestCase):
131

L
liym27 已提交
132
    def test_nested_case(self):
133

L
liym27 已提交
134 135 136
        def fn_1(x=1):
            var_5 = layers.fill_constant(shape=[1], dtype='int32', value=5)
            var_6 = layers.fill_constant(shape=[1], dtype='int32', value=6)
137 138 139 140 141 142 143 144
            out = layers.case(pred_fn_pairs=[
                (var_5 < var_6,
                 partial(
                     layers.fill_constant, shape=[1], dtype='int32', value=x)),
                (var_5 == var_6,
                 partial(
                     layers.fill_constant, shape=[2], dtype='int32', value=x))
            ])
L
liym27 已提交
145 146 147 148 149
            return out

        def fn_2(x=2):
            var_5 = layers.fill_constant(shape=[1], dtype='int32', value=5)
            var_6 = layers.fill_constant(shape=[1], dtype='int32', value=6)
150 151 152 153 154 155
            out = layers.case(pred_fn_pairs=[
                (var_5 < var_6, partial(fn_1, x=x)),
                (var_5 == var_6,
                 partial(
                     layers.fill_constant, shape=[2], dtype='int32', value=x))
            ])
L
liym27 已提交
156 157 158 159 160
            return out

        def fn_3():
            var_5 = layers.fill_constant(shape=[1], dtype='int32', value=5)
            var_6 = layers.fill_constant(shape=[1], dtype='int32', value=6)
161 162 163 164 165 166
            out = layers.case(pred_fn_pairs=[
                (var_5 < var_6, partial(fn_2, x=3)),
                (var_5 == var_6,
                 partial(
                     layers.fill_constant, shape=[2], dtype='int32', value=7))
            ])
L
liym27 已提交
167 168 169 170 171 172 173 174 175 176 177
            return out

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = layers.fill_constant(shape=[1], dtype='float32', value=0.3)
            y = layers.fill_constant(shape=[1], dtype='float32', value=0.1)
            z = layers.fill_constant(shape=[1], dtype='float32', value=0.2)
            pred_2 = layers.less_than(x, y)  # false: 0.3 < 0.1
            pred_1 = layers.less_than(z, x)  # true: 0.2 < 0.3

178 179
            out_1 = layers.case(pred_fn_pairs=[(pred_1, fn_1), (pred_2, fn_2)],
                                default=fn_3)
L
liym27 已提交
180

181 182
            out_2 = layers.case(pred_fn_pairs=[(pred_2, fn_1), (pred_1, fn_2)],
                                default=fn_3)
L
liym27 已提交
183

184 185
            out_3 = layers.case(pred_fn_pairs=[(x == y, fn_1), (x == z, fn_2)],
                                default=fn_3)
L
liym27 已提交
186

187 188
            place = fluid.CUDAPlace(
                0) if core.is_compiled_with_cuda() else fluid.CPUPlace()
L
liym27 已提交
189 190 191 192
            exe = fluid.Executor(place)

            res = exe.run(main_program, fetch_list=[out_1, out_2, out_3])

193 194 195
            np.testing.assert_allclose(res[0], 1, rtol=1e-05)
            np.testing.assert_allclose(res[1], 2, rtol=1e-05)
            np.testing.assert_allclose(res[2], 3, rtol=1e-05)
L
liym27 已提交
196 197 198


class TestAPICase_Error(unittest.TestCase):
199

L
liym27 已提交
200
    def test_error(self):
201

L
liym27 已提交
202 203 204 205 206 207 208 209 210 211
        def fn_1():
            return layers.fill_constant(shape=[4, 2], dtype='int32', value=1)

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = layers.fill_constant(shape=[1], dtype='float32', value=0.23)
            z = layers.fill_constant(shape=[1], dtype='float32', value=0.2)
            pred_1 = layers.less_than(z, x)  # true

212
            # The type of 'pred_fn_pairs' in case must be list or tuple
L
liym27 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
            def type_error_pred_fn_pairs():
                layers.case(pred_fn_pairs=1, default=fn_1)

            self.assertRaises(TypeError, type_error_pred_fn_pairs)

            # The elements' type of 'pred_fn_pairs' in Op(case) must be tuple
            def type_error_pred_fn_1():
                layers.case(pred_fn_pairs=[1], default=fn_1)

            self.assertRaises(TypeError, type_error_pred_fn_1)

            # The tuple's size of 'pred_fn_pairs' in Op(case) must be 2
            def type_error_pred_fn_2():
                layers.case(pred_fn_pairs=[(1, 2, 3)], default=fn_1)

            self.assertRaises(TypeError, type_error_pred_fn_2)

            # The pred's type of 'pred_fn_pairs' in Op(case) must be bool Variable
            def type_error_pred():
                layers.case(pred_fn_pairs=[(1, fn_1)], default=fn_1)

            self.assertRaises(TypeError, type_error_pred)

            # The function of pred_fn_pairs in case must be callable
            def type_error_fn():
                layers.case(pred_fn_pairs=[(pred_1, 2)], default=fn_1)

            self.assertRaises(TypeError, type_error_fn)

            # The default in Op(case) must be callable
            def type_error_default():
                layers.case(pred_fn_pairs=[(pred_1, fn_1)], default=fn_1())

            self.assertRaises(TypeError, type_error_default)


249 250
# when optimizer in case
class TestMutiTask(unittest.TestCase):
251

252 253 254 255 256
    def test_optimizer_in_case(self):
        BATCH_SIZE = 1
        INPUT_SIZE = 784
        EPOCH_NUM = 2

257 258 259 260 261 262
        x = fluid.data(name='x',
                       shape=[BATCH_SIZE, INPUT_SIZE],
                       dtype='float32')
        y = fluid.data(name='y',
                       shape=[BATCH_SIZE, INPUT_SIZE],
                       dtype='float32')
263 264 265 266 267 268 269 270 271

        switch_id = fluid.data(name='switch_id', shape=[1], dtype='int32')

        one = layers.fill_constant(shape=[1], dtype='int32', value=1)
        adam = optimizer.Adam(learning_rate=0.001)
        adagrad = optimizer.Adagrad(learning_rate=0.001)

        def fn_1():
            sum = layers.elementwise_mul(x, y)
272
            loss = paddle.mean(sum, name="f_1_loss")
273 274 275 276
            adam.minimize(loss)

        def fn_2():
            sum = layers.elementwise_mul(x, y)
277
            loss = paddle.mean(sum, name="f_2_loss")
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
            adagrad.minimize(loss)

        layers.case(pred_fn_pairs=[(switch_id == one, fn_1)], default=fn_2)

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

        for epoch in range(EPOCH_NUM):
            np.random.seed(epoch)
            feed_image = np.random.random(
                size=[BATCH_SIZE, INPUT_SIZE]).astype('float32')
            main_program = fluid.default_main_program()
            out = exe.run(main_program,
                          feed={
                              'x': feed_image,
                              'y': feed_image,
                              'switch_id': np.array([epoch]).astype('int32')
                          },
                          fetch_list=[])


L
liym27 已提交
299 300
if __name__ == '__main__':
    unittest.main()