mindspore.ops.ForiLoop

View Source On Gitee
class mindspore.ops.ForiLoop[source]

Provide a useful op for loop from lower to upper. The execution logic of the ForiLoop operator can be roughly represented by the following code:

def ForiLoop(lower, upper, loop_func, init_val):
    for i in range(lower, upper):
        init_val = loop_func(i, init_val)
    return init_val

The current ForiLoop operator has the following syntactic limitations:

  • Using a side-effect function as loop_func is currently not support, such as operations that modify parameters, global variables, etc.

  • The return value of loop_func being of a different type or shape from the init_val is currently not support.

  • Negative numbers or custom increments is currently not support.

Warning

This is an experimental API that is subject to change or deletion.

Inputs:
  • lower (Union[int, Tensor]) - The start index of loop.

  • upper (Union[int, Tensor]) - The end index of loop.

  • loop_func (Function) - The loop function, takes two arguments.

  • init_val (Union[Tensor, number, str, bool, list, tuple, dict]) - The init value.

  • unroll (bool, optional) - The flag for whether unroll in compile process, only valid when the number of loop iterations is determined. Default: True .

Outputs:

Union[Tensor, number, str, bool, list, tuple, dict], the final result of the loop, has same type and shape with input init_val .

Raises
  • TypeError – If lower is not an int or a Tensor.

  • TypeError – If upper is not an int or a Tensor.

  • TypeError – If loop_func is not a function.

  • ValueError – If loop_func cannot take index and init_val as arguments or if the type of output it produces is different from the type or shape of init_val .

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import ops
>>> def cumsum(index, res):
...     return index + res
...
>>> result_init = 0
>>> fori_loop = ops.ForiLoop()
>>> result = fori_loop(0, 4, cumsum, result_init)
>>> print(result)
6