test_for_enumerate.py 15.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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.

15 16
import os
import tempfile
17 18 19
import unittest

import numpy as np
20

21
import paddle
22
from paddle import fluid
23
from paddle.static import InputSpec
24 25


26
# 0. for in range var.numpy()[0]
27
@paddle.jit.to_static
28
def for_in_range(x):
29
    z = paddle.tensor.fill_constant([1], 'int32', 0)
30 31 32 33 34 35
    x = fluid.dygraph.to_variable(x)
    for i in range(x.numpy()[0]):
        z = z + i
    return z


36
# 1. for iter list
37
@paddle.jit.to_static
38
def for_iter_list(x_array):
39
    z = paddle.tensor.fill_constant([1], 'int32', 0)
40 41 42 43 44 45
    for x in x_array:
        z = z + x
    return z


# 2. for enumerate list
46
@paddle.jit.to_static
47
def for_enumerate_list(x_array):
48
    z = paddle.tensor.fill_constant([1], 'int32', 0)
49 50 51 52 53 54
    for i, x in enumerate(x_array):
        z = z + x + i
    return z


# 3. for iter var.numpy()
55
@paddle.jit.to_static
56
def for_iter_var_numpy(x_array):
57
    z = paddle.tensor.fill_constant([1], 'int32', 0)
58 59 60 61 62 63 64
    x_array = fluid.dygraph.to_variable(x_array)
    for x in x_array.numpy():
        z = z + x
    return z


# 4. for enumerate var.numpy()
65
@paddle.jit.to_static
66
def for_enumerate_var_numpy(x_array):
67 68
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
69 70 71 72 73 74 75 76
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy()):
        y = y + i
        z = z + x
    return y, z


# 5. for enumerate var.numpy() with start
77
@paddle.jit.to_static
78
def for_enumerate_var_numpy_with_start(x_array):
79 80
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
81 82 83 84 85 86 87 88
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy(), 1):
        y = y + i
        z = z + x
    return y, z


# 6. for in range with break
89
@paddle.jit.to_static
90
def for_in_range_with_break(x):
91
    z = paddle.tensor.fill_constant([1], 'int32', 0)
92 93 94 95 96 97 98 99 100
    x = fluid.dygraph.to_variable(x)
    for i in range(x.numpy()[0]):
        z = z + i
        if i > 2:
            break
    return z


# 7. for enumerate var.numpy() with break
101
@paddle.jit.to_static
102
def for_enumerate_var_numpy_with_break(x_array):
103 104
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
105 106 107 108 109 110 111 112 113 114
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy()):
        y = y + i
        z = z + x
        if i > 2:
            break
    return y, z


# 8. for enumerate var.numpy() with continue
115
@paddle.jit.to_static
116
def for_enumerate_var_numpy_with_continue(x_array):
117 118
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
119 120 121 122 123 124 125 126 127 128
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy()):
        y = y + i
        if i > 2:
            continue
        z = z + x
    return y, z


# 9. for enumerate var.numpy() with start & break
129
@paddle.jit.to_static
130
def for_enumerate_var_numpy_with_start_break(x_array):
131 132
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
133 134 135 136 137 138 139 140 141 142
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy(), 1):
        y = y + i
        z = z + x
        if i > 2:
            break
    return y, z


# 10. for enumerate var.numpy() with start & continue
143
@paddle.jit.to_static
144
def for_enumerate_var_numpy_with_start_continue(x_array):
145 146
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
147 148 149 150 151 152 153 154 155
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array.numpy(), 1):
        y = y + i
        if i > 2:
            continue
        z = z + x
    return y, z


156
# 11. for iter var
157
@paddle.jit.to_static
158
def for_iter_var(x_array):
159
    z = paddle.tensor.fill_constant([1], 'int32', 0)
160
    x_array = fluid.dygraph.to_variable(x_array)
161

162 163 164 165 166 167
    for x in x_array:
        z = z + x
    return z


