test_ifelse.py 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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

17
import numpy as np
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
from ifelse_simple_func import (
    NetWithControlFlowIf,
    add_fn,
    dyfunc_empty_nonlocal,
    dyfunc_ifelse_ret_int1,
    dyfunc_ifelse_ret_int2,
    dyfunc_ifelse_ret_int3,
    dyfunc_ifelse_ret_int4,
    dyfunc_with_if_else,
    dyfunc_with_if_else2,
    dyfunc_with_if_else3,
    dyfunc_with_if_else_with_list_geneator,
    fluid,
    if_tensor_case,
    if_with_and_or,
    if_with_and_or_1,
    if_with_and_or_2,
    if_with_and_or_3,
    if_with_and_or_4,
    if_with_class_var,
    loss_fn,
    nested_if_else,
    nested_if_else_2,
    nested_if_else_3,
)
43

44
import paddle
45
import paddle.nn.functional as F
46
from paddle.fluid import core
47
from paddle.jit.dy2static.utils import Dygraph2StaticException
48

49 50
np.random.seed(1)

51 52 53 54
if fluid.is_compiled_with_cuda():
    place = fluid.CUDAPlace(0)
else:
    place = fluid.CPUPlace()
55

56

57 58 59 60 61 62 63 64 65
class TestDy2staticException(unittest.TestCase):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = None
        self.error = "Your if/else have different number of return value."

    def test_error(self):
        if self.dyfunc:
            with self.assertRaisesRegex(Dygraph2StaticException, self.error):
R
Ryan 已提交
66
                paddle.jit.enable_to_static(True)
H
hjyp 已提交
67
                self.assertTrue(paddle.jit.to_static(self.dyfunc)(self.x))
68
        paddle.fluid.dygraph.base.global_var._in_declarative_mode_ = False
R
Ryan 已提交
69
        paddle.jit.enable_to_static(False)
70 71


72 73 74 75 76 77 78 79 80 81 82
class TestDygraphIfElse(unittest.TestCase):
    """
    TestCase for the transformation from control flow `if/else`
    dependent on tensor in Dygraph into Static `fluid.layers.cond`.
    """

    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_with_if_else

    def _run_static(self):
83 84 85
        return self._run_dygraph(to_static=True)

    def _run_dygraph(self, to_static=False):
86

87
        with fluid.dygraph.guard(place):
88
            x_v = fluid.dygraph.to_variable(self.x)
89
            if to_static:
H
hjyp 已提交
90
                ret = paddle.jit.to_static(self.dyfunc)(x_v)
91 92
            else:
                ret = self.dyfunc(x_v)
93 94 95 96 97 98 99 100 101 102 103 104 105
            return ret.numpy()

    def test_ast_to_func(self):
        self.assertTrue((self._run_dygraph() == self._run_static()).all())


