Python / PyTorch Fundamentals Interview Questions
How does broadcasting work in PyTorch and what are the rules?
Broadcasting allows PyTorch to perform arithmetic between tensors of different shapes without explicit copying. PyTorch follows the same broadcasting rules as NumPy. Understanding broadcasting is essential to avoid subtle shape bugs.
import torch # Rule: align shapes from the RIGHT, expand dims of size 1 a = torch.ones(3, 4) # shape (3, 4) b = torch.ones(4) # shape (4) â treated as (1, 4) â broadcast to (3, 4) c = a + b # works! c.shape = (3, 4) # Adding a bias vector to a batch of activations batch = torch.randn(32, 128) # (batch=32, features=128) bias = torch.randn(128) # (128,) broadcasts across the batch dim out = batch + bias # (32, 128) â # Adding column and row vectors â 2D result col = torch.arange(3).reshape(3, 1) # (3, 1) row = torch.arange(4).reshape(1, 4) # (1, 4) grid = col + row # (3, 4) â outer-sum print(grid) # tensor([[0, 1, 2, 3], # [1, 2, 3, 4], # [2, 3, 4, 5]]) # Common broadcasting errors: # a = torch.ones(3, 4) # b = torch.ones(3) # (3,) aligns to (1, 3) NOT (3, 1) # a + b â ERROR: size 4 != size 3 in dimension 1 # Fix: b.reshape(3, 1) to make it (3, 1)
| Step | Rule |
|---|---|
| 1. Align right | Pad missing leading dimensions with 1 |
| 2. Check compatibility | Each dim must be equal, or one of them must be 1 |
| 3. Expand size-1 dims | Dimension of size 1 is stretched to match the other tensor |
| 4. Error if incompatible | Raises RuntimeError if no dim is 1 and sizes differ |
More Related questions...