# 12. for enumerate var
168
@paddle.jit.to_static
169
def for_enumerate_var(x_array):
170 171
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
172 173 174 175 176 177 178
    x_array = fluid.dygraph.to_variable(x_array)
    for i, x in enumerate(x_array):
        y = y + i
        z = z + x
    return y, z


179
# 13. for iter list[var]
180
@paddle.jit.to_static
181 182 183
def for_iter_var_list(x):
    # 1. prepare data, ref test_list.py
    x = fluid.dygraph.to_variable(x)
184
    iter_num = paddle.tensor.fill_constant(shape=[1], value=5, dtype="int32")
185 186 187 188
    a = []
    for i in range(iter_num):
        a.append(x + i)
    # 2. iter list[var]
189
    y = paddle.tensor.fill_constant([1], 'int32', 0)
190 191 192 193 194 195
    for x in a:
        y = y + x
    return y


# 14. for enumerate list[var]
196
@paddle.jit.to_static
197 198 199
def for_enumerate_var_list(x):
    # 1. prepare data, ref test_list.py
    x = fluid.dygraph.to_variable(x)
200
    iter_num = paddle.tensor.fill_constant(shape=[1], value=5, dtype="int32")
201 202 203 204
    a = []
    for i in range(iter_num):
        a.append(x + i)
    # 2. iter list[var]
205 206
    y = paddle.tensor.fill_constant([1], 'int32', 0)
    z = paddle.tensor.fill_constant([1], 'int32', 0)
207 208 209 210 211 212
    for i, x in enumerate(a):
        y = y + i
        z = z + x
    return y, z


213 214 215
# 15. for enumerate list[var] with a nested for range
@paddle.jit.to_static
def for_enumerate_var_with_nested_range(x_array):
216
    x = paddle.tensor.fill_constant([1], 'int32', 0)
217 218 219 220 221 222 223
    x_array = fluid.dygraph.to_variable(x_array)
    for i, num in enumerate(x_array):
        for idx in range(num):
            x = x + num
    return x


224 225 226
# 16. for iter var[idx]
@paddle.jit.to_static
def for_iter_var_idx(x_array):
227
    z = paddle.tensor.fill_constant([1], 'int32', 0)
228 229 230 231 232 233 234
    x_array = fluid.dygraph.to_variable(x_array)

    for x in x_array[0:]:
        z = z + x
    return z


235
# 17. for a,b,c in z: (a, b, c) is a tuple
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
@paddle.jit.to_static
def for_tuple_as_iter_var(x_array):
    x = paddle.to_tensor(x_array)
    z = paddle.to_tensor(np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]))

    a_result = paddle.zeros([3])
    b_result = paddle.zeros([3])
    c_result = paddle.zeros([3])

    for a, b, c in z:
        a_result += a
        b_result += b
        c_result += c

    return a_result, b_result, c_result


253
# 18. for t in enumerate(collection): t is tuple of (idx, element)
254 255 256 257 258 259 260 261 262 263 264 265 266
@paddle.jit.to_static
def for_tuple_as_enumerate_iter(x_array):
    x = paddle.to_tensor(x_array)
    x_list = [x, x, x]

    a_result = paddle.zeros([5])

    for t in enumerate(x_list):
        a_result += t[1]

    return a_result


267
# 19. for i, (a, b, c, d, e) in enumerate(collection): (a, b, c, d, e) is a tuple
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
@paddle.jit.to_static
def for_tuple_as_enumerate_value(x_array):
    x = paddle.to_tensor(x_array)
    x_list = [x, x, x]

    a_result = paddle.zeros([1])
    b_result = paddle.zeros([1])
    c_result = paddle.zeros([1])
    d_result = paddle.zeros([1])
    e_result = paddle.zeros([1])

    for i, (a, b, c, d, e) in enumerate(x_list):
        a_result += a
        b_result += b
        c_result += c
        d_result += d
        e_result += e

    return a_result


289 290 291
# 20. test for function in a class
class ForwardContainsForLayer(paddle.nn.Layer):
    def __init__(self):
292
        super().__init__()
