test_while_loop_op.py 23.8 KB
Newer Older
G
guofei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2018 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 18
import numpy as np

19
import paddle
20
import paddle.nn.functional as F
21
from paddle import fluid
22
from paddle.fluid import core
23
from paddle.fluid.backward import append_backward
24
from paddle.fluid.framework import Program, program_guard
G
guofei 已提交
25

26 27
paddle.enable_static()

G
guofei 已提交
28 29 30 31

class TestApiWhileLoop(unittest.TestCase):
    def test_var_tuple(self):
        def cond(i):
L
LiYuRio 已提交
32
            return paddle.less_than(i, ten)
G
guofei 已提交
33 34

        def body(i):
35
            return paddle.add(x=i, y=one)
G
guofei 已提交
36 37 38 39

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
40 41 42 43 44
            i = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=0)
            one = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
            ten = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=10
            )
45
            out = paddle.static.nn.while_loop(cond, body, (i,))
G
guofei 已提交
46

47 48 49 50 51
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
G
guofei 已提交
52 53
        exe = fluid.Executor(place)
        res = exe.run(main_program, fetch_list=out)
54 55 56
        np.testing.assert_allclose(
            np.asarray(res[0]), np.full(1, 10, np.int64), rtol=1e-05
        )
G
guofei 已提交
57 58 59

    def test_var_list(self):
        def cond(i, mem):
L
LiYuRio 已提交
60
            return paddle.less_than(i, ten)
G
guofei 已提交
61 62

        def body(i, mem):
63
            mem = paddle.add(x=mem, y=one)
64
            i = paddle.increment(i)
G
guofei 已提交
65 66 67 68 69
            return [i, mem]

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
70
            i = paddle.zeros(shape=[1], dtype='int64')
71 72 73
            ten = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=10
            )
74
            mem = paddle.static.data(name='mem', shape=[10], dtype='float32')
75 76 77
            one = paddle.tensor.fill_constant(
                shape=[10], dtype='float32', value=1
            )
78
            out = paddle.static.nn.while_loop(cond, body, [i, mem])
G
guofei 已提交
79 80 81 82

            data = np.random.rand(10).astype('float32')
            data_one = np.ones(10).astype('float32')

83 84 85 86 87
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
G
guofei 已提交
88 89 90 91
        exe = fluid.Executor(place)
        res = exe.run(main_program, feed={'mem': data}, fetch_list=out)
        for i in range(10):
            data = np.add(data, data_one)
92
        np.testing.assert_allclose(np.asarray(res[1]), data, rtol=1e-05)
G
guofei 已提交
93

94
    def test_var_dict(self):
95
        def cond(i, ten, test_dict, test_list, test_list_dict):
L
LiYuRio 已提交
96
            return paddle.less_than(i, ten)
97

98 99 100 101
        def body(i, ten, test_dict, test_list, test_list_dict):
            test_dict["test_key"] = i
            test_dict["test_key"] += 1

102
            test_list[0] = paddle.reshape(test_list[0], [2, -1]) + 1
103 104

            test_list_dict[0]["test_key"] += 1
105
            test_list_dict[0]["test_key"] = F.relu(
106 107
                test_list_dict[0]["test_key"]
            )
108

109
            i = paddle.increment(i)
110
            return [i, ten, test_dict, test_list, test_list_dict]
111 112 113 114

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
115
            i = paddle.zeros(shape=[1], dtype='int64')
116 117 118 119 120 121
            ten = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=10
            )
            test_data = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=0
            )
122

123
            test_dict = {"test_key": test_data}
124
            test_list = [
125 126 127
                paddle.tensor.fill_constant(
                    shape=[1, 2], dtype='int64', value=0
                )
128
            ]
129 130
            test_list_dict = [
                {
131
                    "test_key": paddle.tensor.fill_constant(
132 133 134 135
                        shape=[1], dtype='float32', value=0
                    )
                }
            ]
136

