test_switch_case.py 22.6 KB
Newer Older
L
liym27 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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.

import unittest
16 17 18
from functools import partial

import numpy as np
L
liym27 已提交
19

20
import paddle
L
liym27 已提交
21 22 23
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.layers as layers
24
from paddle.fluid.backward import append_backward
L
liym27 已提交
25 26
from paddle.fluid.framework import Program, program_guard

27 28
paddle.enable_static()

L
liym27 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

class TestAPISwitchCase(unittest.TestCase):
    def test_return_single_var(self):
        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):
            index_1 = layers.fill_constant(shape=[1], dtype='int32', value=1)
            index_2 = layers.fill_constant(shape=[1], dtype='int32', value=2)
            index_5 = layers.fill_constant(shape=[1], dtype='int32', value=5)

            # call fn_1
49
            out_0 = paddle.static.nn.switch_case(
50 51
                branch_index=index_1, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )
L
liym27 已提交
52 53

            # call fn_2 : branch_fns={0: fn_1, 1:fn_2, 2:fn_3}
54
            out_1 = paddle.static.nn.switch_case(
55 56
                branch_index=index_1, branch_fns=(fn_1, fn_2, fn_3)
            )
L
liym27 已提交
57 58

            # call default fn_3
59
            out_2 = paddle.static.nn.switch_case(
60 61 62 63
                branch_index=index_5,
                branch_fns=((1, fn_1), (2, fn_2)),
                default=fn_3,
            )
L
liym27 已提交
64 65

            # no default, call fn_2
66
            out_3 = paddle.static.nn.switch_case(
67 68
                branch_index=index_2, branch_fns=[(1, fn_1), (2, fn_2)]
            )
L
liym27 已提交
69 70

            # no default, call fn_2 but branch_index is 5
71
            out_4 = paddle.static.nn.switch_case(
72 73 74 75 76 77 78 79 80
                branch_index=index_5,
                branch_fns=[(1, fn_1), (3, fn_2), (2, fn_3)],
            )

            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
L
liym27 已提交
81 82
            exe = fluid.Executor(place)

83 84 85
            res = exe.run(
                main_program, fetch_list=[out_0, out_1, out_2, out_3, out_4]
            )
L
liym27 已提交
86

87 88 89 90
            np.testing.assert_allclose(
                res[0],
                1,
                rtol=1e-05,
91 92
                err_msg='result is {} but answer is {}'.format(res[0], 1),
            )
93 94 95 96
            np.testing.assert_allclose(
                res[1],
                2,
                rtol=1e-05,
97
                err_msg='result is {} but answer is {}'.format(res[1], 2),
98
            )
99 100 101 102
            np.testing.assert_allclose(
                res[2],
                3,
                rtol=1e-05,
103
                err_msg='result is {} but answer is {}'.format(res[2], 3),
104
            )
105 106 107 108
            np.testing.assert_allclose(
                res[3],
                2,
                rtol=1e-05,
109
                err_msg='result is {} but answer is {}'.format(res[3], 2),
110
            )
111 112 113 114
            np.testing.assert_allclose(
                res[4],
                2,
                rtol=1e-05,
115
                err_msg='result is {} but answer is {}'.format(res[4], 2),
116
            )
L
liym27 已提交
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    def test_0d_tensor(self):
        def fn_1():
            return paddle.full(shape=[], dtype='int32', fill_value=1)

        def fn_2():
            return paddle.full(shape=[], dtype='int32', fill_value=2)

        def fn_3():
            return paddle.full(shape=[], dtype='int32', fill_value=3)

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            index_1 = paddle.full(shape=[], dtype='int32', fill_value=1)
            index_2 = paddle.full(shape=[], dtype='int32', fill_value=2)
            index_5 = paddle.full(shape=[], dtype='int32', fill_value=5)

            # call fn_1
            out_0 = paddle.static.nn.switch_case(
                branch_index=index_1, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )

            # call fn_2 : branch_fns={0: fn_1, 1:fn_2, 2:fn_3}
            out_1 = paddle.static.nn.switch_case(
                branch_index=index_1, branch_fns=(fn_1, fn_2, fn_3)
            )

            # call default fn_3
            out_2 = paddle.static.nn.switch_case(
                branch_index=index_5,
                branch_fns=((1, fn_1), (2, fn_2)),
                default=fn_3,
            )

            # no default, call fn_2
            out_3 = paddle.static.nn.switch_case(
                branch_index=index_2, branch_fns=[(1, fn_1), (2, fn_2)]
            )

            # no default, call fn_2 but branch_index is 5
            out_4 = paddle.static.nn.switch_case(
                branch_index=index_5,
                branch_fns=[(1, fn_1), (3, fn_2), (2, fn_3)],
            )

            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
            exe = fluid.Executor(place)

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

            np.testing.assert_allclose(
                res[0],
                1,
                rtol=1e-05,
                err_msg='result is {} but answer is {}'.format(res[0], 1),
            )
