Please enable JavaScript to use CodeHS

AI Engineer

Build a mini GPT

A GPT is just a stack of transformer blocks trained to predict the next token. In this tutorial you will see the full architecture in PyTorch and the training loop that turns a random model into a text generator.

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.

attention
A mechanism where each output position mixes input positions, weighted by how relevant they are.
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.
language model
A model that predicts the next token (or fills in missing tokens) in a sequence of text.
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.

Architecture

What GPT actually is

GPT stands for Generative Pre-trained Transformer. It is an autoregressive model: it predicts the next token, then feeds that token back in to predict the one after that.

The architecture has four pieces: token embeddings, positional encodings, a stack of transformer blocks, and a final linear layer that maps each token's hidden state to a probability distribution over the vocabulary.

Core idea: GPT is 'just' next-token prediction repeated. The power comes from scale: billions of parameters, trillions of tokens, and many transformer blocks.

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'. Explain the section 'What GPT actually is' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Causal attention

Causal (masked) self-attention

During training, the model sees the whole sentence but it should only use earlier tokens to predict each next token. Causal attention masks out future positions by setting their scores to negative infinity before softmax.

This is why GPT cannot peek at the answer while learning. At generation time, the same mask lets it predict one new token at a time.

causal_mask.py
import torch

seq_len = 5
mask = torch.tril(torch.ones(seq_len, seq_len))
print(mask)
Output
tensor([[1., 0., 0., 0., 0.],
        [1., 1., 0., 0., 0.],
        [1., 1., 1., 0., 0.],
        [1., 1., 1., 1., 0.],
        [1., 1., 1., 1., 1.]])

Line-by-line: causal_mask.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. print(mask) — 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'. Explain the section 'Causal (masked) self-attention' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Code

A mini GPT in PyTorch

Below is a tiny, self-contained GPT. It has an embedding layer, a single transformer block, and an output head. Real models repeat the block many times and add layer normalization and dropout, but the skeleton is the same.

mini_gpt.py
import torch
import torch.nn as nn
import torch.nn.functional as F

class MiniGPT(nn.Module):
    def __init__(self, vocab_size, embed_dim, seq_len, n_heads):
        super().__init__()
        self.token_embed = nn.Embedding(vocab_size, embed_dim)
        self.pos_embed   = nn.Embedding(seq_len, embed_dim)
        self.attn = nn.MultiheadAttention(embed_dim, n_heads, batch_first=True)
        self.ffn = nn.Sequential(
            nn.Linear(embed_dim, 4 * embed_dim),
            nn.ReLU(),
            nn.Linear(4 * embed_dim, embed_dim),
        )
        self.lm_head = nn.Linear(embed_dim, vocab_size)
        self.seq_len = seq_len

    def forward(self, x, return_hidden=False):
        b, t = x.size()
        pos = torch.arange(t, device=x.device).unsqueeze(0)
        x = self.token_embed(x) + self.pos_embed(pos)

        mask = torch.tril(torch.ones(t, t, device=x.device)) == 0
        x = x + self.attn(x, x, x, attn_mask=mask, is_causal=True)[0]
        x = x + self.ffn(x)
        if return_hidden:
            return x                      # (b, t, embed_dim)
        logits = self.lm_head(x)        # (b, t, vocab_size)
        return logits

model = MiniGPT(vocab_size=100, embed_dim=32, seq_len=16, n_heads=4)
ids = torch.randint(0, 100, (1, 10))
logits = model(ids)
print("logits shape:", logits.shape)   # (1, 10, 100)
Output
logits shape: torch.Size([1, 10, 100])

