Chapter 5 of 42 · ~20 min read & lab+75 XP
Chapter 5 · Deep Learning

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!

Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

Forgetting optimizer.zero_grad() or model.eval() is responsible for more silent bugs in junior PyTorch PRs than any math error!

Data Scientist

Using with torch.no_grad(): during evaluation cuts GPU memory usage by ~50% and speeds up inference significantly.

Interview & Debug Edge

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()?'

Step 0 · Test Your Gut Before Any Math!

What happens if you forget to call optimizer.zero_grad() at the start of every PyTorch training iteration?

What You Will Master in This Chapter
  • 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() with with torch.no_grad(): during validation and inference to save VRAM and disable Dropout/BatchNorm updates
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
(B,C,H,W)   vs.   (B,T,D)(B, C, H, W) \;\text{ vs. }\; (B, T, D)Say aloud:“Batch-Channel-Height-Width versus Batch-Time-Dimension”
Plain-English Meaning
PyTorch's two universal tensor conventions: (B, C, H, W) for 2D vision (CNNs) and (B, T, D) for sequences & Transformers.
Everyday Example
(32, 3, 224, 224) = 32 RGB images; (16, 512, 768) = 16 sentences of 512 tokens.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

PyTorch Standard Tensor Shapes Across DomainsTabular / MLP(B, F)(64, 128) featuresImages (CNN)(B, C, H, W)(32, 3, 224, 224)Text / Sequence(B, T, D)(16, 512, 768)
PyTorch standard image tensor layout (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
Animated Mini-Lab • 1.5

PyTorch `nn.Linear(in, out)` Shape & Parameter Explorer

Input `(32, 128)` → `nn.Linear(128, 64)` → Output `(32, 64)` · Trainable Params: 8,256

2. Broadcasting Rules (Zero-Copy Vectorization)

PyTorch Broadcasting: Right-to-Left Dimension Alignment (Zero Memory Copy!)Matrix X: (32, 128) + Bias b: ( 128)Right-align → (32, 128) + ( 1, 128) → stretch dim 0 virtually!Output: (32, 128) ✓ (Rule: dims equal OR one is 1!)
NumPy / PyTorch Broadcasting aligns dimensions right-to-left: dimensions match if they are equal OR one of them is 1 (e.g., (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 assert preds.shape == targets.shape!

3. The Canonical 5-Step PyTorch Training Loop

The 5-Line PyTorch Training Loop (Every Deep Learning Project!)1. zero_grad()2. y = model(x)3. loss(y, t)4. backward()5. opt.step()
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:

  1. optimizer.zero_grad(set_to_none=True)
  2. preds = model(x)
  3. loss = criterion(preds, y)
  4. loss.backward()
  5. optimizer.step()
Pause & Check · Quick Intuition Pulse

Does with torch.no_grad(): automatically disable Dropout and freeze BatchNorm running stats?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS PyTorch 5-Step Training Loop animate from zero_grad() to optimizer.step().
Interactive Animation • 1.5 Deep Lab

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.

Step 1 / 5
optimizer.zero_grad()// Clear stale gradients from previous step!
preds = model(x_batch)// Forward pass builds autograd graph
loss = criterion(preds, y_batch)// Compute scalar loss tensor
loss.backward()// Populate .grad for every parameter
optimizer.step()// Update weights using .grad ✓
0%
optimizer.zero_grad()
Intuition Takeaway: Master PyTorch shapes ((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!
Where This Powers Real ML, Deep Learning & Generative AI

Foundation for Every PyTorch Project

This exact nn.Module + 5-step loop + eval()/no_grad() pattern scales directly to CNNs, Transformers, and distributed training.

Production NumPy & PyTorch Code Patterns
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!
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Computing MSELoss between preds of shape (32, 1) and targets of shape (32,), silently broadcasting into a (32, 32) pairwise matrix!
Best Practice: Always verify assert preds.shape == targets.shape before computing regression losses!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1In PyTorch, what is the shape of torch.zeros(32, 1) + torch.zeros(32) due to broadcasting?

Apply What You Learned — Solve Matching Coding Problems