137 138 139 140 141 142 143
            (
                i,
                ten,
                test_dict,
                test_list,
                test_list_dict,
            ) = paddle.static.nn.while_loop(
144 145 146 147 148 149 150
                cond, body, [i, ten, test_dict, test_list, test_list_dict]
            )
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
151
        exe = fluid.Executor(place)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        res = exe.run(
            main_program,
            fetch_list=[
                test_dict["test_key"],
                test_list[0],
                test_list_dict[0]["test_key"],
            ],
        )
        np.testing.assert_allclose(
            np.asarray(res[0]),
            np.full(shape=1, fill_value=10, dtype=np.int64),
            rtol=1e-05,
        )
        np.testing.assert_allclose(
            np.asarray(res[1]),
            np.full(shape=(2, 1), fill_value=10, dtype=np.int64),
            rtol=1e-05,
        )
        np.testing.assert_allclose(
            np.asarray(res[2]),
            np.full(shape=1, fill_value=10, dtype=np.float32),
            rtol=1e-05,
        )
175

G
guofei 已提交
176 177 178 179

class TestApiWhileLoop_Nested(unittest.TestCase):
    def test_nested_net(self):
        def external_cond(i, j, init, sums):
L
LiYuRio 已提交
180
            return paddle.less_than(i, loop_len1)
G
guofei 已提交
181 182 183

        def external_body(i, j, init, sums):
            def internal_cond(j, init, sums):
L
LiYuRio 已提交
184
                return paddle.less_than(j, loop_len2)
G
guofei 已提交
185 186

            def internal_body(j, init, sums):
187 188
                init = paddle.add(x=init, y=ones)
                sums = paddle.add(x=init, y=sums)
189
                j = paddle.increment(j)
G
guofei 已提交
190 191
                return [j, init, sums]

192
            result = paddle.static.nn.while_loop(
193 194
                internal_cond, internal_body, [j, init, sums]
            )
G
guofei 已提交
195 196 197
            j = result[0]
            init = result[1]
            sums = result[2]
198
            sums = paddle.add(x=init, y=sums)
199
            i = paddle.increment(i)
G
guofei 已提交
200 201 202 203 204
            return [i, j, init, sums]

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
205 206
            i = paddle.zeros(shape=[1], dtype='int64')
            j = paddle.zeros(shape=[1], dtype='int64')
207 208 209 210 211 212
            init = paddle.static.data(
                name='init', shape=[3, 3], dtype='float32'
            )
            sums = paddle.static.data(
                name='sums', shape=[3, 3], dtype='float32'
            )
213 214 215 216 217 218 219 220 221
            loop_len1 = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=2
            )
            loop_len2 = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=3
            )
            ones = paddle.tensor.fill_constant(
                shape=[3, 3], dtype='float32', value=1
            )
G
guofei 已提交
222

223
            out = paddle.static.nn.while_loop(
224 225
                external_cond, external_body, [i, j, init, sums]
            )
G
guofei 已提交
226 227 228 229

            data = np.random.rand(3, 3).astype('float32')
            data_sums = np.zeros([3, 3]).astype('float32')

230 231 232 233 234
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
G
guofei 已提交
235
        exe = fluid.Executor(place)
236 237 238
        res = exe.run(
            main_program, feed={'init': data, 'sums': data_sums}, fetch_list=out
        )
G
guofei 已提交
239 240 241 242 243
        for i in range(3):
            data = np.add(data, 1)
            data_sums = np.add(data, data_sums)
        for j in range(2):
            data_sums = np.add(data, data_sums)
244
        np.testing.assert_allclose(np.asarray(res[3]), data_sums, rtol=1e-05)
245 246 247 248 249


class TestApiWhileLoop_Backward(unittest.TestCase):
    def test_while_loop_backward(self):
        def cond(i, x):
L
LiYuRio 已提交
250
            return paddle.less_than(i, eleven)
251

252
        def body(i, x):
253
            x = paddle.multiply(x=i, y=i)
254
            i = paddle.increment(i)
255
            return [i, x]
256 257 258 259

        main_program = Program()
        startup_program = Program()
        with fluid.program_guard(main_program, startup_program):