293 294 295 296 297 298 299 300 301 302 303 304 305
        self.high = 5
        self.low = 3

    @paddle.jit.to_static
    def forward(self, x):
        # just for test case, x is useless in this method
        y = paddle.zeros([10, 2, 3])
        z = []
        for i in range(self.high - self.low):
            z.append(y[i].clone())
        return z


306
# 21. for original list
307 308
@paddle.jit.to_static
def for_original_list():
309
    z = paddle.tensor.fill_constant([1], 'int32', 0)
310 311 312 313 314 315 316 317
    for x in [1, 2, 3]:
        z = z + x
    return z


# 22. for original tuple
@paddle.jit.to_static
def for_original_tuple():
318
    z = paddle.tensor.fill_constant([1], 'int32', 0)
319 320 321 322 323
    for x in (1, 2, 3):
        z = z + x
    return z


324 325
# 23. for zip error
@paddle.jit.to_static(
326 327
    input_spec=[InputSpec(shape=[None, 10]), InputSpec(shape=[None, 10])]
)
328 329 330 331 332 333 334 335
def for_zip_error(x, y):
    for i, j in zip(x, y):
        a = i + j
    return x + y


# 24. for zip
@paddle.jit.to_static(
336 337
    input_spec=[InputSpec(shape=[2, 10]), InputSpec(shape=[2, 10])]
)
338 339 340 341 342 343
def for_zip(x, y):
    for i, j in zip(x, y):
        a = i + j
    return x + y


344 345 346 347 348 349 350 351 352 353 354 355
@paddle.jit.to_static
def tensor_array_slice_in_enumerate():
    feats = {}
    feats['key'] = []
    feats_idx = paddle.arange(0, 10)
    for i, idx in enumerate(feats_idx):
        if i > 1:
            feat_n2 = feats['key'][-2]
        feats['key'].append(idx)
    return feat_n2


356 357
class TestTransformBase(unittest.TestCase):
    def setUp(self):
358 359 360 361 362
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
363 364 365 366 367 368 369 370
        self.set_input()
        self.set_test_func()

    def set_input(self):
        self.input = [1, 2, 3]

    def set_test_func(self):
        raise NotImplementedError(
371 372
            "For Enumerate test should implement set_test_func"
        )
373 374

    def _run(self, to_static):
R
Ryan 已提交
375
        paddle.jit.enable_to_static(to_static)
376 377 378 379 380 381 382 383 384 385 386 387 388
        with fluid.dygraph.guard():
            return self.dygraph_func(self.input)

    def get_dygraph_output(self):
        return self._run(to_static=False)

    def get_static_output(self):
        return self._run(to_static=True)


class TestTransform(TestTransformBase):
    def transformed_result_compare(self):
        dy_outs = self.get_dygraph_output()
389
        if not isinstance(dy_outs, (tuple, list)):
390
            dy_outs = (dy_outs,)
391

392
        self.dygraph_func.eval()
393
        st_outs = self.get_static_output()
394
        if not isinstance(st_outs, (tuple, list)):
395
            st_outs = (st_outs,)
396 397

        for x, y in zip(dy_outs, st_outs):
398
            np.testing.assert_allclose(x.numpy(), y.numpy(), rtol=1e-05)
399 400


401 402
class TestTransformForOriginalList(TestTransform):
    def _run(self, to_static):
R
Ryan 已提交
403
        paddle.jit.enable_to_static(to_static)
404 405 406 407
        with fluid.dygraph.guard():
            return self.dygraph_func()


408 409 410 411 412 413 414 415 416 417 418 419
class TestTransformError(TestTransformBase):
    def transformed_error(self, etype):
        with self.assertRaises(etype):
            dy_out = self.get_dygraph_output()
            st_out = self.get_static_output()


class TestForInRange(TestTransform):
    def set_input(self):
        self.input = np.array([5])

    def set_test_func(self):
420
        self.dygraph_func = for_in_range
421 422 423 424 425 426 427

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


class TestForIterList(TestTransform):
    def set_test_func(self):
428
        self.dygraph_func = for_iter_list
429 430 431 432 433 434 435

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


