Please enable JavaScript to use CodeHS

AI Engineer

Build your own tiny LLM

Industry models are huge, but the recipe is the same at any scale. This tutorial trains a small transformer on a real-looking corpus.

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.

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.

Tokenise

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.

tiny_tokenizer.py
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))
Output
vocab size: 22

Line-by-line: tiny_tokenizer.py

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

  1. import re, collections — Import the re library so we can use its built-in tools.
  2. words = [' '.join(list(w)) + ' </w>' for w in text.split()] — Loop over the data one batch at a time.
  3. vocab = set(''.join(text.split())) — Prepare a dataset by splitting or formatting raw examples.
  4. for _ in range(10): — Loop over the data one batch at a time.
  5. for w in words: — Loop over the data one batch at a time.
  6. tok = w.split() — Prepare a dataset by splitting or formatting raw examples.
  7. for i in range(len(tok)-1): — Loop over the data one batch at a time.
  8. 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.


Train

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.

llm_train.py
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)
Output
logits shape: torch.Size([2, 8, 100])

Line-by-line: llm_train.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. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  4. class TinyGPT(nn.Module): — Define a custom TinyGPT class that tells PyTorch how to fetch one example.
  5. def __init__(self, vocab, d, heads, layers): — Define the __init__ function, which describes a step in the data or model pipeline.
  6. self.blocks = nn.ModuleList([ — Subclass nn.Module, the base class for every PyTorch neural network.
  7. for _ in range(layers) — Loop over the data one batch at a time.
  8. self.head = nn.Linear(d, vocab) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  9. def forward(self, x): — Define the forward function, which describes a step in the data or model pipeline.
  10. for block in self.blocks: — Loop over the data one batch at a time.
  11. x = torch.randint(0, 100, (2, 8)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  12. 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

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.


Quick quiz

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.