180
            self.assertEqual(res[0].shape, ())
181 182 183 184
            np.testing.assert_allclose(
                res[1],
                2,
                rtol=1e-05,
185
                err_msg='result is {} but answer is {}'.format(res[1], 2),
186
            )
187
            self.assertEqual(res[1].shape, ())
188 189 190 191
            np.testing.assert_allclose(
                res[2],
                3,
                rtol=1e-05,
192
                err_msg='result is {} but answer is {}'.format(res[2], 3),
193
            )
194
            self.assertEqual(res[2].shape, ())
195 196 197 198
            np.testing.assert_allclose(
                res[3],
                2,
                rtol=1e-05,
199
                err_msg='result is {} but answer is {}'.format(res[3], 2),
200
            )
201
            self.assertEqual(res[3].shape, ())
202 203 204 205
            np.testing.assert_allclose(
                res[4],
                2,
                rtol=1e-05,
206
                err_msg='result is {} but answer is {}'.format(res[4], 2),
207
            )
208 209 210 211 212 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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
            self.assertEqual(res[4].shape, ())

    def test_0d_tensor_backward(self):
        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            x = paddle.full(shape=[], dtype='float32', fill_value=-2.0)
            x.stop_gradient = False
            pred = paddle.full(shape=[], dtype='int32', fill_value=2)
            # pred is 2, so out = 2 * x
            out = paddle.static.nn.switch_case(
                branch_index=pred,
                branch_fns=[(1, lambda: x), (2, lambda: 2 * x)],
                default=lambda: -x,
            )
            append_backward(out)

        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
        exe = fluid.Executor(place)

        res = exe.run(main_program, fetch_list=[out.name, x.grad_name])
        np.testing.assert_allclose(
            np.asarray(res[0]), np.array(-4.0), rtol=1e-05
        )
        self.assertEqual(res[0].shape, ())
        np.testing.assert_allclose(
            np.asarray(res[1]), np.array(2.0), rtol=1e-05
        )
        self.assertEqual(res[1].shape, ())

    def test_0d_tensor_dygraph(self):
        paddle.disable_static()

        def fn_1():
            return paddle.full(shape=[], dtype='int32', fill_value=1)

        def fn_2():
            return paddle.full(shape=[], dtype='int32', fill_value=2)

        def fn_3():
            return paddle.full(shape=[], dtype='int32', fill_value=3)

        index_1 = paddle.full(shape=[], dtype='int32', fill_value=1)
        index_2 = paddle.full(shape=[], dtype='int32', fill_value=2)
        index_5 = paddle.full(shape=[], dtype='int32', fill_value=5)

        # call fn_1
        out_0 = paddle.static.nn.switch_case(
            branch_index=index_1, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
        )

        # call fn_2 : branch_fns={0: fn_1, 1:fn_2, 2:fn_3}
        out_1 = paddle.static.nn.switch_case(
            branch_index=index_1, branch_fns=(fn_1, fn_2, fn_3)
        )

        # call default fn_3
        out_2 = paddle.static.nn.switch_case(
            branch_index=index_5,
            branch_fns=((1, fn_1), (2, fn_2)),
            default=fn_3,
        )

        # no default, call fn_2
        out_3 = paddle.static.nn.switch_case(
            branch_index=index_2, branch_fns=[(1, fn_1), (2, fn_2)]
        )

        # no default, call fn_2 but branch_index is 5
        out_4 = paddle.static.nn.switch_case(
            branch_index=index_5,
            branch_fns=[(1, fn_1), (3, fn_2), (2, fn_3)],
        )
        np.testing.assert_allclose(
            out_0,
            1,
            rtol=1e-05,
            err_msg='result is {} but answer is {}'.format(out_0, 1),
        )
        self.assertEqual(out_0.shape, [])
        np.testing.assert_allclose(
            out_1,
            2,
            rtol=1e-05,
            err_msg='result is {} but answer is {}'.format(out_1, 2),
        )
        self.assertEqual(out_1.shape, [])
        np.testing.assert_allclose(
            out_2,
            3,
            rtol=1e-05,
            err_msg='result is {} but answer is {}'.format(out_2, 3),
        )
        self.assertEqual(out_2.shape, [])
        np.testing.assert_allclose(
            out_3,
            2,
            rtol=1e-05,
            err_msg='result is {} but answer is {}'.format(out_3, 2),
        )
        self.assertEqual(out_3.shape, [])
        np.testing.assert_allclose(
            out_4,
            2,
            rtol=1e-05,
            err_msg='result is {} but answer is {}'.format(out_4, 2),
        )
        self.assertEqual(out_4.shape, [])

        paddle.enable_static()