260
            i = paddle.static.data(name='i', shape=[1], dtype='float32')
261
            i.stop_gradient = False
262 263 264 265 266 267
            eleven = paddle.tensor.fill_constant(
                shape=[1], dtype='float32', value=11
            )
            one = paddle.tensor.fill_constant(
                shape=[1], dtype='float32', value=1
            )
268
            x = paddle.static.data(name='x', shape=[1], dtype='float32')
269 270
            x.stop_gradient = False

271
            out = paddle.static.nn.while_loop(cond, body, [i, x])
272
            mean = paddle.mean(out[1])
273 274
            append_backward(mean)

275 276 277 278 279
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
280 281 282 283 284 285 286
        exe = fluid.Executor(place)

        feed_i = np.ones(1).astype('float32')
        feed_x = np.ones(1).astype('float32')
        data = np.asarray([100]).astype('float32')
        i_grad = np.asarray([110]).astype('float32')

287 288 289 290 291
        res = exe.run(
            main_program,
            feed={'i': feed_i, 'x': feed_x},
            fetch_list=[mean.name, i.grad_name],
        )
292 293
        np.testing.assert_allclose(np.asarray(res[0]), data, rtol=1e-05)
        np.testing.assert_allclose(np.asarray(res[1]), i_grad, rtol=1e-05)
294 295 296

    def test_while_loop_backward2(self):
        def cond(i, x):
297
            return i < 3
298 299

        def body(i, x):
300
            x = x * i
301 302 303 304 305 306
            i = i + 1
            return [i, x]

        main_program = Program()
        startup_program = Program()
        with fluid.program_guard(main_program, startup_program):
307
            i = paddle.static.data(name='i', shape=[1], dtype='float32')
308
            i.stop_gradient = False
309
            x = paddle.static.data(name='x', shape=[1], dtype='float32')
310 311
            x.stop_gradient = False

312
            out = paddle.static.nn.while_loop(cond, body, [i, x])
313
            mean = paddle.mean(out[1])
314 315
            append_backward(mean)

316 317 318 319 320
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
321 322 323 324
        exe = fluid.Executor(place)

        feed_i = np.ones(1).astype('float32')
        feed_x = np.ones(1).astype('float32')
325 326 327
        data = np.asarray([2]).astype('float32')
        i_grad = np.asarray([3]).astype('float32')
        x_grad = np.asarray([2]).astype('float32')
328

329 330 331 332 333
        res = exe.run(
            main_program,
            feed={'i': feed_i, 'x': feed_x},
            fetch_list=[mean.name, i.grad_name, x.grad_name],
        )
334 335 336
        np.testing.assert_allclose(np.asarray(res[0]), data, rtol=1e-05)
        np.testing.assert_allclose(np.asarray(res[1]), i_grad, rtol=1e-05)
        np.testing.assert_allclose(np.asarray(res[2]), x_grad, rtol=1e-05)
337 338


339 340 341
class TestApiWhileLoop_NestedWithBackwardAndLoDTensorArray(unittest.TestCase):
    def test_nested_net_with_backward_and_lodtensor(self):
        def external_cond(i, j, x, mem_array):
L
LiYuRio 已提交
342
            return paddle.less_than(i, array_len)
343 344 345

        def external_body(i, j, x, mem_array):
            def internal_cond(j, x, mem_array):
L
LiYuRio 已提交
346
                return paddle.less_than(j, array_len2)
347 348

            def internal_body(j, x, mem_array):
349 350
                inner_data = paddle.tensor.array_read(array=data_array, i=j)
                inner_prev = paddle.tensor.array_read(array=mem_array, i=j)
351 352
                inner_sum_0 = paddle.add(x=inner_data, y=inner_prev)
                inner_sum_1 = paddle.add(x=x, y=inner_sum_0)
353
                j = paddle.increment(x=j)
354
                paddle.tensor.array_write(inner_sum_1, i=j, array=mem_array)
355 356
                return [j, x, mem_array]

