Please enable JavaScript to use CodeHS

AI Engineer

Train at scale

Moving from notebooks to production means robust data loaders, checkpointing, and training hygiene. This tutorial shows the loop that every PyTorch project uses.

AI ~15 min Programmer
Vocabulary

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.

Dataset

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.

dataset.py
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)
Output
batch shapes: torch.Size([32, 2]) torch.Size([32])

Line-by-line: dataset.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. from torch.utils.data import Dataset, DataLoader — Import tools from the torch.utils.data package.
  3. class NumberDataset(Dataset): — Define a custom NumberDataset class that tells PyTorch how to fetch one example.
  4. def __init__(self, n): — Define the __init__ function, which describes a step in the data or model pipeline.
  5. self.x = torch.randn(n, 2) — Create a tensor filled with random numbers to use as fake data or initial weights.
  6. def __len__(self): — Define the __len__ function, which describes a step in the data or model pipeline.
  7. def __getitem__(self, i): — Define the __getitem__ function, which describes a step in the data or model pipeline.
  8. train_loader = DataLoader(NumberDataset(1000), batch_size=32, shuffle=True) — Define a custom Dataset. Given an index, it returns one training example.
  9. 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.


Loop

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.

train_loop.py
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')
Output
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.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn as nn — Import the torch library so we can use its built-in tools.
  3. model = nn.Linear(2, 2) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  4. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) — Create an Adam optimizer that will update the model's weights using gradients.
  5. criterion = nn.CrossEntropyLoss() — Choose CrossEntropyLoss as the loss function; it tells the optimizer how wrong the predictions are.
  6. best_loss = float('inf') — Compute the loss, which measures how far the prediction is from the target.
  7. for epoch in range(3): — Start the training loop. Each epoch is one full pass through the dataset.
  8. model.train() — Put the model in training mode, enabling dropout and batch-normalization updates.
  9. total_loss = 0 — Compute the loss, which measures how far the prediction is from the target.
  10. for xb, yb in train_loader: — Loop over the data one batch at a time.
  11. optimizer.zero_grad() — Clear out old gradients so they do not accumulate across steps.
  12. loss = criterion(logits, yb) — Compute the loss, which measures how far the prediction is from the target.
  13. loss.backward() — Compute gradients: how much each weight contributed to the loss.
  14. 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

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.


Quick quiz

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.