Skip to content

Commit bc46c52

Browse files
committed
Add doc for while op
1 parent 0329ee7 commit bc46c52

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

python/paddle/fluid/layers/control_flow.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,60 @@ def __exit__(self, exc_type, exc_val, exc_tb):
607607

608608

609609
class While(object):
610+
"""
611+
while loop control flow.
612+
613+
Args:
614+
cond (Variable): condition used to compare.
615+
name (str): The name of this layer.
616+
617+
Examples:
618+
.. code-block:: python
619+
620+
# The value these d0, d1 and d2 can be fed from python.
621+
d0 = fluid.layers.data(
622+
"d0", shape=[10], append_batch_size=False, dtype='float32')
623+
d1 = fluid.layers.data(
624+
"d1", shape=[10], append_batch_size=False, dtype='float32')
625+
d2 = fluid.layers.data(
626+
"d2", shape=[10], append_batch_size=False, dtype='float32')
627+
i = fluid.layers.zeros(shape=[1], dtype='int64')
628+
i.stop_gradient = True
629+
init = fluid.layers.zeros(shape=[10], dtype='float32')
630+
# Initialize mem_array from init
631+
mem_array = fluid.layers.array_write(x=init, i=i)
632+
# Initialize data_array from d0
633+
data_array = fluid.layers.array_write(x=d0, i=i)
634+
# Set a value to data_array using d1[i].
635+
i = fluid.layers.increment(i)
636+
fluid.layers.array_write(d1, i, array=data_array)
637+
# Set a value to data_array using d2[i].
638+
i = fluid.layers.increment(i)
639+
fluid.layers.array_write(d2, i, array=data_array)
640+
# Create a idx to start the while loop.
641+
i = fluid.layers.zeros(shape=[1], dtype='int64')
642+
i.stop_gradient = True
643+
644+
array_len = fluid.layers.fill_constant(
645+
shape=[1], dtype='int64', value=3)
646+
array_len.stop_gradient = True
647+
# Create the while loop condition.
648+
cond = fluid.layers.less_than(x=i, y=array_len)
649+
650+
# Within the loop, perform sums.
651+
while_op = fluid.layers.While(cond=cond)
652+
with while_op.block():
653+
d = fluid.layers.array_read(array=data_array, i=i)
654+
prev = fluid.layers.array_read(array=mem_array, i=i)
655+
result = fluid.layers.sums(input=[d, prev])
656+
657+
i = fluid.layers.increment(x=i, in_place=True)
658+
fluid.layers.array_write(result, i=i, array=mem_array)
659+
fluid.layers.less_than(x=i, y=array_len, cond=cond)
660+
661+
sum_result = fluid.layers.array_read(array=mem_array, i=i)
662+
"""
663+
610664
BEFORE_WHILE_BLOCK = 0
611665
IN_WHILE_BLOCK = 1
612666
AFTER_WHILE_BLOCK = 2

0 commit comments

Comments
 (0)