Created by: liym27
This PR supports list.append()
in control flow if、for、while
Python list
will be transformed into LoDTensorArray
. In order to use LoDTensorArray
like a python list
, more support is needed.
LoDTensorArray is supported in stack op: https://github.com/PaddlePaddle/Paddle/pull/22962
Example 1, in control flow if
- before:
def test_list_in_if(x):
x = fluid.dygraph.to_variable(x)
a = []
if x.numpy()[0] > 0:
a.append(x)
else:
a.append(fluid.layers.fill_constant(shape=[1, 2], value=9, dtype=
'int64'))
return a
- after:
def test_list_in_if(x):
x = fluid.layers.assign(x)
a = fluid.layers.create_array(dtype='float32')
def true_fn_0(a, x):
fluid.layers.array_write(x=x, i=fluid.layers.array_length(a), array=a)
def false_fn_0(a):
fluid.layers.array_write(x=fluid.layers.fill_constant(shape=[1, 2],
value=9, dtype='int64'), i=fluid.layers.array_length(a), array=a)
fluid.layers.cond(x[0] > 0, lambda : true_fn_0(a, x), lambda :
false_fn_0(a))
return a
Example 2, in control flow while
- before:
def test_list_in_while_loop(x, iter_num):
x = fluid.dygraph.to_variable(x)
iter_num = fluid.layers.fill_constant(shape=[1], value=iter_num, dtype=
'int32')
a = []
i = 0
while i < iter_num.numpy()[0]:
a.append(x)
i += 1
return a
- after:
def test_list_in_while_loop(x, iter_num):
x = fluid.layers.assign(x)
iter_num = fluid.layers.fill_constant(shape=[1], value=iter_num, dtype=
'int32')
a = fluid.layers.create_array(dtype='float32')
i = 0
a = fluid.dygraph.dygraph_to_static.variable_trans_func.to_static_variable(
a)
x = fluid.dygraph.dygraph_to_static.variable_trans_func.to_static_variable(
x)
iter_num = (fluid.dygraph.dygraph_to_static.variable_trans_func.
to_static_variable(iter_num))
i = fluid.dygraph.dygraph_to_static.variable_trans_func.to_static_variable(
i)
def while_condition_0(a, x, iter_num, i):
return i < iter_num[0]
def while_body_0(a, x, iter_num, i):
fluid.layers.array_write(x=x, i=fluid.layers.array_length(a), array=a)
i += 1
return a, x, iter_num, i
a, x, iter_num, i = fluid.layers.while_loop(while_condition_0,
while_body_0, [a, x, iter_num, i])
return a