Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- 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.
- tokenizer
- A tool that splits text into tokens and maps them to integer IDs.
- training loop
- The repeated cycle of forward pass, loss, backward pass, and optimizer step that trains a model.
- transformer
- An architecture that uses attention to process sequences in parallel instead of one step at a time.
- DataLoader
- A PyTorch object that batches, shuffles, and loads data in parallel for training loops.
- embedding
- A learned vector that represents a token, word, or item in a continuous numerical space.
- pipeline
- A scikit-learn object that chains preprocessing steps and a model so the same transformations are applied during training and inference.
Build a tiny byte-pair tokeniser
You can use a pre-existing tokenizer or train one on your corpus. The key idea is the same: map common subword pieces to ids so the model sees shorter sequences.
import re, collections
text = 'the quick brown fox jumps over the lazy dog. the fast fox jumps'
words = [' '.join(list(w)) + ' </w>' for w in text.split()]
vocab = set(''.join(text.split()))
for _ in range(10):
pairs = collections.Counter()
for w in words:
tok = w.split()
for i in range(len(tok)-1):
pairs[(tok[i], tok[i+1])] += 1
if not pairs:
break
best = pairs.most_common(1)[0][0]
vocab.add(''.join(best))
print('vocab size:', len(vocab))
vocab size: 22
Line-by-line: tiny_tokenizer.py
Read this slowly. Each line does one small, concrete thing.
import re, collections— Import therelibrary so we can use its built-in tools.words = [' '.join(list(w)) + ' </w>' for w in text.split()]— Loop over the data one batch at a time.vocab = set(''.join(text.split()))— Prepare a dataset by splitting or formatting raw examples.for _ in range(10):— Loop over the data one batch at a time.for w in words:— Loop over the data one batch at a time.tok = w.split()— Prepare a dataset by splitting or formatting raw examples.for i in range(len(tok)-1):— Loop over the data one batch at a time.print('vocab size:', len(vocab))— 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: Train a Small LLM from Scratch'. Explain the section 'Build a tiny byte-pair tokeniser' 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 tiny training loop
A from-scratch LLM needs a dataloader that slides a window over tokenised text, a causal transformer, and a cross-entropy loss over all positions. Training to convergence takes time, but the loop is compact.
import torch
import torch.nn as nn
import torch.nn.functional as F
class TinyGPT(nn.Module):
def __init__(self, vocab, d, heads, layers):
super().__init__()
self.emb = nn.Embedding(vocab, d)
self.pos = nn.Embedding(64, d)
self.blocks = nn.ModuleList([
nn.TransformerEncoderLayer(d, heads, d*4, batch_first=True)
for _ in range(layers)
])
self.head = nn.Linear(d, vocab)
def forward(self, x):
b, t = x.shape
x = self.emb(x) + self.pos(torch.arange(t, device=x.device))
for block in self.blocks:
x = block(x)
return self.head(x)
model = TinyGPT(100, 32, 2, 2)
x = torch.randint(0, 100, (2, 8))
logits = model(x)
print('logits shape:', logits.shape)
logits shape: torch.Size([2, 8, 100])
Line-by-line: llm_train.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.import torch.nn.functional as F— Import thetorchlibrary so we can use its built-in tools.class TinyGPT(nn.Module):— Define a customTinyGPTclass that tells PyTorch how to fetch one example.def __init__(self, vocab, d, heads, layers):— Define the__init__function, which describes a step in the data or model pipeline.self.blocks = nn.ModuleList([— Subclassnn.Module, the base class for every PyTorch neural network.for _ in range(layers)— Loop over the data one batch at a time.self.head = nn.Linear(d, vocab)— Add a linear layer that multiplies inputs by a weight matrix and adds a bias.def forward(self, x):— Define theforwardfunction, which describes a step in the data or model pipeline.for block in self.blocks:— Loop over the data one batch at a time.x = torch.randint(0, 100, (2, 8))— Create a tensor filled with random numbers to use as fake data or initial weights.print('logits shape:', logits.shape)— Print a result so we can see what the model learned.
Pop-in: Pre-trained models are cheat sheets
You do not have to teach the model English from scratch. You download a model that already knows English, then fine-tune it for your exact task.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Train a Small LLM from Scratch'. Explain the section 'A tiny 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 use a sliding window dataloader?
What does sliding a block_size window over tokenised text give you?
It produces many overlapping training examples from one long document, with each input paired to a target shifted by one token.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Train a Small LLM from Scratch'. The practice question 'Why use a sliding window dataloader?' asks: What does sliding a block_size window over tokenised text give you? The answer is: It produces many overlapping training examples from one long document, with each input paired to a target shifted by one token.. 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: Train a Small LLM from Scratch'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What loss is used for language modeling?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Train a Small LLM from Scratch'. The quiz asks: What loss is used for language modeling? The correct answer is: Cross-entropy over next-token predictions. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. Why are positional embeddings needed?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Train a Small LLM from Scratch'. The quiz asks: Why are positional embeddings needed? The correct answer is: To tell the model the order of tokens. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. What does a sliding window produce?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Train a Small LLM from Scratch'. The quiz asks: What does a sliding window produce? The correct answer is: Many overlapping (input, target) pairs from one document. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Next: efficient fine-tuning with LoRA and QLoRA.
Part of the CodeHS tutorial library.