mindspore.ops.Scan

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

Scan a function over an array while the processing of the current element depends on the execution result of the previous element. The execution logic of the Scan operator can be roughly represented by the following code:

def Scan(loop_func, init, xs, length=None):
    if xs is None:
        xs = [None] * length
    carry = init
    ys = []
    for x in xs:
        carry, y = loop_func(carry, x)
        ys.append(y)
    return carry, ys

The current Scan 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 first element of the return value of loop_func being of a different type or shape from the init_val is currently not support.

Warning

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

Inputs:
  • loop_func (Function) - The loop function.

  • init (Union[Tensor, number, str, bool, list, tuple, dict]) - An initial loop carry value.

  • xs (Union[tuple, list, None]) - The value over which to scan.

  • length (Union[int, None], optional) - The size of xs. Default: None .

  • unroll (bool, optional) - The flag for whether to perform loop unrolling in compile process. Default: True .

Outputs:

Tuple(Union[Tensor, number, str, bool, list, tuple, dict], list). Output of scan loop, a tuple with two elements, the first element has same type and shape with init argument, and the second is a list containing the results of each loop.

Raises
  • TypeError – If loop_func is not a function.

  • TypeError – If xs is not a tuple, a list or None.

  • TypeError – If length is not an int or None.

  • TypeError – If unroll is not a bool.

  • ValueError – If loop_func cannot take init and element of xs as inputs.

  • ValueError – If the return value of loop_func is not a tuple with two elements, or the first element of the tuple has different type or shape from init .

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import ops
>>> def cumsum(res, el):
...     res = res + el
...     return res, res
...
>>> a = [1, 2, 3, 4]
>>> result_init = 0
>>> scan_op = ops.Scan()
>>> result = scan_op(cumsum, result_init, a)
>>> print(result == (10, [1, 3, 6, 10]))
True