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
        with fluid.dygraph.guard(place):
87
            x_v = fluid.dygraph.to_variable(self.x)
88
            if to_static:
H
hjyp 已提交
89
                ret = paddle.jit.to_static(self.dyfunc)(x_v)
90 91
            else:
                ret = self.dyfunc(x_v)
92 93 94 95 96 97 98 99 100 101 102 103 104
            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):
105 106 107 108 109
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
        self.dyfunc = dyfunc_with_if_else3


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


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


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


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


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


140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
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.
155
        # map_func(lambda x: paddle.static.nn.cond(i==0, lambda: x, lambda: add_fn(x), y)
156
        y = map_func(lambda x: x if (i == 0) is not None else add_fn(x), y)
157 158 159
        i += 1
        return [i, ten, y]

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


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


172
def dyfunc_ifExp(x):
173 174 175 176 177 178 179 180 181
    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]

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


class TestDygraphIfElse7(TestDygraphIfElse):
    def setUp(self):
        self.x = np.random.random([10, 16]).astype('float32')
193
        self.dyfunc = dyfunc_ifExp
194 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
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
224 225


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


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


238 239 240 241 242 243 244 245 246 247 248
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):
249
        return self._run(to_static=True)
250 251

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

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

257 258 259 260 261 262 263 264 265 266
        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())


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


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

278
    x_v = relu(x_v)
279 280 281 282 283 284 285 286 287 288 289 290
    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


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

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


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


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


317 318
class DiffModeNet1(paddle.nn.Layer):
    def __init__(self, mode):
319
        super().__init__()
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        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):
335
        super().__init__()
336 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
        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 已提交
364
        paddle.jit.enable_to_static(to_static)
365 366 367 368 369 370

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

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

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


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


392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
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)


415 416 417 418 419 420 421
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 已提交
422
        paddle.jit.enable_to_static(True)
423 424
        static_func = paddle.jit.to_static(self.dyfunc)
        out = static_func(self.x)
R
Ryan 已提交
425
        paddle.jit.enable_to_static(False)
426 427 428
        return out

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


433
class TestDy2StIfElseRetInt2(TestDy2staticException):
434 435
    def setUp(self):
        self.x = np.random.random([5]).astype('float32')
436
        self.error = "Your if/else have different number of return value."
437 438 439 440 441 442 443 444 445 446
        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):
447
        self.assertIsInstance(self.out, (paddle.Tensor, core.eager.Tensor))
448 449 450 451 452 453 454 455


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 已提交
456
        paddle.jit.enable_to_static(True)
457
        with self.assertRaises(Dygraph2StaticException):
458 459
            static_func = paddle.jit.to_static(self.dyfunc)
            out = static_func(self.x)
460 461 462 463
        # 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_`
464
        # a wrong value. So We need set `_in_declarative_mode_` to False manually.
465
        paddle.fluid.dygraph.base.global_var._in_declarative_mode_ = False
R
Ryan 已提交
466
        paddle.jit.enable_to_static(False)
467 468


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

    @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()
502 503 504
        np.testing.assert_allclose(
            (b + net.param).numpy(), out.numpy(), rtol=1e-05
        )
505 506


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