Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- accuracy
- The fraction of predictions that are correct. It can be misleading when classes are imbalanced.
- batch
- A small group of examples processed together. Batches let us estimate gradients quickly and use hardware efficiently.
- epoch
- One full pass through the entire training dataset.
- gradient
- A vector of partial derivatives showing how much each parameter affects the loss.
- loss
- A number that measures how wrong the model is. Training tries to minimize loss.
- model
- A function with learnable parameters that maps inputs to outputs.
- optimizer
- An algorithm, like SGD or Adam, that updates model weights using gradients.
- parameters
- The collection of learnable numbers inside a model.
Custom datasets and dataloaders
A Dataset is an interface: given an index, return features and a label. A DataLoader batches, shuffles, and parallelises loading. Separating data from model code makes experiments reproducible.
import torch
from torch.utils.data import Dataset, DataLoader
class NumberDataset(Dataset):
def __init__(self, n):
self.x = torch.randn(n, 2)
self.y = (self.x.sum(dim=1) > 0).long()
def __len__(self):
return len(self.y)
def __getitem__(self, i):
return self.x[i], self.y[i]
train_loader = DataLoader(NumberDataset(1000), batch_size=32, shuffle=True)
xb, yb = next(iter(train_loader))
print('batch shapes:', xb.shape, yb.shape)
batch shapes: torch.Size([32, 2]) torch.Size([32])
Line-by-line: dataset.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.from torch.utils.data import Dataset, DataLoader— Import tools from thetorch.utils.datapackage.class NumberDataset(Dataset):— Define a customNumberDatasetclass that tells PyTorch how to fetch one example.def __init__(self, n):— Define the__init__function, which describes a step in the data or model pipeline.self.x = torch.randn(n, 2)— Create a tensor filled with random numbers to use as fake data or initial weights.def __len__(self):— Define the__len__function, which describes a step in the data or model pipeline.def __getitem__(self, i):— Define the__getitem__function, which describes a step in the data or model pipeline.train_loader = DataLoader(NumberDataset(1000), batch_size=32, shuffle=True)— Define a custom Dataset. Given an index, it returns one training example.print('batch shapes:', xb.shape, yb.shape)— Print a result so we can see what the model learned.
Pop-in: Datasets and DataLoaders are plug adapters
They translate your raw data into the batches PyTorch expects. You can reuse the same training loop code even when the data source changes.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Production PyTorch'. Explain the section 'Custom datasets and dataloaders' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
A production training loop
A production loop handles checkpointing, validation, early stopping, and gradient clipping. Mixed precision speeds up training on modern GPUs with minimal accuracy loss.
import torch
import torch.nn as nn
model = nn.Linear(2, 2)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
best_loss = float('inf')
for epoch in range(3):
model.train()
total_loss = 0
for xb, yb in train_loader:
optimizer.zero_grad()
logits = model(xb)
loss = criterion(logits, yb)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
total_loss += loss.item()
avg = total_loss / len(train_loader)
print(f'epoch {epoch}: loss {avg:.4f}')
if avg < best_loss:
best_loss = avg
torch.save(model.state_dict(), 'best.pt')
epoch 0: loss 0.6931 epoch 1: loss 0.6929 epoch 2: loss 0.6927
Line-by-line: train_loop.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.import torch.nn as nn— Import thetorchlibrary so we can use its built-in tools.model = nn.Linear(2, 2)— Add a linear layer that multiplies inputs by a weight matrix and adds a bias.optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)— Create anAdamoptimizer that will update the model's weights using gradients.criterion = nn.CrossEntropyLoss()— ChooseCrossEntropyLossas the loss function; it tells the optimizer how wrong the predictions are.best_loss = float('inf')— Compute the loss, which measures how far the prediction is from the target.for epoch in range(3):— Start the training loop. Each epoch is one full pass through the dataset.model.train()— Put the model in training mode, enabling dropout and batch-normalization updates.total_loss = 0— Compute the loss, which measures how far the prediction is from the target.for xb, yb in train_loader:— Loop over the data one batch at a time.optimizer.zero_grad()— Clear out old gradients so they do not accumulate across steps.loss = criterion(logits, yb)— Compute the loss, which measures how far the prediction is from the target.loss.backward()— Compute gradients: how much each weight contributed to the loss.torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)— Cap the size of gradients to keep training stable.
Pop-in: You are seeing the same loop again
Almost every deep-learning script repeats the same four steps: predict, compute loss, backpropagate, update weights. Once you can spot that pattern, the rest is just details.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Production PyTorch'. Explain the section 'A production training loop' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Check yourself
Why clip gradients?
What does torch.nn.utils.clip_grad_norm_ prevent?
It caps the total gradient norm, preventing exploding gradients and making training more stable.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Production PyTorch'. The practice question 'Why clip gradients?' asks: What does torch.nn.utils.clip_grad_norm_ prevent? The answer is: It caps the total gradient norm, preventing exploding gradients and making training more stable.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Production PyTorch'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What does a DataLoader do?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Production PyTorch'. The quiz asks: What does a DataLoader do? The correct answer is: Batches, shuffles, and parallelises loading from a Dataset. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. Why checkpoint the best model?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Production PyTorch'. The quiz asks: Why checkpoint the best model? The correct answer is: To keep the version with lowest validation loss and avoid overfitting. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. What is mixed precision?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Production PyTorch'. The quiz asks: What is mixed precision? The correct answer is: Using lower precision floats to speed up training with little accuracy loss. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Next: transfer learning for computer vision.
Part of the CodeHS tutorial library.