Assignment 7b: BabyGPT
CSE 415: Introduction to Artificial Intelligence
The University of Washington, Seattle, Autumn 2026
horizontal bar
Due Wednesday, December 9, at 11:59 PM, via Gradescope (assignment "A7b"). There are no grace days for A7. Late work is accepted for three days, with a penalty, as in A6: submissions on Thursday, December 10 earn 80% credit, on Friday, December 11 60%, and on Saturday, December 12 40%. A7b closes at 11:59 PM on Saturday, December 12.
 
A7b is the second part of A7 (A7a, “Backprop and Baselines,” is due December 4). It is worth 85 points: Part 4 (30), Part 5 (20), and Part 6, the report (35), plus up to 25 points of extra credit. Use the same partner as in A7a, if any. You are permitted to use AI as a coding assistant; however, we recommend that you read the guidelines for prompting (see the ED post about prompting guidelines under "General" here). The report covers both A7a and A7b, including the general sections described on the Assignment Reports page and the models and tools you used for agentic programming.
 
Contents
Introduction

In A7a you built the pieces: backpropagation, the chain rule for text, n-gram baselines, and sampling. In A7b you put a neural network in place of the n-gram count table. BabyGPT is a small GPT-style transformer, about 356,000 parameters, that reads up to 64 characters of context. You will write its attention mechanism and forward pass, train it on the corpus you chose in A7a, and record what it writes as it learns: your own version of the NYT article. In the report you compare what happened with your A7a predictions.

The diagram below follows the data through BabyGPT, top to bottom. BabyGPT works on a batch of B = 32 windows at once, each window a run of T = 64 consecutive characters from the text. The shapes in parentheses are the sizes of the arrays (PyTorch tensors) at each stage; read (B, T, C) as “for each of the B windows and each of its T positions, a vector of C = 96 numbers.” V is the vocabulary size (the number of distinct characters in the corpus).

  Input: the character ids                             shape (B, T): one integer per character
     |
     v
  Embedding: replace each id by a vector of C numbers
  (learned, one per character), and add a vector
  (also learned) for its position 0..T-1 in the window shape (B, T, C); call it x
     |
     v
  3 Blocks, one after another. Each Block does two steps:
     x = x + MultiHeadAttention(LayerNorm(x))         each position gathers information
                                                       from the positions before it
     x = x + FeedForward(LayerNorm(x))                each position's vector is transformed
                                                       on its own (the same small MLP at every position)
                                                       x keeps shape (B, T, C)
     |
     v
  Output: LayerNorm, then a Linear layer               shape (B, T, V): the logits, V scores per
                                                       position, one for each possible next character

The “x = x + ...” form is a residual connection: each step adds a correction to x rather than replacing it, which makes deep networks much easier to train. LayerNorm rescales each vector to mean 0 and variance 1 (it is provided).

At every position t of the window, BabyGPT predicts the character at position t+1, so one forward pass makes B·T predictions, and the loss is the average cross-entropy over all of them (your Q2 cross_entropy, for tensors). Training uses PyTorch's loss.backward(), which does for tensors exactly what your Value.backward() did for numbers. Self-attention (A6 Exercise 14) is the only place where positions exchange information; the causal mask makes sure position t sees only positions 0 to t.

The A7b starter code adds these files to your a7-starter-code/ folder:

  • Files you’ll edit:
    • babygpt.py — Part 4: one attention head, the transformer block, and the model.
    • train.py — Part 5: batches, evaluation, and the training loop. The command-line program at the bottom is provided.
    • a7b_report.txt — Part 6: the report template.
  • Files you will not edit:
    • runtools.py — tools for the report: sample at several temperatures, plot the loss curve, and the partners' 2 × 2 cross-evaluation.
    • extras/ — one script for each extra-credit option.
    • autograder.py — the same autograder as in A7a, now with Q6–Q8.

Your tinygrad.py and lm_basics.py stay in the folder: train.py uses your NGramModel for the bigram baseline and your sample_next to generate text. If they still have bugs, fix them now (they are not graded again).

