torch.broadcast_shapes
function broadcast_shapes(...shapes: readonly number[][]): number[]Computes the broadcast shape of multiple shapes.
Determines what shape multiple tensors would have after broadcasting together. This is useful for:
- Validating shape compatibility: check if operations can work together
- Pre-allocating output tensors: know the result shape before computation
- Shape inference: understanding how broadcasting will affect dimensions
- Debugging shape mismatches: see what shape dimensions will become
- Batching operations: compute common shape for multiple tensors
The broadcasting rules apply from the trailing dimensions backward:
- Dimensions of size 1 can expand to any size
- All other dimensions must be equal
- Missing dimensions (in shorter shapes) are prepended as 1s
- Order independent: Result is same regardless of input order
- Dimension alignment: Trailing dimensions align first (right-justified)
- Prepending: Shorter shapes get prepended with 1s automatically
- Empty input: Broadcasting zero shapes returns empty shape []
- Incompatible shapes: Throws error if dimensions don't broadcast
- Size mismatch: Non-1 dimensions must match exactly or error
Parameters
shapesreadonly number[][]- Variable number of shapes to broadcast together
Returns
number[]– The resulting broadcast shape after applying broadcasting rulesExamples
// Two compatible shapes
torch.broadcast_shapes([3, 1], [1, 4]); // [3, 4]
// Three shapes with prepended dimensions
torch.broadcast_shapes([2, 3], [3], [1, 1, 3]); // [1, 2, 3]
// Batch broadcasting
const shape1 = [32, 1, 64]; // Batch with 1 feature
const shape2 = [1, 128, 64]; // 1 batch with 128 features
torch.broadcast_shapes(shape1, shape2); // [32, 128, 64]
// Image broadcasting
const img_shape = [3, 224, 224]; // Single image
const batch_shape = [32, 1, 1]; // Batch with unit spatial dims
torch.broadcast_shapes(img_shape, batch_shape); // [32, 224, 224]See Also
- PyTorch torch.broadcast_shapes()
- broadcast_to - Broadcast single tensor to shape
- broadcast_tensors - Broadcast actual tensor objects
- expand - Expand tensor along dimensions