357 358
            outer_data = paddle.tensor.array_read(array=data_array, i=i)
            outer_prev = paddle.tensor.array_read(array=mem_array, i=i)
359 360
            outer_sum_0 = paddle.add(x=outer_data, y=outer_prev)
            outer_sum_1 = paddle.add(x=x, y=outer_sum_0)
361
            i = paddle.increment(x=i)
362
            paddle.tensor.array_write(outer_sum_1, i=i, array=mem_array)
363
            j, x, mem_array = paddle.static.nn.while_loop(
364 365
                internal_cond, internal_body, [j, x, mem_array]
            )
366
            return [i, j, x, mem_array]
367 368 369 370

        main_program = Program()
        startup_program = Program()
        with fluid.program_guard(main_program, startup_program):
371 372 373 374
            d0 = paddle.static.data(name='d0', shape=[10], dtype='float32')
            d1 = paddle.static.data(name='d1', shape=[10], dtype='float32')
            d2 = paddle.static.data(name='d2', shape=[10], dtype='float32')
            x = paddle.static.data(name='x', shape=[10], dtype='float32')
375
            x.stop_gradient = False
376
            i = paddle.zeros(shape=[1], dtype='int64')
377
            i.stop_gradient = True
378
            init = paddle.zeros(shape=[10], dtype='float32')
379 380
            mem_array = paddle.tensor.array_write(x=init, i=i)
            data_array = paddle.tensor.array_write(x=d0, i=i)
381
            mem_array.stop_gradient = False
382
            i = paddle.increment(i)
383
            paddle.tensor.array_write(d1, i, array=data_array)
384
            i = paddle.increment(i)
385
            paddle.tensor.array_write(d2, i, array=data_array)
386
            i = paddle.zeros(shape=[1], dtype='int64')
387
            i.stop_gradient = True
388 389 390 391
            array_len = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=1
            )
            j = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
392
            j.stop_gradient = True
393 394 395
            array_len2 = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=3
            )
396

397
            out = paddle.static.nn.while_loop(
398 399
                external_cond, external_body, [i, j, x, mem_array]
            )
400

401
            sum_result = paddle.tensor.array_read(array=mem_array, i=j)
402
            mean = paddle.mean(sum_result)
403
            append_backward(mean)
404

405 406 407 408 409
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
410 411 412 413 414 415 416 417
            exe = fluid.Executor(place)

            d = []
            for i in range(3):
                d.append(np.random.random(size=[10]).astype('float32'))
            feed_x = np.ones(10).astype('float32')
            data_sum = d[0] + d[1] + d[2] + 3 * feed_x
            x_grad = [0.3] * 10
418 419 420 421 422
            res = exe.run(
                main_program,
                feed={'d0': d[0], 'd1': d[1], 'd2': d[2], 'x': feed_x},
                fetch_list=[sum_result.name, x.grad_name],
            )
423 424
            np.testing.assert_allclose(res[0], data_sum, rtol=1e-05)
            np.testing.assert_allclose(res[1], x_grad, rtol=1e-05)
425 426 427 428 429


class TestApiWhileLoopWithSwitchCase(unittest.TestCase):
    def test_with_switch_case(self):
        def cond(i):
L
LiYuRio 已提交
430
            return paddle.less_than(i, ten)
431 432 433

        def body(i):
            def fn_add_three():
434
                data_add_three = paddle.add(x=i, y=three)
435 436 437
                return data_add_three

            def fn_square():
438
                data_mul_data = paddle.multiply(x=i, y=i)
439 440 441
                return data_mul_data

            def fn_add_one():
442
                data_add_one = paddle.add(x=i, y=one)
443 444
                return data_add_one

445
            return paddle.static.nn.switch_case(
446 447 448 449
                branch_index=i,
                branch_fns={2: fn_add_three, 5: fn_square},
                default=fn_add_one,
            )
450 451 452 453

        main_program = Program()
        startup_program = Program()
        with fluid.program_guard(main_program, startup_program):
454 455 456 457 458 459 460 461
            i = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
            ten = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=10
            )
            three = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=3
            )
            one = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