Line-by-line: mini_gpt.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 MiniGPT(nn.Module): — Define a custom MiniGPT class that tells PyTorch how to fetch one example.
  5. def __init__(self, vocab_size, embed_dim, seq_len, n_heads): — Define the __init__ function, which describes a step in the data or model pipeline.
  6. nn.Linear(embed_dim, 4 * embed_dim), — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  7. nn.Linear(4 * embed_dim, embed_dim), — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  8. self.lm_head = nn.Linear(embed_dim, vocab_size) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  9. def forward(self, x, return_hidden=False): — Define the forward function, which describes a step in the data or model pipeline.
  10. ids = torch.randint(0, 100, (1, 10)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  11. print("logits shape:", logits.shape) # (1, 10, 100) — 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'. Explain the section 'A mini GPT in PyTorch' 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

The training loop

To train, take a sequence, shift it by one, and ask the model to predict each next token. The loss is cross-entropy across the whole sequence.

train_gpt.py
import torch
import torch.nn.functional as F

# model is a MiniGPT from above
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

# fake batch of token IDs (batch, seq_len)
input_ids = torch.randint(0, 100, (8, 16))
target_ids = torch.roll(input_ids, -1, dims=1)

for epoch in range(100):
    logits = model(input_ids)
    loss = F.cross_entropy(logits.view(-1, 100), target_ids.view(-1))

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if epoch % 20 == 0:
        print(f"epoch {epoch}: loss = {loss.item():.3f}")
Output
epoch 0: loss = 4.605
epoch 20: loss = 3.812
epoch 40: loss = 3.401
epoch 60: loss = 3.124
epoch 80: loss = 2.901

Line-by-line: train_gpt.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.functional as F — Import the torch library so we can use its built-in tools.
  3. optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) — Create an Adam optimizer that will update the model's weights using gradients.
  4. input_ids = torch.randint(0, 100, (8, 16)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  5. for epoch in range(100): — Start the training loop. Each epoch is one full pass through the dataset.
  6. loss = F.cross_entropy(logits.view(-1, 100), target_ids.view(-1)) — Compute the cross-entropy loss, a common measure for classification.
  7. optimizer.zero_grad() — Clear out old gradients so they do not accumulate across steps.
  8. loss.backward() — Compute gradients: how much each weight contributed to the loss.
  9. optimizer.step() — Update the model weights using the gradients the optimizer just computed.
  10. print(f"epoch {epoch}: loss = {loss.item():.3f}") — Compute the loss, which measures how far the prediction is from the target.

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.

Loss drops as the model learns which tokens follow which. On real data, training continues for days or weeks across many GPUs.

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'. Explain the section 'The 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.


Generate

Generating text

Generation is a loop: feed the current sequence into the model, get logits for the last position, sample a token, append it, and repeat.

generate.py
@torch.no_grad()
def generate(model, start_ids, max_new=20):
    generated = list(start_ids)
    for _ in range(max_new):
        ids = torch.tensor([generated[-model.seq_len:]])
        logits = model(ids)[0, -1, :]
        probs = F.softmax(logits, dim=-1)
        next_id = torch.multinomial(probs, num_samples=1).item()
        generated.append(next_id)
    return generated
Output
# returns a list of token IDs that can be decoded back to text

Line-by-line: generate.py

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

  1. @torch.no_grad() — Disable gradient computation during evaluation to save memory and speed.
  2. def generate(model, start_ids, max_new=20): — Define the generate function, which describes a step in the data or model pipeline.
  3. for _ in range(max_new): — Loop over the data one batch at a time.
  4. ids = torch.tensor([generated[-model.seq_len:]]) — Create a PyTorch tensor from raw Python numbers.
  5. probs = F.softmax(logits, dim=-1) — Convert logits into probabilities that add up to 1.

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'. Explain the section 'Generating text' 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 is attention causal during training?

What would happen if the model could look at future tokens while learning to predict the next one?

The model would cheat by copying the answer. Causal masking forces it to learn from only past tokens, which is the same constraint it faces at generation time.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT'. The practice question 'Why is attention causal during training?' asks: What would happen if the model could look at future tokens while learning to predict the next one? The answer is: The model would cheat by copying the answer. Causal masking forces it to learn from only past tokens, which is the same constraint it faces at generation time.. 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'. 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 GPT predict?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT'. The quiz asks: What does a GPT predict? The correct answer is: The next token given the previous tokens. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. What does causal masking prevent?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT'. The quiz asks: What does causal masking prevent? The correct answer is: The model from using future tokens during training. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What is the shape of the output logits for a batch of (8, 32) token IDs and a vocabulary of size 100?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Build a Mini GPT'. The quiz asks: What is the shape of the output logits for a batch of (8, 32) token IDs and a vocabulary of size 100? The correct answer is: (8, 32, 100). Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Train a GPT end to end: dataloaders, validation, checkpoints, and sampling strategies.

Part of the CodeHS tutorial library.