322

L
liym27 已提交
323 324
    def test_return_var_tuple(self):
        def fn_1():
325 326 327
            return layers.fill_constant(
                shape=[1, 2], dtype='int32', value=1
            ), layers.fill_constant(shape=[2, 3], dtype='float32', value=2)
L
liym27 已提交
328 329

        def fn_2():
330 331 332
            return layers.fill_constant(
                shape=[3, 4], dtype='int32', value=3
            ), layers.fill_constant(shape=[4, 5], dtype='float32', value=4)
L
liym27 已提交
333 334

        def fn_3():
335 336 337
            return layers.fill_constant(
                shape=[5], dtype='int32', value=5
            ), layers.fill_constant(shape=[5, 6], dtype='float32', value=6)
L
liym27 已提交
338 339 340 341 342 343

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            index_1 = layers.fill_constant(shape=[1], dtype='int32', value=1)

344 345 346
            out = paddle.static.nn.switch_case(
                index_1, ((1, fn_1), (2, fn_2)), fn_3
            )
L
liym27 已提交
347

348 349 350 351 352
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
L
liym27 已提交
353 354 355
            exe = fluid.Executor(place)
            ret = exe.run(main_program, fetch_list=out)

356 357 358 359 360 361
            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 已提交
362 363 364 365 366


class TestAPISwitchCase_Nested(unittest.TestCase):
    def test_nested_switch_case(self):
        def fn_1(x=1):
367
            out = paddle.static.nn.switch_case(
368 369 370 371 372 373 374 375 376 377 378 379
                branch_index=layers.fill_constant(
                    shape=[1], dtype='int32', value=x
                ),
                branch_fns={
                    1: partial(
                        layers.fill_constant, shape=[1], dtype='int32', value=1
                    ),
                    x: partial(
                        layers.fill_constant, shape=[2], dtype='int32', value=x
                    ),
                },
            )
L
liym27 已提交
380 381 382
            return out

        def fn_2(x=2):
383
            out = paddle.static.nn.switch_case(
384 385 386 387 388 389 390 391 392 393 394 395 396
                branch_index=layers.fill_constant(
                    shape=[1], dtype='int32', value=2
                ),
                branch_fns={
                    1: partial(
                        layers.fill_constant,
                        shape=[4, 3],
                        dtype='int32',
                        value=1,
                    ),
                    2: partial(fn_1, x=x),
                },
            )
L
liym27 已提交
397 398 399
            return out

        def fn_3():
400
            out = paddle.static.nn.switch_case(
401 402 403 404 405 406 407 408 409 410 411 412 413
                branch_index=layers.fill_constant(
                    shape=[1], dtype='int32', value=3
                ),
                branch_fns={
                    1: partial(
                        layers.fill_constant,
                        shape=[4, 3],
                        dtype='int32',
                        value=1,
                    ),
                    3: partial(fn_2, x=3),
                },
            )
