From 41a7b07159dd6532e3eac0bffcfd6bc5f56229f8 Mon Sep 17 00:00:00 2001 From: liym27 <33742067+liym27@users.noreply.github.com> Date: Mon, 21 Dec 2020 15:13:44 +0800 Subject: [PATCH] [Dy2Stat] Fix bug for loop: a variable is used and created in loop, but used before created (#29769) --- .../fluid/dygraph/dygraph_to_static/loop_transformer.py | 8 +++++++- .../fluid/tests/unittests/dygraph_to_static/test_loop.py | 6 +++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/python/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py b/python/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py index 9c1271c1cd7..924143049ef 100644 --- a/python/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py +++ b/python/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py @@ -167,7 +167,13 @@ class NameVisitor(gast.NodeVisitor): # var_a = func2(x) # - if isinstance(var_name_to_ctxs[name][0], gast.Load): + is_created = False + for ctx in var_name_to_ctxs[name]: + if isinstance(ctx, gast.Store): + is_created = True + + if isinstance(var_name_to_ctxs[name][0], + gast.Load) and is_created: loop_var_names.add(name) create_var_names.add(name) diff --git a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py index b6aa73d3763..bc235ca8606 100644 --- a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py +++ b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py @@ -86,11 +86,15 @@ def for_loop_dyfunc(max_len): def for_loop_dyfunc2(max_len): # Test case: a variable is used and created in loop, but used before created + x = fluid.layers.fill_constant(shape=[1, 2], dtype="int32", value=1) + for i in range(max_len): if i > 1: s = a a = 1 - ret = fluid.layers.fill_constant(shape=[1], dtype="int32", value=s) + q, _ = x.shape # test var x.shape only used but not created in loop + + ret = fluid.layers.fill_constant(shape=[1], dtype="int32", value=s + q) return ret -- GitLab