paddle.fluid.layers.control_flow. cond ( pred, true_fn=None, false_fn=None, name=None ) [source]

This API returns true_fn() if the predicate pred is true else false_fn() . Users could also set true_fn or false_fn to None if do nothing and this API will treat the callable simply returns None in this case.

true_fn and false_fn should return same nest structure of tensors or both return None if user doens’t like to return anything. A nest structure of tensors in PaddlePaddle is tensor(s), or tuple of tensors, or list of tensors.


1. The tuples or lists returned by true_fn and false_fn must have the same shape because of dataflow model of PaddlePaddle while the tensors in the tuples or the lists can have different shapes.

2. Any tensors or operations created outside of true_fn and false_fn will be executed regardless of which branch is selected at runtime. This has frequently surprised users who expected a lazy semantics. For example:

import paddle

a = paddle.zeros((1, 1))
b = paddle.zeros((1, 1))
c = a * b
out = paddle.nn.cond(a < b, lambda: a + c, lambda: b * b)

No matter whether a < b , c = a * b will run.

  • pred (Tensor) – A boolean tensor whose numel should be 1. The boolean value determines whether to return the result of true_fn or false_fn .

  • true_fn (callable, optional) – A callable to be performed if pred is true. The default value is None .

  • false_fn (callable, optional) – A callable to be performed if pred is false. The default value is None .

  • name (str, optional) – The default value is None . Normally users don’t have to set this parameter. For more information, please refer to Name .


returns true_fn() if the predicate pred is true else false_fn() .

Return type


  • TypeError – if true_fn or false_fn is not callable.

  • ValueError – if true_fn and false_fn don’t return the same nest structure of tensors.


import paddle

# pseudocode:
# if 0.1 < 0.23:
#     return 1, True
# else:
#     return 3, 2

def true_func():
    return paddle.fill_constant(shape=[1, 2], dtype='int32',
                                value=1), paddle.fill_constant(shape=[2, 3],

def false_func():
    return paddle.fill_constant(shape=[3, 4], dtype='float32',
                                value=3), paddle.fill_constant(shape=[4, 5],

x = paddle.fill_constant(shape=[1], dtype='float32', value=0.1)
y = paddle.fill_constant(shape=[1], dtype='float32', value=0.23)
pred = paddle.less_than(x=x, y=y, name=None)
ret = paddle.nn.cond(pred, true_func, false_func)
# ret is a tuple containing 2 tensors
# ret[0] = [[1 1]]
# ret[1] = [[ True  True  True]
#           [ True  True  True]]