L
liym27 已提交
414 415 416 417 418 419 420 421 422
            return out

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            index_1 = fluid.data(name="index_1", shape=[1], dtype='uint8')
            index_2 = layers.fill_constant(shape=[1], dtype='int32', value=2)
            index_3 = layers.fill_constant(shape=[1], dtype='int64', value=3)

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
            out_1 = paddle.static.nn.switch_case(
                branch_index=index_1, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )
            out_2 = paddle.static.nn.switch_case(
                branch_index=index_2, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )

            out_3 = paddle.static.nn.switch_case(
                branch_index=index_3, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )

            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
            exe = fluid.Executor(place)

            res = exe.run(
                main_program,
                feed={"index_1": np.array([1], dtype="uint8")},
                fetch_list=[out_1, out_2, out_3],
            )

            np.testing.assert_allclose(
                res[0],
                1,
                rtol=1e-05,
                err_msg='result is {} but answer is {}'.format(res[0], 1),
            )
            np.testing.assert_allclose(
                res[1],
                2,
                rtol=1e-05,
                err_msg='result is {} but answer is {}'.format(res[1], 2),
            )
            np.testing.assert_allclose(
                res[2],
                3,
                rtol=1e-05,
                err_msg='result is {} but answer is {}'.format(res[2], 3),
            )

    def test_nested_switch_0d_tensor(self):
        def fn_1(x=1):
            out = paddle.static.nn.switch_case(
                branch_index=paddle.full(shape=[], dtype='int32', fill_value=x),
                branch_fns={
                    1: partial(
                        paddle.full, shape=[], dtype='int32', fill_value=1
                    ),
                    x: partial(
                        paddle.full, shape=[], dtype='int32', fill_value=x
                    ),
                },
            )
            return out

        def fn_2(x=2):
            out = paddle.static.nn.switch_case(
                branch_index=paddle.full(shape=[], dtype='int32', fill_value=2),
                branch_fns={
                    1: partial(
                        paddle.full,
                        shape=[],
                        dtype='int32',
                        fill_value=1,
                    ),
                    2: partial(fn_1, x=x),
                },
            )
            return out

        def fn_3():
            out = paddle.static.nn.switch_case(
                branch_index=paddle.full(shape=[], dtype='int32', fill_value=3),
                branch_fns={
                    1: partial(
                        paddle.full,
                        shape=[],
                        dtype='int32',
                        fill_value=1,
                    ),
                    3: partial(fn_2, x=3),
                },
            )
            return out

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
            index_1 = fluid.data(name="index_1", shape=[1], dtype='uint8')
            index_2 = paddle.full(shape=[], dtype='int32', fill_value=2)
            index_3 = paddle.full(shape=[], dtype='int64', fill_value=3)

518
            out_1 = paddle.static.nn.switch_case(
519 520
                branch_index=index_1, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )
521
            out_2 = paddle.static.nn.switch_case(
522 523 524
                branch_index=index_2, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )

525
            out_3 = paddle.static.nn.switch_case(
526 527 528 529 530 531 532 533
                branch_index=index_3, branch_fns={1: fn_1, 2: fn_2, 3: fn_3}
            )

            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
L
liym27 已提交
534 535
            exe = fluid.Executor(place)

536 537 538 539 540
            res = exe.run(
                main_program,
                feed={"index_1": np.array([1], dtype="uint8")},
                fetch_list=[out_1, out_2, out_3],
            )
L
liym27 已提交
541

542 543 544 545
            np.testing.assert_allclose(
                res[0],
                1,
                rtol=1e-05,
546 547
                err_msg='result is {} but answer is {}'.format(res[0], 1),
            )
548
            self.assertEqual(res[0].shape, ())
549 550 551 552
            np.testing.assert_allclose(
                res[1],
                2,
                rtol=1e-05,
553 554
                err_msg='result is {} but answer is {}'.format(res[1], 2),
            )
