broadcast_tensors

paddle. broadcast_tensors ( input: Sequence[Tensor], name: str | None = None ) → list[Tensor] [source]

This API has two signatures:

  1. paddle.broadcast_tensors(input, name=None) (Paddle-style):

    Broadcast a list of tensors following broadcast semantics.

  2. paddle.broadcast_tensors(*tensors) (PyTorch-style):

    Broadcast variadic tensor arguments following broadcast semantics.

Note

If you want know more about broadcasting, please refer to Introduction to Tensor .

The following figure illustrates the process of broadcasting three tensors to the same dimensions. The dimensions of the three tensors are [4, 1, 3], [2, 3], and [4, 2, 1], respectively. During broadcasting, alignment starts from the last dimension, and for each dimension, either the sizes of the two tensors in that dimension are equal, or one of the tensors has a dimension of 1, or one of the tensors lacks that dimension. In the figure below, in the last dimension, Tensor3 has a size of 1, while Tensor1 and Tensor2 have sizes of 3; thus, this dimension is expanded to 3 for all tensors. In the second-to-last dimension, Tensor1 has a size of 2, and Tensor2 and Tensor3 both have sizes of 2; hence, this dimension is expanded to 2 for all tensors. In the third-to-last dimension, Tensor2 lacks this dimension, while Tensor1 and Tensor3 have sizes of 4; consequently, this dimension is expanded to 4 for all tensors. Ultimately, all tensors are expanded to [4, 2, 3].

Illustration of BroadCast
Parameters
  • input (list|tuple) – Sequence of input tensors. Supported data types: bool, float16, float32, float64, int32, int64, complex64, complex128. All the Tensors in input must have same data type. Currently we only support tensors with rank no greater than 5.

  • name (str|None, optional) – Name for the operation (optional, default is None). For more information, please refer to api_guide_Name.

Returns

list(Tensor), The list of broadcasted tensors following the same order as input.

Examples

>>> import paddle
>>> x1 = paddle.rand([1, 2, 3, 4]).astype('float32')
>>> x2 = paddle.rand([1, 2, 1, 4]).astype('float32')
>>> x3 = paddle.rand([1, 1, 3, 1]).astype('float32')
>>> out1, out2, out3 = paddle.broadcast_tensors(input=[x1, x2, x3])
>>> # out1, out2, out3: tensors broadcasted from x1, x2, x3 with shape [1,2,3,4]