class TestDygraphIfElse2(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_with_if_else2


class TestDygraphIfElse3(TestDygraphIfElse):
106 107 108 109 110
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_with_if_else3


111 112 113 114 115 116
class TestDygraphIfElse4(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_empty_nonlocal


117 118 119 120 121 122
class TestDygraphIfElseWithListGenerator(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_with_if_else_with_list_geneator


123
class TestDygraphNestedIfElse(TestDygraphIfElse):
124 125 126
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = nested_if_else
127 128


129
class TestDygraphNestedIfElse2(TestDygraphIfElse):
130 131 132 133 134
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = nested_if_else_2


135
class TestDygraphNestedIfElse3(TestDygraphIfElse):
136 137 138 139 140
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = nested_if_else_3


141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
def dyfunc_ifExp_with_while(x):
    y = [x]

    def add_fn(x):
        x = x + 1
        return x

    def cond(i, ten, y):
        return i < ten

    def map_func(func, tensor_list):
        return [func(x) for x in tensor_list]

    def body(i, ten, y):
        # It will be converted into `layers.cond` as followed.
156
        # map_func(lambda x: paddle.static.nn.cond(i==0, lambda: x, lambda: add_fn(x), y)
157
        y = map_func(lambda x: x if (i == 0) is not None else add_fn(x), y)
158 159 160
        i += 1
        return [i, ten, y]

161 162
    i = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=0)
    ten = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=10)
163
    i, ten, y = paddle.static.nn.while_loop(cond, body, [i, ten, y])
164 165 166 167 168 169 170 171 172
    return y[0]


class TestDygraphIfElse6(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_ifExp_with_while


173
def dyfunc_ifExp(x):
174 175 176 177 178 179 180 181 182
    y = [x]

    def add_fn(x):
        x = x + 1
        return x

    def map_func(func, tensor_list):
        return [func(x) for x in tensor_list]

183
    i = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=0)
184
    # It will be converted into `layers.cond` as followed.
185
    # map_func(lambda x: paddle.static.nn.cond(i==1, lambda: x, lambda: add_fn(x), y)
186 187
    # `if (Tensor) == 1` is supported in dygraph.
    y = map_func(lambda x: x if i == 1 else add_fn(x), y)
188 189 190 191 192 193
    return y[0]


class TestDygraphIfElse7(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
194
        self.dyfunc = dyfunc_ifExp
195 196


197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
class TestDygraphIfElseWithAndOr(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_and_or


class TestDygraphIfElseWithAndOr1(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_and_or_1


class TestDygraphIfElseWithAndOr2(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_and_or_2


class TestDygraphIfElseWithAndOr3(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_and_or_3


class TestDygraphIfElseWithAndOr4(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_and_or_4
225 226


227 228 229 230 231 232
class TestDygraphIfElseWithClassVar(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_with_class_var


233 234 235 236 237 238
class TestDygraphIfTensor(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = if_tensor_case


239 240 241 242 243 244 245 246 247 248 249
class TestDygraphIfElseNet(unittest.TestCase):
    """
    TestCase for the transformation from control flow `if/else`
    dependent on tensor in Dygraph into Static `fluid.layers.cond`.
    """

    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.Net = NetWithControlFlowIf

    def _run_static(self):
250
        return self._run(to_static=True)
251 252

    def _run_dygraph(self):
253 254 255
        return self._run(to_static=False)

    def _run(self, to_static=False):
R
Ryan 已提交
256
        paddle.jit.enable_to_static(to_static)
257

258 259 260 261 262 263 264 265 266 267
        with fluid.dygraph.guard(place):
            net = self.Net()
            x_v = fluid.dygraph.to_variable(self.x)
            ret = net(x_v)
            return ret.numpy()

    def test_ast_to_func(self):
        self.assertTrue((self._run_dygraph() == self._run_static()).all())


268 269
# Test to call function ahead caller.
def relu(x):
270
    return F.relu(x)
271 272


273
def call_external_func(x, label=None):
274
    if paddle.mean(x) < 0:
275 276 277 278
        x_v = x - 1
    else:
        x_v = add_fn(x)

279
    x_v = relu(x_v)
280 281 282 283 284 285 286 287 288 289 290 291
    if label is not None:
        loss = loss_fn(x_v, label)
        return loss
    return x_v


class TestAst2FuncWithExternalFunc(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = call_external_func


292
class NetWithExternalFunc(paddle.nn.Layer):
H
hjyp 已提交
293
    @paddle.jit.to_static
294
    def forward(self, x, label=None):
295
        if paddle.mean(x) < 0:
296 297 298 299
            x_v = x - 1
        else:
            x_v = add_fn(x)

300
        x_v = softmax(x_v)
301 302 303 304 305 306
        if label is not None:
            loss = loss_fn(x_v, label)
            return loss
        return x_v


307 308
# Test to call function behind caller.
def softmax(x):
309
    return paddle.nn.functional.softmax(x)
310 311


312 313 314 315 316 317
class TestNetWithExternalFunc(TestDygraphIfElseNet):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.Net = NetWithExternalFunc


318 319
class DiffModeNet1(paddle.nn.Layer):
    def __init__(self, mode):
320
        super().__init__()
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        self.mode = mode

    @paddle.jit.to_static
    def forward(self, x, y):
        if self.mode == 'train':
            out = x + y
        elif self.mode == 'infer':
            out = x - y
        else:
            raise ValueError('Illegal mode')
        return out


class DiffModeNet2(paddle.nn.Layer):
    def __init__(self, mode):
336
        super().__init__()
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        self.mode = mode

    @paddle.jit.to_static
    def forward(self, x, y):
        if self.mode == 'train':
            out = x + y
            return out
        elif self.mode == 'infer':
            out = x - y
            return out
        else:
            raise ValueError('Illegal mode')


class TestDiffModeNet(unittest.TestCase):
    """
    TestCase for the net with different modes
    """

    def setUp(self):
        self.x = paddle.randn([10, 16], 'float32')
        self.y = paddle.randn([10, 16], 'float32')
        self.init_net()

    def init_net(self):
        self.Net = DiffModeNet1

    def _run(self, mode, to_static):
R
Ryan 已提交
365
        paddle.jit.enable_to_static(to_static)
366 367 368 369 370 371

        net = self.Net(mode)
        ret = net(self.x, self.y)
        return ret.numpy()

    def test_train_mode(self):
372
        self.assertTrue(
373 374 375 376 377
            (
                self._run(mode='train', to_static=True)
                == self._run(mode='train', to_static=False)
            ).all()
        )
378 379

    def test_infer_mode(self):
380
        self.assertTrue(
381 382 383 384 385
            (
                self._run(mode='infer', to_static=True)
                == self._run(mode='infer', to_static=False)
            ).all()
        )
386 387 388 389 390 391 392


class TestDiffModeNet2(TestDiffModeNet):
    def init_net(self):
        self.Net = DiffModeNet2


393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
class TestNewVarCreateInOneBranch(unittest.TestCase):
    def test_var_used_in_another_for(self):
        def case_func(training):
            # targets and targets_list is dynamically defined by training
            if training:
                targets = [1, 2, 3]
                targets_list = [targets]

            num_step = 3
            for i in range(num_step):
                if i > 0:
                    rois, rosi_num = 1, 2
                    # targets is in loop_vars.
                    if training:
                        ros, rosi_num, targets = -1, -2, [-1, -2, -3]
                        targets_list.append(targets)

            return rosi_num

        self.assertEqual(paddle.jit.to_static(case_func)(False), 2)
        self.assertEqual(paddle.jit.to_static(case_func)(True), -2)


416 417 418 419 420 421 422
class TestDy2StIfElseRetInt1(unittest.TestCase):
    def setUp(self):
        self.x = np.random.random([5]).astype('float32')
        self.dyfunc = dyfunc_ifelse_ret_int1
        self.out = self.get_dy2stat_out()

    def get_dy2stat_out(self):
R
Ryan 已提交
423
        paddle.jit.enable_to_static(True)
424 425
        static_func = paddle.jit.to_static(self.dyfunc)
        out = static_func(self.x)
R
Ryan 已提交
426
        paddle.jit.enable_to_static(False)
427 428 429
        return out

    def test_ast_to_func(self):
430
        self.assertIsInstance(self.out[0], (paddle.Tensor, core.eager.Tensor))
431 432 433
        self.assertIsInstance(self.out[1], int)


434
class TestDy2StIfElseRetInt2(TestDy2staticException):
435 436
    def setUp(self):
        self.x = np.random.random([5]).astype('float32')
437
        self.error = "Your if/else have different number of return value."
438 439 440 441 442 443 444 445 446 447
        self.dyfunc = dyfunc_ifelse_ret_int2


class TestDy2StIfElseRetInt3(TestDy2StIfElseRetInt1):
    def setUp(self):
        self.x = np.random.random([5]).astype('float32')
        self.dyfunc = dyfunc_ifelse_ret_int3
        self.out = self.get_dy2stat_out()

    def test_ast_to_func(self):
448
        self.assertIsInstance(self.out, (paddle.Tensor, core.eager.Tensor))
449 450 451 452 453 454 455 456


class TestDy2StIfElseRetInt4(TestDy2StIfElseRetInt1):
    def setUp(self):
        self.x = np.random.random([5]).astype('float32')
        self.dyfunc = dyfunc_ifelse_ret_int4

    def test_ast_to_func(self):
R
Ryan 已提交
457
        paddle.jit.enable_to_static(True)
458
        with self.assertRaises(Dygraph2StaticException):
459 460
            static_func = paddle.jit.to_static(self.dyfunc)
            out = static_func(self.x)
461 462 463 464
        # Why need set `_in_declarative_mode_` here?
        # In Dy2St we use `with _switch_declarative_mode_guard_()` to indicate
        # that the code block is under @to_static, but in this UT
        # an exception is thrown during Dy2St, making the `_in_declarative_mode_`
465
        # a wrong value. So We need set `_in_declarative_mode_` to False manually.
466
        paddle.fluid.dygraph.base.global_var._in_declarative_mode_ = False
R
Ryan 已提交
467
        paddle.jit.enable_to_static(False)
468 469


470 471
class IfElseNet(paddle.nn.Layer):
    def __init__(self):
472
        super().__init__()
473 474 475
        self.param = self.create_parameter(
            shape=[3, 2], dtype='float32', is_bias=False
        )
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

    @paddle.jit.to_static
    def forward(self, a, b, c):
        a = paddle.matmul(a, self.param)
        a = paddle.reshape(a, (2, 4))
        cond = paddle.to_tensor([10])
        if cond == 10:
            a_argmax = a.argmax(axis=-1)
            b = b + self.param
        else:
            print(c)
        return b


class TestDy2StIfElseBackward(unittest.TestCase):
    def test_run_backward(self):
        a = paddle.randn((4, 3), dtype='float32')
        a.stop_gradient = False
        b = paddle.to_tensor([10]).astype('float32')
        b.stop_gradient = False
        c = paddle.to_tensor([2])
        c.stop_gradient = False

        net = IfElseNet()
        net.train()
        out = net(a, b, c)
        out.backward()
503 504 505
        np.testing.assert_allclose(
            (b + net.param).numpy(), out.numpy(), rtol=1e-05
        )
506 507


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