555
            self.assertEqual(res[1].shape, ())
556 557 558 559
            np.testing.assert_allclose(
                res[2],
                3,
                rtol=1e-05,
560 561
                err_msg='result is {} but answer is {}'.format(res[2], 3),
            )
562
            self.assertEqual(res[2].shape, ())
L
liym27 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579


# test TypeError and ValueError of api switch_case
class TestAPISwitchCase_Error(unittest.TestCase):
    def test_error(self):
        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):
580 581 582 583 584 585
            key_float32 = layers.fill_constant(
                shape=[1], dtype='float32', value=0.23
            )
            key_int32 = layers.fill_constant(
                shape=[1], dtype='int32', value=0.23
            )
L
liym27 已提交
586 587 588

            # The type of 'branch_index' in Op(switch_case) must be Variable
            def type_error_branch_index():
589
                paddle.static.nn.switch_case(
590 591
                    branch_index=1, branch_fns=[(1, fn_1)], default=fn_3
                )
L
liym27 已提交
592 593 594 595 596

            self.assertRaises(TypeError, type_error_branch_index)

            # The data type of 'branch_index' in Op(switch_case) must be int32, int64 or uint8
            def dtype_error_branch_index():
597
                paddle.static.nn.switch_case(
598 599 600 601
                    branch_index=key_float32,
                    branch_fns=[(1, fn_1)],
                    default=fn_3,
                )
L
liym27 已提交
602 603 604 605 606

            self.assertRaises(TypeError, dtype_error_branch_index)

            # The type of 'branch_fns' in Op(switch_case) must be list, tuple or dict
            def type_error_branch_fns():
607
                paddle.static.nn.switch_case(
608 609
                    branch_index=key_int32, branch_fns=1, default=fn_3
                )
L
liym27 已提交
610 611 612 613 614

            self.assertRaises(TypeError, type_error_branch_fns)

            # The elements' type of 'branch_fns' in Op(switch_case) must be tuple
            def type_error_index_fn_pair_1():
615
                paddle.static.nn.switch_case(
616 617
                    branch_index=key_int32, branch_fns=[1], default=fn_3
                )
L
liym27 已提交
618 619 620 621 622

            self.assertRaises(TypeError, type_error_index_fn_pair_1)

            # The tuple's size of 'branch_fns' in Op(switch_case) must be 2
            def type_error_index_fn_pair_2():
623
                paddle.static.nn.switch_case(
624 625
                    branch_index=key_int32, branch_fns=[(1, 2, 3)], default=fn_3
                )
L
liym27 已提交
626 627 628 629 630

            self.assertRaises(TypeError, type_error_index_fn_pair_2)

            # The key's type of 'branch_fns' in Op(switch_case) must be int
            def type_error_key():
631
                paddle.static.nn.switch_case(
632 633
                    branch_index=key_int32, branch_fns=[(2.3, 2)], default=fn_3
                )
L
liym27 已提交
634 635 636 637 638

            self.assertRaises(TypeError, type_error_key)

            # The key in 'branch_fns' must be unique
            def value_error_key():
639
                paddle.static.nn.switch_case(
640 641 642 643
                    branch_index=key_int32,
                    branch_fns=[(2, fn_1), (2, fn_2)],
                    default=fn_3,
                )
L
liym27 已提交
644 645 646 647 648

            self.assertRaises(ValueError, value_error_key)

            # The type of function in 'branch_fns' must be callable
            def type_error_fn():
649
                paddle.static.nn.switch_case(
650 651 652 653
                    branch_index=key_int32,
                    branch_fns=[(1, 1), (2, fn_2)],
                    default=fn_3,
                )
L
liym27 已提交
654 655 656 657 658

            self.assertRaises(TypeError, type_error_fn)

            # The default in Op(case) must be callable
            def type_error_default():
659
                paddle.static.nn.switch_case(
660 661 662 663
                    branch_index=key_int32,
                    branch_fns=[(1, fn_1), (2, fn_2)],
                    default=1,
                )
L
liym27 已提交
664 665 666 667 668 669

            self.assertRaises(TypeError, type_error_default)


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