Getting Started

Unzip the A7b starter code into the folder that holds your A7a work (it unpacks into a7-starter-code/). It replaces autograder.py with the full version and does not touch your A7a files. Then install PyTorch and matplotlib. On a laptop, the CPU-only version of PyTorch is enough:

pip install torch matplotlib                                               # macOS and Windows
pip install torch --index-url https://download.pytorch.org/whl/cpu        # Linux (CPU-only, smaller)
pip install matplotlib

Where to run. Training BabyGPT for 3,000 steps takes about 3 minutes on our 8-core test machine, and should take about 4 to 10 minutes on a recent laptop. If your laptop is much slower, or PyTorch won't install on it, you can use Google Colab instead:

  • Google Colab (free, with a Google account): upload your folder, then run the same commands in a notebook cell with a ! in front, e.g. !python train.py --corpus austen --device cuda after choosing a GPU runtime.

Run the autograder for A7b with python autograder.py --part b (or -q q6 for one question). The Q8 test trains a small model for about 10 seconds.

Part 4: The Transformer (30 points)

Q6: One Head of Causal Self-Attention (15 points)

In babygpt.py, write Head.forward. For each position, the head computes a query, a key and a value vector (the three Linear layers are provided); the score of position j for position i is the dot product of i’s query with j’s key, divided by √head_size; scores for positions j > i are set to −∞ (the causal mask), so softmax gives them weight 0; and the output at i is the weighted sum of the value vectors. This is A6 Exercise 14(c)–(d), for a whole batch at once:

  q, k, v = query(x), key(x), value(x)                    each (B, T, H)
  scores  = q @ kT / sqrt(H)                          (B, T, T)
  scores  = scores with -inf wherever tril[:T, :T] == 0
  weights = softmax(scores) over the last dimension       (B, T, T); rows sum to 1
  out     = weights @ v                                   (B, T, H)

Also save weights.detach() in self.last_att; the extra-credit tools read it. The tests check the output against this formula, that changing later positions never changes earlier outputs, that the weights for future positions are exactly 0, and the scaling. Our solution is 8 lines.

Q7: The Block and the Model (15 points)

Write Block.forward (two residual connections, each applied after a LayerNorm, as in the diagram above) and BabyGPT.forward: add the token and position embeddings, run the blocks in order, apply the final LayerNorm and the output Linear, and, if targets are given, compute the mean cross-entropy loss with F.cross_entropy (reshape the logits to (B·T, V) and the targets to (B·T)). MultiHeadAttention, FeedForward and the weight initialization are provided. One of the tests checks that an untrained model's loss is close to ln(V). Why should it be? (It's a good thing to understand before you train.) About 12 lines.

Part 5: Training BabyGPT (20 points)

Q8: Batches, Evaluation, and the Training Loop (20 points)

In train.py, write get_batch (random windows of the training text, with targets shifted one character to the left), estimate_loss (the average loss on a fixed set of batches, for the training and validation text, with gradients turned off), and train: the loop of forward pass, loss.backward(), and optimizer step, which also measures the losses every 100 steps and saves a 200-character sample at steps 0, 100, 250, 500, 1000, 2000 and 3000 (the docstrings give the details). The tests check batch shapes and the one-character shift, that evaluation is reproducible, and that training on a small text brings the validation loss below the bigram baseline. About 50 lines.

Then train BabyGPT on your corpus:

python train.py --corpus austen --tiny     # about 15 seconds: a quick check of your code
python train.py --corpus austen            # the real run: 3,000 steps

The real run writes runs/austen-default/: run.json (the losses and samples), snapshots.txt (the samples, readable), and model.pt (the trained model). Partners: train one model on each partner's corpus.

Part 6: Report (35 points)

Q9: Report (35 points)

