PyTorch Basics From Scratch: Tensors, Shapes, Broadcasting & The 5-Line Training Loop
Your hands-on PyTorch launchpad: reading tensor shapes (B, C, H, W) & (B, T, D), right-to-left Broadcasting rules, model.train() vs. model.eval() + torch.no_grad(), and the canonical 5-line PyTorch training loop!
PyTorch powers over 85% of modern AI research and production models — mastering tensor shapes, broadcasting, and the 5-step training loop removes 90% of beginner friction!
Forgetting optimizer.zero_grad() or model.eval() is responsible for more silent bugs in junior PyTorch PRs than any math error!
Using with torch.no_grad(): during evaluation cuts GPU memory usage by ~50% and speeds up inference significantly.
Classic live-coding PyTorch check: 'What happens if you forget optimizer.zero_grad() inside a training loop, and what is the difference between model.eval() and torch.no_grad()?'
What happens if you forget to call optimizer.zero_grad() at the start of every PyTorch training iteration?
- Read and verify standard PyTorch tensor shapes:
(B, F)tabular,(B, C, H, W)images, and(B, T, D)sequences - Apply right-to-left Broadcasting rules cleanly (and avoid silent shape bugs like
(32,) + (32, 1)→(32, 32)!) - Write the canonical 5-step PyTorch Training Loop (
zero_grad→ forward → loss →backward→step) - Always pair
model.eval()withwith torch.no_grad():during validation and inference to save VRAM and disable Dropout/BatchNorm updates
(B, C, H, W) for 2D vision (CNNs) and (B, T, D) for sequences & Transformers.(32, 3, 224, 224) = 32 RGB images; (16, 512, 768) = 16 sentences of 512 tokens.A PyTorch Tensor is just a NumPy array with two superpowers: it can live on a GPU (.to('cuda')) and it remembers every math operation performed on it (Autograd) so calling loss.backward() computes all gradients automatically!
1. Reading PyTorch Tensor Shapes Like a Native
(B, C, H, W): Batch size × Color Channels (3 for RGB) × Height × Width — knowing tensor shapes catches 80% of deep learning bugs!Whenever a PyTorch error says mat1 and mat2 shapes cannot be multiplied, print .shape! Nearly every model uses one of three conventions:
- Tabular / MLP:
(B, F)— Batch × Features - Images / CNN:
(B, C, H, W)— Batch × Channels × Height × Width - Text / Audio:
(B, T, D)— Batch × Sequence Length × Embedding Dim
PyTorch `nn.Linear(in, out)` Shape & Parameter Explorer
2. Broadcasting Rules (Zero-Copy Vectorization)
(32, 128) + (128,) adds bias across all 32 rows with zero memory copy)!When adding or multiplying two tensors of different shapes, PyTorch aligns them right-to-left: dimensions are compatible if they are equal OR one of them is 1.
(32, 128) + (128,)→(32, 128)✓ (adding bias to a batch!)- Watch out:
(32, 1) - (32,)silently broadcasts into a(32, 32)matrix — one of the sneakiest MSE loss bugs in PyTorch! Always assertpreds.shape == targets.shape!
3. The Canonical 5-Step PyTorch Training Loop
zero_grad() → Forward pass → Compute Loss → loss.backward() → optimizer.step()!Every PyTorch model — from a 2-layer toy classifier to a frontier vision-language model — runs this exact 5-step rhythm per batch:
optimizer.zero_grad(set_to_none=True)preds = model(x)loss = criterion(preds, y)loss.backward()optimizer.step()
Does with torch.no_grad(): automatically disable Dropout and freeze BatchNorm running stats?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Setting gradients to None instead of writing zeros into memory skips a memset kernel per parameter — slightly faster and uses less VRAM!
zero_grad() to optimizer.step().The 5-Step PyTorch Training Loop in Motion
Every PyTorch model — from a 2-layer MLP to a 70B LLM — trains using these exact 5 lines.
(B, C, H, W) / (B, T, D)), right-to-left Broadcasting, the 5-step training loop, and pairing model.eval() + torch.no_grad() — and you're ready to build any Deep Learning architecture!Foundation for Every PyTorch Project
This exact nn.Module + 5-step loop + eval()/no_grad() pattern scales directly to CNNs, Transformers, and distributed training.
import torch
import torch.nn as nn
model = nn.Sequential(nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
model.train()
for x_batch, y_batch in train_loader:
optimizer.zero_grad(set_to_none=True) # 1. Clear stale grads
logits = model(x_batch) # 2. Forward pass
loss = criterion(logits, y_batch) # 3. Compute loss
loss.backward() # 4. Backprop gradients
optimizer.step() # 5. Update weights!
model.eval()
with torch.no_grad():
val_logits = model(x_val) # Clean, low-VRAM inference!
MSELoss between preds of shape (32, 1) and targets of shape (32,), silently broadcasting into a (32, 32) pairwise matrix!assert preds.shape == targets.shape before computing regression losses!torch.zeros(32, 1) + torch.zeros(32) due to broadcasting?