torch.broadcast_tensors
Broadcasts tensors to a common shape.
Takes multiple tensors and broadcasts them all to a common shape. Each input tensor is expanded (or left unchanged if already the right shape) to match the broadcasted result. Useful for:
- Element-wise operations: ensuring operands have compatible shapes
- Batch operations: aligning tensors with different batch dimensions
- Multi-input functions: matching shapes before combined processing
- Type consistency: ensuring all outputs have same shape
- Coefficient matching: preparing tensors for matrix operations
This is the tensor version of broadcast_shapes - it actually broadcasts the tensors, not just computing what the shape would be.
- Memory efficient: Uses views/broadcasts where possible (no copies unless needed)
- Input order independent: Result shapes are same regardless of order
- Maintains dtypes: Each tensor keeps its original data type
- Same length output: Returns exactly as many tensors as inputs
- Incompatible shapes: Will throw error if shapes can't broadcast together
- Size constraints: Non-1 dimensions must match or be 1
Parameters
tensorsTensor[]- Variable number of tensors to broadcast
Returns
Tensor[]– Array of tensors broadcast to a common shape (same length as input)Examples
// Broadcasting two tensors for element-wise operation
const a = torch.randn(3, 1); // [3, 1]
const b = torch.randn(1, 4); // [1, 4]
const [bc_a, bc_b] = torch.broadcast_tensors(a, b); // Both [3, 4]
const result = bc_a.add(bc_b); // [3, 4] element-wise addition
// Broadcasting multiple tensors for batch operation
const weights = torch.randn(1, 64); // Single weight vector
const biases = torch.randn(32, 1); // Single bias per sample
const features = torch.randn(32, 64); // Batch of features
const [w, b, f] = torch.broadcast_tensors(weights, biases, features);
// All have shape [32, 64]
// Broadcasting with prepended dimensions
const scalar_like = torch.randn(1); // [1]
const vector = torch.randn(5); // [5]
const matrix = torch.randn(3, 5); // [3, 5]
const [s, v, m] = torch.broadcast_tensors(scalar_like, vector, matrix);
// All have shape [3, 5]See Also
- PyTorch torch.broadcast_tensors()
- broadcast_shapes - Compute broadcast shape without tensors
- broadcast_to - Broadcast single tensor to specific shape
- expand - Expand tensor dimensions