The starter code includes a7b_report.txt, your report for all of A7. It has the general sections from the Assignment Reports page (Parts A, C and D: process, reflection, and the record of your AI use for A7a and A7b; required, no points of their own), a partnership retrospective (required), Part E for extra credit, and these graded questions:

  • R1. Your own NYT article (8). Your snapshots, what the model has learned by each step, and your loss curve (python runtools.py plot runs/<yours>-default).
  • R2. Predictions vs. what happened (7). Your A7a predictions next to the results, and an explanation of the biggest miss.
  • R3. Baselines, and why a network (6). BabyGPT vs. your n-gram models; table sizes vs. parameter count, as in A6 Exercise 12; how a network generalizes to contexts it never saw. Partners add the 2 × 2 table from python runtools.py cross.
  • R4. Temperature (5). Samples at T = 0, 0.5, 1 and 2 (python runtools.py sample), explained with softmax(logits / T).
  • R5. Attention (5). A short experiment: what happens when you remove the causal mask (predict first!), and why the scores are divided by √head_size.
  • R6. AI usage reflection (4).
Extra Credit (up to 25 points in all)

Each option has a script in extras/ that runs your trained model and saves a figure. Most of the credit is for what you write in Part E of the report about what the results show, not for running the script. You may do any combination of options; the points add up to at most 25 in all. You don't need a GPU of your own: EC1, EC2 and EC4 together are worth up to 24 points, and EC3 can be done with a free Google Colab GPU.

  • EC1. Embeddings (up to 8 points). (a) Plot your model's 96-number character embeddings in two dimensions (by PCA) and list each letter's nearest neighbors. Which characters does the model treat as similar, and why might it? (b) With a small set of pretrained word vectors (provided), find nearest neighbors and try analogies such as king − man + woman (as in A6 Exercise 14(a)). Why can't your character model do this?
  • EC2. Temperature extremes (up to 8 points). (a) Generate from your model at temperatures from 0 to 5 and measure, for each: how often it repeats itself, the fraction of real words, and how much of its output is copied from the training text. (b) Ask a real language model a set of 30 factual questions about the books in data/ (with answers provided), five times each at several temperatures, and measure accuracy and how much the answers vary. Where does “creative” turn into “wrong”? The model is Qwen2.5-0.5B-Instruct, small enough to run on your own computer (pip install transformers; it downloads about 1 GB the first time): python extras/ec2_llm.py --local Qwen/Qwen2.5-0.5B-Instruct --limit 10 --temps 0 1 2. This shortened run asks 10 of the questions at 3 temperatures; the full run (all 30 questions, 5 temperatures) can take about 40 minutes on a laptop CPU. If you already have another model available through an OpenAI-compatible API, you may use it instead (--base-url and --model); say which model in Part E.
  • EC3. Laptop vs. GPU (up to 5 points). Time training (tokens per second, printed by train.py) for the default model and the 20-times-larger --config wide (7.2 million parameters), on your laptop and on a GPU (a free Google Colab GPU runtime is enough). Where does the GPU help, where doesn't it, and why?
  • EC4. Inside the transformer (up to 8 points). (a) Heat maps of the attention weights of each head for a prompt of your choice. (b) Context: take one character in several contexts (the e at the end of “the”, “be”, “she”) and plot how far its vector moves from its context-free starting point after each block. (c) Switch off one head at a time and rank the heads by how much the validation loss rises.
  • EC5. Individuals only: a second corpus (up to 3 points). Train a second model on another corpus and do the partners' 2 × 2 cross-evaluation (R3).
What to Turn In

Turn in the following files to Gradescope, in the assignment “A7b”:

babygpt.py
train.py
a7b_report_firstname_lastname.txt
loss_curve.png                     (from runs/<yours>-default/)
run.json                           (from runs/<yours>-default/)

Partners: turn in the loss_curve.png and run.json of both runs, renamed loss_curve_<corpus>.png and run_<corpus>.json. Extra credit: also the figures named in Part E. Don't turn in model.pt or the corpora. Before submitting, run python autograder.py.

Partnerships. Fill in the partnership comment at the top of babygpt.py and train.py as in A7a, make a group submission on Gradescope with your partner, and complete the partnership retrospective in the report.

Updates and Corrections
 
If needed, updates and corrections will be posted here, and/or in ED.
 
Last updated 2026-11-29.