sequence_mask

paddle.nn.functional. sequence_mask ( x: Tensor, maxlen: int | None = None, dtype: DTypeLike = 'int64', name: str | None = None ) Tensor [source]

SequenceMask Layer

This layer outputs a mask according to the input x and maxlen with data type of dtype.

Supposing x is a Tensor with shape [d_1, d_2, …, d_n], the y is a mask with shape [d_1, d_2, …, d_n, maxlen], where:

y(i1,i2,...,in,j)=(j<x(i1,i2,...,in))
Case:

Consider input:
    x = [3, 1, 1, 0]    max_len = 4

then we get out:
    mask = [[1, 1, 1, 0],
            [1, 0, 0, 0],
            [1, 0, 0, 0],
            [0, 0, 0, 0]]
Parameters
  • x (Variable) – Input tensor of sequence_mask layer, whose elements are integers less than maxlen. Tensor with shape [d_1, d_2, …, d_n].

  • maxlen (int|None, optional) – Maximum length of the sequence. If maxlen is None, it would be replace with max(x).

  • dtype (np.dtype|paddle.dtype|str, optional) – Data type of the output, int64 by default.

  • name (str|None, optional) – For detailed information, please refer to Name. Usually name is no need to set and None by default.

Returns

Tensor, The output sequence mask. Tensor with shape [d_1, d_2, …, d_n, maxlen] and data type of dtype. The data type should be bool, float32, float64, int8, int32 or int64.

Examples

>>> import paddle

>>> lengths = paddle.to_tensor([10, 9, 8])
>>> mask = paddle.nn.functional.sequence_mask(lengths)

>>> print(mask)
Tensor(shape=[3, 10], dtype=int64, place=Place(cpu), stop_gradient=True,
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
 [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]])