462
            out = paddle.static.nn.while_loop(cond, body, [i])
463

464 465 466 467 468
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
469 470 471 472
        exe = fluid.Executor(place)
        res = exe.run(main_program, fetch_list=out)

        data = np.asarray([25]).astype('int64')
473
        np.testing.assert_allclose(np.asarray(res[0]), data, rtol=1e-05)
G
guofei 已提交
474 475 476 477 478 479 480 481


class TestApiWhileLoop_Error(unittest.TestCase):
    def test_error(self):
        def cond_returns_constant(i):
            return 1

        def cond_returns_not_bool_tensor(i):
482
            return paddle.increment(i)
G
guofei 已提交
483 484

        def cond_returns_bool_tensor(i):
L
LiYuRio 已提交
485
            return paddle.less_than(i, ten)
G
guofei 已提交
486 487

        def cond_returns_2d_tensor(i):
L
LiYuRio 已提交
488
            return paddle.less_than(i, ten_2d)
G
guofei 已提交
489

490
        def cond_receives_two_args(i, ten):
L
LiYuRio 已提交
491
            return paddle.less_than(i, ten)
492

G
guofei 已提交
493
        def body(i):
494
            return paddle.increment(i)
G
guofei 已提交
495

496
        def body_returns_error_length(i):
497
            i = paddle.increment(i)
498 499 500
            return [i, i]

        def body_returns_error_type(i, ten):
501
            return paddle.increment(i)
502

503 504 505 506
        def cond_returns_with_mutable_dict(i, test_dict):
            return i > 0

        def body_returns_with_mutable_dict(i, test_dict):
507
            test_dict['new_key'] = paddle.tensor.fill_constant(
508 509
                shape=[1], dtype='int64', value=1
            )
510
            return paddle.increment(i), test_dict
511 512 513 514 515 516

        def cond_returns_with_mutable_list(i, test_list):
            return i > 0

        def body_returns_with_mutable_list(i, test_list):
            test_list.append(
517
                paddle.tensor.fill_constant(shape=[1], dtype='int64', value=1)
518
            )
519
            return paddle.increment(i), test_list
520

G
guofei 已提交
521 522 523
        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
            data = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=1
            )
            data_1d = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=1
            )
            data_2d = paddle.tensor.fill_constant(
                shape=[2, 2], dtype='int64', value=1
            )
            ten = paddle.tensor.fill_constant(
                shape=[1], dtype='int64', value=10
            )
            ten_2d = paddle.tensor.fill_constant(
                shape=[2, 2], dtype='int64', value=10
            )
G
guofei 已提交
539

540
            # The type of `cond` in Op(while_loop) must be callable
G
guofei 已提交
541
            def type_error_cond():
542
                out = paddle.static.nn.while_loop(data, body, [data_1d])
G
guofei 已提交
543 544 545 546 547

            self.assertRaises(TypeError, type_error_cond)

            # The type of `body` in Op(while_loop) must be callable
            def type_error_body():
548
                out = paddle.static.nn.while_loop(
549 550
                    cond_returns_bool_tensor, data, [data_1d]
                )
G
guofei 已提交
551 552 553 554 555

            self.assertRaises(TypeError, type_error_body)

            # The type of `loop_vars` in Op(while_loop) must be list or tuple
            def type_error_loop_vars():
556 557 558
                out = paddle.static.nn.while_loop(
                    cond_returns_bool_tensor, body, data_1d
                )
G
guofei 已提交
559 560 561 562 563

            self.assertRaises(TypeError, type_error_loop_vars)

            # The value of `loop_vars` is empty
            def value_error_loop_vars():
564 565 566
                out = paddle.static.nn.while_loop(
                    cond_returns_bool_tensor, body, []
                )
G
guofei 已提交
567 568 569 570 571

            self.assertRaises(ValueError, value_error_loop_vars)

            # The type of `cond` returns in Op(while_loop) must be Variable
            def type_error_cond_returns_not_variable():
572 573 574
                out = paddle.static.nn.while_loop(
                    cond_returns_constant, body, [data_1d]
                )
