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 9c1271c1cd7baba67397999193086e6df52183bc..924143049efc1315f4f2dc27a7e648ecc0b4e253 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 b6aa73d37639b89d0d374e34725c526f119b1064..bc235ca8606499aa02743f4b627d478f007f4ed8 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