Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- epoch
- One full pass through the entire training dataset.
- gradient
- A vector of partial derivatives showing how much each parameter affects the loss.
- learning rate
- How far the optimizer moves the weights each step. Too big and training explodes; too small and it crawls.
- 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.
- softmax
- A function that turns logits into probabilities that add up to 1.
Building a text dataloader
Training on a whole book at once is impossible. A dataloader slices the token stream into fixed-size blocks, groups them into batches, and feeds them to the model. The target for each input is the same sequence shifted left by one.
import torch
from torch.utils.data import Dataset, DataLoader
class TextDataset(Dataset):
def __init__(self, tokens, block_size):
self.tokens = tokens
self.block_size = block_size
def __len__(self):
return len(self.tokens) - self.block_size - 1
def __getitem__(self, i):
x = torch.tensor(self.tokens[i:i+self.block_size], dtype=torch.long)
y = torch.tensor(self.tokens[i+1:i+self.block_size+1], dtype=torch.long)
return x, y
tokens = list(range(1000))
loader = DataLoader(TextDataset(tokens, 8), batch_size=2, shuffle=False)
x, y = next(iter(loader))
print('x shape:', x.shape)
print('first input:', x[0].tolist())
print('first target:', y[0].tolist())
x shape: torch.Size([2, 8]) first input: [0, 1, 2, 3, 4, 5, 6, 7] first target: [1, 2, 3, 4, 5, 6, 7, 8]
Line-by-line: dataloader.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 TextDataset(Dataset):— Define a customTextDatasetclass that tells PyTorch how to fetch one example.def __init__(self, tokens, block_size):— Define the__init__function, which describes a step in the data or model pipeline.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.x = torch.tensor(self.tokens[i:i+self.block_size], dtype=torch.long)— Create a PyTorch tensor from raw Python numbers.y = torch.tensor(self.tokens[i+1:i+self.block_size+1], dtype=torch.long)— Create a PyTorch tensor from raw Python numbers.loader = DataLoader(TextDataset(tokens, 8), batch_size=2, shuffle=False)— Define a custom Dataset. Given an index, it returns one training example.print('x shape:', x.shape)— Print a result so we can see what the model learned.print('first input:', x[0].tolist())— Print a result so we can see what the model learned.print('first target:', y[0].tolist())— 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: Build a Mini GPT — Deep Dive'. Explain the section 'Building a text dataloader' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Temperature, top-k, and top-p
Greedy decoding picks the most likely token and often loops. Temperature softens or sharpens the probability distribution. Top-k restricts sampling to the k most likely tokens. Top-p (nucleus) restricts to the smallest set whose cumulative probability exceeds p.
import torch
import torch.nn.functional as F
logits = torch.tensor([2.0, 1.0, 0.1, 0.05, 0.01])
for temp in [0.5, 1.0, 2.0]:
probs = F.softmax(logits / temp, dim=-1)
print(f'temp={temp}:', probs.round(decimals=3).tolist())
temp=0.5: [0.665, 0.244, 0.061, 0.022, 0.009] temp=1.0: [0.522, 0.192, 0.086, 0.064, 0.054] temp=2.0: [0.335, 0.187, 0.135, 0.123, 0.117]
Line-by-line: sampling.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.functional as F— Import thetorchlibrary so we can use its built-in tools.logits = torch.tensor([2.0, 1.0, 0.1, 0.05, 0.01])— Create a PyTorch tensor from raw Python numbers.for temp in [0.5, 1.0, 2.0]:— Loop over the data one batch at a time.probs = F.softmax(logits / temp, dim=-1)— Convert logits into probabilities that add up to 1.print(f'temp={temp}:', probs.round(decimals=3).tolist())— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Build a Mini GPT — Deep Dive'. Explain the section 'Temperature, top-k, and top-p' 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 real training loop
A production loop tracks train and validation loss, saves checkpoints, and stops early if validation loss rises. It also logs learning rate, gradient norm, and sample generations.
import torch
# Simplified training loop outline
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
best_val = float('inf')
for epoch in range(10):
model.train()
for xb, yb in train_loader:
logits = model(xb)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), yb.view(-1))
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
# validation and checkpointing omitted for brevity
print('training loop complete')
training loop complete
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.optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)— Create anAdamoptimizer that will update the model's weights using gradients.for epoch in range(10):— 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.for xb, yb in train_loader:— Loop over the data one batch at a time.loss = F.cross_entropy(logits.view(-1, logits.size(-1)), yb.view(-1))— Compute the cross-entropy loss, a common measure for classification.optimizer.zero_grad()— Clear out old gradients so they do not accumulate across steps.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.optimizer.step()— Update the model weights using the gradients the optimizer just computed.print('training loop complete')— Print a result so we can see what the model learned.
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.
Why shift targets by one token?
In language modeling, why is y[i] == x[i+1]?
The model predicts the next token at each position, so the target for position i is the token that follows it.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT — Deep Dive'. The practice question 'Why shift targets by one token?' asks: In language modeling, why is y[i] == x[i+1]? The answer is: The model predicts the next token at each position, so the target for position i is the token that follows it.. 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: Build a Mini GPT — Deep Dive'. Explain the section 'A real 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
What does temperature control?
A lower temperature makes sampling more deterministic. Why?
It sharpens the softmax distribution, concentrating probability on the most likely tokens.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT — Deep Dive'. The practice question 'What does temperature control?' asks: A lower temperature makes sampling more deterministic. Why? The answer is: It sharpens the softmax distribution, concentrating probability on the most likely tokens.. 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: Build a Mini GPT — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What is the target in a language-model dataloader?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT — Deep Dive'. The quiz asks: What is the target in a language-model dataloader? The correct answer is: The input sequence shifted left by one token. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. What does a lower temperature do?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT — Deep Dive'. The quiz asks: What does a lower temperature do? The correct answer is: Makes the distribution sharper and more deterministic. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. Why checkpoint the model on validation loss?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT — Deep Dive'. The quiz asks: Why checkpoint the model on validation loss? The correct answer is: To keep the version that generalises best and avoid overfitting. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Finally, use reinforcement learning to align the model.
Part of the CodeHS tutorial library.