Launch the interactive walkthrough to discover each component, including the 3D Q-Sphere Lab & Python in Colab.
Master PyTorch, the favorite framework of AI researchers worldwide: dynamic computation graphs (Eager Mode), Tensors, and nn.Module.
optimizer.zero_grad() (Clear old gradients)
2. y_pred = model(X) (Make predictions)
3. loss = criterion(y_pred, y) (Grade error)
4. loss.backward() (Calculate gradients)
5. optimizer.step() (Update weights!)torch.nn.Module provides state encapsulation and parameter registration.Create tensors and move to device (CPU or GPU CUDA).
Pass input through model instance: outputs = model(inputs).
loss.backward() computes partial derivatives across leaf tensors.
optimizer.step() shifts parameters along negative gradient.
Problem: Training modern Transformer models like LLaMA and Stable Diffusion.
Solution: PyTorch native support for FlashAttention and Distributed Data Parallel (DDP) powers frontier AI research.
Interactive activity component
Write a full 5-step PyTorch training loop and verify loss reduction.
For Google Colab or Jupyter notebooks, run this shell command to install the required dependencies:
!pip install torch1 import torch 2 import torch.nn as nn 3 import torch.optim as optim
import torch β Core PyTorch
import torch.nn as nn β Neural network modules
import torch.optim as optim β Optimization algorithms
1 # Synthetic dataset: y = 2.5 * x + 1.0 2 X = torch.randn(100, 1) 3 y = 2.5 * X + 1.0 + torch.randn(100, 1) * 0.1 # With noise 4 5 # Define linear model: 1 input -> 1 output 6 model = nn.Linear(1, 1) 7 criterion = nn.MSELoss() 8 optimizer = optim.SGD(model.parameters(), lr=0.1) 9 10 # The 5-Step PyTorch Training Loop: 11 for epoch in range(50): 12 optimizer.zero_grad() # 1. Zero gradients 13 predictions = model(X) # 2. Forward pass 14 loss = criterion(predictions, y) # 3. Calculate loss 15 loss.backward() # 4. Backward pass 16 optimizer.step() # 5. Optimizer step 17 18 learned_w = model.weight.item() 19 learned_b = model.bias.item() 20 print(f"Learned equation: y = {learned_w:.2f} * x + {learned_b:.2f} (Target: 2.50 * x + 1.00)")
# Synthetic dataset: y = 2.5 * x + 1.0
Synthetic data
X = torch.randn(100, 1)
100 input samples
y = 2.5 * X + 1.0 + torch.randn(100, 1) * 0.1 # With noise
Target labels
# Define linear model: 1 input -> 1 output
Model
model = nn.Linear(1, 1)
Single linear layer
criterion = nn.MSELoss()
MSE loss
optimizer = optim.SGD(model.parameters(), lr=0.1)
SGD optimizer
# The 5-Step PyTorch Training Loop:
Standard loop
for epoch in range(50):
Run 50 epochs
optimizer.zero_grad() # 1. Zero gradients
Step 1
predictions = model(X) # 2. Forward pass
Step 2
loss = criterion(predictions, y) # 3. Calculate loss
Step 3
loss.backward() # 4. Backward pass
Step 4
optimizer.step() # 5. Optimizer step
Step 5
learned_w = model.weight.item()
Get weight
learned_b = model.bias.item()
Get bias
print(f"Learned equation: y = {learned_w:.2f} * x + {learned_b:.2f} (Target: 2.50 * x + 1.00)")
Display result
Click "Copy for Colab", open Google Colab, paste into a single cell, and run.
1 # ========================================================= 2 # Complete PyTorch Training Loop from Scratch 3 # Prepared for Google Colab (Run with Shift + Enter) 4 # ========================================================= 5 6 # Step 1: Install required packages 7 !pip install torch 8 9 # Step 2: Import libraries 10 import torch 11 import torch.nn as nn 12 import torch.optim as optim 13 14 # Step 3: Run Demonstration 15 # Synthetic dataset: y = 2.5 * x + 1.0 16 X = torch.randn(100, 1) 17 y = 2.5 * X + 1.0 + torch.randn(100, 1) * 0.1 # With noise 18 19 # Define linear model: 1 input -> 1 output 20 model = nn.Linear(1, 1) 21 criterion = nn.MSELoss() 22 optimizer = optim.SGD(model.parameters(), lr=0.1) 23 24 # The 5-Step PyTorch Training Loop: 25 for epoch in range(50): 26 optimizer.zero_grad() # 1. Zero gradients 27 predictions = model(X) # 2. Forward pass 28 loss = criterion(predictions, y) # 3. Calculate loss 29 loss.backward() # 4. Backward pass 30 optimizer.step() # 5. Optimizer step 31 32 learned_w = model.weight.item() 33 learned_b = model.bias.item() 34 print(f"Learned equation: y = {learned_w:.2f} * x + {learned_b:.2f} (Target: 2.50 * x + 1.00)")
Clears gradient buffers.
Generates predictions and evaluates MSE against noisy targets.
Computes analytical gradients and updates weights; converges to w β 2.50, b β 1.00.
100 synthetic data points following y = 2.5x + 1.0
Learned equation: y = 2.50 * x + 1.00 (Target: 2.50 * x + 1.00)
The canonical 5-step PyTorch loop converged on the exact true physical relationship in 50 iterations.
CNN, MNIST dataset, backpropagation, loss functions, and optimization.
Test your understanding with these questions. Remember, this is for learning, not examination!