PyTorch torch.broadcast_shapes function
PyTorch torch reference manual
torch.broadcast_shapes is a function in PyTorch used to compute the broadcast result of multiple shapes. It returns the shape obtained by broadcasting the input shapes without actually creating a tensor.
Function definition
torch.broadcast_shapes(*shapes)
Usage examples
Example
import
torch
Compute the shape broadcast result
result
=
torch.
broadcast_shapes
(
(
3
,
1
)
,
(
1
,
4
)
,
(
3
,
4
)
)
(
"(3,1) + (1,4) + (3,4) ->"
,
result
)
Output: (3, 4)
Multiple shapes
result
=
torch.
broadcast_shapes
(
(
5
,
)
,
(
1
,
5
)
,
(
3
,
1
,
5
)
)
(
"(5,) + (1,5) + (3,1,5) ->"
,
result
)
Output: (3, 1, 5)
A single shape
result
=
torch.
broadcast_shapes
(
(
2
,
3
)
)
(
"(2,3) ->"
,
result
)
Output: (2, 3)
An error is raised when broadcasting is not possible
try
:
result
=
torch.
broadcast_shapes
(
(
3
,
)
,
(
4
,
)
)
except
RuntimeError
as
e:
(
"Broadcast error:"
,
e
)