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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