G
guofei 已提交
575 576 577 578 579

            self.assertRaises(TypeError, type_error_cond_returns_not_variable)

            # The type of `cond` returns in Op(while_loop) must be a bollean variable
            def type_error_cond_returns_not_boolean():
580
                out = paddle.static.nn.while_loop(
581 582
                    cond_returns_not_bool_tensor, body, [data_1d]
                )
G
guofei 已提交
583 584 585 586 587

            self.assertRaises(TypeError, type_error_cond_returns_not_boolean)

            # The shape of `cond` returns in Op(while_loop) must be 1
            def type_error_shape_cond_returns_2d():
588 589 590
                out = paddle.static.nn.while_loop(
                    cond_returns_2d_tensor, body, [data_2d]
                )
G
guofei 已提交
591 592 593

            self.assertRaises(TypeError, type_error_shape_cond_returns_2d)

594 595
            # The length of `body` returns in Op(while_loop) must be same as `loop_vars`
            def value_error_body_returns_error_length():
596
                out = paddle.static.nn.while_loop(
597 598
                    cond_returns_bool_tensor, body_returns_error_length, [data]
                )
599 600 601 602 603

            self.assertRaises(ValueError, value_error_body_returns_error_length)

            # The type of `body` returns in Op(while_loop) must be same as `loop_vars`
            def value_error_body_returns_error_type():
604
                out = paddle.static.nn.while_loop(
605 606
                    cond_receives_two_args, body_returns_error_type, [data, ten]
                )
607 608 609

            self.assertRaises(ValueError, value_error_body_returns_error_type)

610 611 612
            # The length of `output_vars` with mutable value should keep same with `loop_vars`
            def value_error_body_returns_with_mutable_dict():
                test_dict = {
613
                    "int_constant": paddle.tensor.fill_constant(
614 615
                        shape=[2, 2], dtype='int64', value=1
                    )
616
                }
617
                out = paddle.static.nn.while_loop(
618 619 620 621
                    cond_returns_with_mutable_dict,
                    body_returns_with_mutable_dict,
                    [data, test_dict],
                )
622

623 624 625
            self.assertRaises(
                ValueError, value_error_body_returns_with_mutable_dict
            )
626 627 628

            def value_error_body_returns_with_mutable_list():
                test_list = [
629 630 631
                    paddle.tensor.fill_constant(
                        shape=[2, 2], dtype='int64', value=1
                    )
632
                ]
633
                out = paddle.static.nn.while_loop(
634 635 636 637
                    cond_returns_with_mutable_list,
                    body_returns_with_mutable_list,
                    [data, test_list],
                )
638

639 640 641
            self.assertRaises(
                ValueError, value_error_body_returns_with_mutable_list
            )
642

G
guofei 已提交
643

644 645 646 647 648 649 650 651 652 653 654 655 656
class TestApiWhileLoopSliceInBody(unittest.TestCase):
    def test_var_slice(self):
        def cond(z, i):
            return i + 1 <= x_shape[0]

        def body(z, i):
            z = z + x[i]
            i += 1
            return z, i

        main_program = Program()
        startup_program = Program()
        with program_guard(main_program, startup_program):
G
GGBond8488 已提交
657
            x = paddle.static.data(name='x', shape=[-1, 5], dtype='int32')
658
            z = paddle.tensor.fill_constant([1], 'int32', 0)
2
201716010711 已提交
659
            x_shape = paddle.shape(x)
660
            i = paddle.tensor.fill_constant([1], 'int32', 0)
661
            z, _ = paddle.static.nn.while_loop(cond, body, [z, i])
662

663 664 665 666 667
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
668 669 670 671
        exe = fluid.Executor(place)

        np_x = np.array([1, 2, 3, 4, 5], dtype='int32')
        res = exe.run(main_program, feed={'x': np_x}, fetch_list=[z])
672
        np.testing.assert_array_equal(res[0], [np.sum(np_x)])
673 674


G
guofei 已提交
675 676
if __name__ == '__main__':
    unittest.main()