class TestForEnumerateSimple(TestForIterList):
    def set_test_func(self):
436
        self.dygraph_func = for_enumerate_list
437 438 439 440


class TestForInRangeWithBreak(TestForInRange):
    def set_test_func(self):
441
        self.dygraph_func = for_in_range_with_break
442 443 444 445 446 447 448


class TestForIterVarNumpy(TestTransform):
    def set_input(self):
        self.input = np.array([1, 2, 3, 4, 5])

    def set_test_func(self):
449
        self.dygraph_func = for_iter_var_numpy
450 451 452 453 454 455 456

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


class TestForEnumerateVarNumpy(TestForIterVarNumpy):
    def set_test_func(self):
457
        self.dygraph_func = for_enumerate_var_numpy
458 459 460 461


class TestForEnumerateVarNumpyWithStart(TestForIterVarNumpy):
    def set_test_func(self):
462
        self.dygraph_func = for_enumerate_var_numpy_with_start
463 464 465 466


class TestForEnumerateVarNumpyWithBreak(TestForIterVarNumpy):
    def set_test_func(self):
467
        self.dygraph_func = for_enumerate_var_numpy_with_break
468 469


Z
zhangchunle 已提交
470
class TestForEnumerateVarNumpyWithContinue(TestForIterVarNumpy):
471
    def set_test_func(self):
472
        self.dygraph_func = for_enumerate_var_numpy_with_continue
473 474 475 476


class TestForEnumerateVarNumpyWithStartAndBreak(TestForIterVarNumpy):
    def set_test_func(self):
477
        self.dygraph_func = for_enumerate_var_numpy_with_start_break
478 479


Z
zhangchunle 已提交
480
class TestForEnumerateVarNumpyWithStartAndContinue(TestForIterVarNumpy):
481
    def set_test_func(self):
482 483 484 485 486 487 488 489
        self.dygraph_func = for_enumerate_var_numpy_with_start_continue


class TestForIterVar(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_iter_var


490 491 492 493 494
class TestForIterVarIdx(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_iter_var_idx


495 496 497
class TestForEnumerateVar(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_enumerate_var
498 499


500 501 502 503 504
class TestForEnumerateVarWithNestedRange(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_enumerate_var_with_nested_range


505 506 507 508 509 510 511 512 513 514
class TestForIterVarList(TestForInRange):
    def set_test_func(self):
        self.dygraph_func = for_iter_var_list


class TestForEnumerateVarList(TestForInRange):
    def set_test_func(self):
        self.dygraph_func = for_enumerate_var_list


515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
class TestForTupleAsIterVar(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_tuple_as_iter_var


class TestForTupleAsEnumerateIter(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_tuple_as_enumerate_iter


class TestForTupleAsEnumerateValue(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = for_tuple_as_enumerate_value


530 531 532 533 534
class TestForwardContainsForLayer(TestForIterVarNumpy):
    def set_test_func(self):
        self.dygraph_func = ForwardContainsForLayer()


535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
class TestForOriginalList(TestTransformForOriginalList):
    def set_test_func(self):
        self.dygraph_func = for_original_list

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


class TestForOriginalTuple(TestTransformForOriginalList):
    def set_test_func(self):
        self.dygraph_func = for_original_tuple

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


551 552 553 554 555 556 557 558
class TestSliceTensorArrayInEnumerate(TestTransformForOriginalList):
    def set_test_func(self):
        self.dygraph_func = tensor_array_slice_in_enumerate

    def test_transformed_result_compare(self):
        self.transformed_result_compare()


559
class TestForZip(unittest.TestCase):
560 561 562 563 564 565
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()

566 567
    def test_for_zip_error(self):
        with self.assertRaises(RuntimeError):
568 569
            model_path = os.path.join(self.temp_dir.name, 'for_zip_error')
            paddle.jit.save(for_zip_error, model_path)
570 571

    def test_for_zip(self):
572 573
        model_path = os.path.join(self.temp_dir.name, 'for_zip')
        paddle.jit.save(for_zip, model_path)
574 575


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