Assignment 7a: Backprop and Baselines
CSE 415: Introduction to Artificial Intelligence
The University of Washington, Seattle, Autumn 2026
horizontal bar
Due Friday, December 4, at 11:59 PM, via Gradescope (assignment "A7a"). There are no grace days for A7. Late work is accepted for three days, with a penalty, as in A6: submissions on Saturday, December 5 earn 80% credit, on Sunday, December 6 60%, and on Monday, December 7 40%. A7a closes at 11:59 PM on Monday, December 7.
 
A7 has two parts with separate deadlines. A7a (this page, 60 points) builds the tools: backpropagation, n-gram language models, and sampling. A7b (85 points, due Wednesday, December 9) uses them to build, train, and study BabyGPT, a small GPT that learns to write like the author of your choice. Together they are worth 145 points.
 
You may do this assignment either individually or in a partnership of two; keep the same partner for A7a and A7b. If you work in a partnership, you'll be turning in one set of files for the partnership (see What to Turn In). You are permitted to use AI as a coding assistant in this assignment; however, we recommend that you read the guidelines for prompting (see the ED post about prompting guidelines under "General" here) and keep your prompting records from the start: the A7b report covers both parts, including the models and tools you used for agentic programming (see the Assignment Reports page).
 
Contents
Introduction

Reading (before you write your predictions in Part 3). Aatish Bhatia, “Let Us Show You How GPT Works — Using Jane Austen,” The New York Times, April 2023 (free through the UW Libraries' NYT access). The article trains a small model, BabyGPT, on Jane Austen's novels and shows what it writes after 250, 500, … training steps: first random letters, then word-like strings, then something that reads, briefly, like Austen. In A7 you will do the same experiment yourself, with code you understand line by line.

A language model is a probability distribution over sequences of tokens (for us, characters). By the chain rule of probability, the joint distribution factors into one next-token distribution per position:

  P(t1, t2, ..., tN) = P(t1) · P(t2 | t1) · P(t3 | t1, t2) · ... · P(tN | t1, ..., tN-1)

So a language model needs just one ability: given a context, produce a distribution over the next token. Generating text is then repeated sampling. A6 asked you to do these steps by hand on tiny examples (backpropagation in Exercise 11; joint distributions of tokens in Exercise 12; softmax, temperature and sampling in Exercise 13). A7a has you write code that does them at scale:

  • Part 1 builds a miniature version of the machinery inside PyTorch: a Value class that records every arithmetic operation and then computes all the gradients by backpropagation. You'll use it to train a small network on XOR, the problem a single perceptron cannot solve.
  • Part 2 builds n-gram language models (a bigram model is the Markov chain of the Markov Models lecture, with characters as states), measures them with perplexity, and writes the sampling code that turns any model's output into text. In A7b, BabyGPT generates through the same sampling code, and your n-gram models are the baselines it has to beat.
  • Part 3 asks you to predict, before you train it, what BabyGPT will do.

A7a needs only standard Python: no NumPy and no PyTorch. (A7b uses PyTorch; installation instructions will be in A7b, along with a way to run it on Google Colab instead of your laptop.)

The starter code contains these files:

  • Files you’ll edit:
    • tinygrad.py — Part 1: the Value class, softmax and cross-entropy, a small multilayer network, and the XOR experiment.
    • lm_basics.py — Part 2: n-gram models, perplexity, and sampling.
    • a7a_predictions.txt — Part 3: the template for your predictions.
  • Files you will not edit:
    • autograder.py — the local autograder (A7a and, later, A7b).
    • data/ — the corpora: austen, shakespeare, federalist (the Federalist Papers), melville (Moby-Dick), holmes (Sherlock Holmes), grimm (Grimms' Fairy Tales), and names (about 32,000 first names, one per line). All are public domain; each is at most 1.2 million characters.
Learning with an AI Coding Assistant

An AI assistant can write every function in A7a in a few seconds; this code is famous, and the assistant has seen many versions of it. That is fine, and you may use it. But the code is not the point. The point is that after A7 you can explain, without help, how a network computes its gradients and how a language model writes text, because the final exam will ask you to (on paper, like A6). Some ways to get there with an assistant:

  • Before asking for a function, work one tiny case by hand (the docstrings give the formulas), then check the code against your hand result.
  • Ask the assistant to explain its code line by line, then explain it back in your own words in a comment. If you can't, ask again.
  • When a test fails, read the autograder's message and form your own hypothesis before pasting the error into the chat.
  • Do Part 3 yourself. Predictions copied from an AI teach you nothing, and the A7b report asks you to explain your own.
Getting Started

Download and unzip the A7a starter code. It unpacks into a folder a7-starter-code/; keep working in that folder, because the A7b starter code will add its files there. Python 3.10 or later is required (3.14 recommended).

Each function you write contains a line raise NotImplementedError(...); replace it with your code. Run the local autograder with

python autograder.py               # all of A7a, including the predictions check
python autograder.py -q q1         # one question
python autograder.py -v            # more detail about failures

The autograder checks what your functions do (values, gradients, probabilities), not how they are written. Gradescope runs the same tests plus a few hidden ones of the same kinds, so passing every local test is a good sign but not a guarantee of full credit. None of the tests uses the numbers from A6.

Part 1: Backpropagation by Hand (35 points)

A neural network computes its loss L through a long chain of small operations. Each Value object stores one number (data), the operation that produced it, and the Values it was computed from. Together they form a computational graph. For example, c = (a*b + 1).tanh() builds:

   a --\
        (*) --> a*b --\
   b --/               (+) --> a*b+1 --> (tanh) --> c
                1 ----/

Backpropagation computes dL/dx for every Value x in the graph by the chain rule, one node at a time, from the output back towards the inputs. Each operation contributes only its local derivative: if out = f(a, b), then

  a.grad += (d out / d a) * out.grad          b.grad += (d out / d b) * out.grad

This is the same calculation as A6 Exercise 11, organized so that a computer can do it for any network. In A7b, PyTorch's loss.backward() will do exactly this for you, for tensors with hundreds of thousands of numbers.

Q1: The Value Class (15 points)

In tinygrad.py, write the operations __add__, __mul__, __pow__ (for a numeric exponent), exp, log, tanh and relu. Each one creates the output Value and gives it a _backward function that adds the local derivative times out.grad to each input's grad (the docstrings give each local derivative). Then write backward(): get the graph's nodes in topological order with the provided topological_order(), set this node's grad to 1, and call every node's _backward() in reverse order. Subtraction, division, negation and sigmoid are provided; they are built from your operations, so they work once yours do.

Two things to get right. (1) Use +=, not =: a Value used twice (as in a*a, or one weight feeding two units) receives gradient from each use. (2) Call the _backward functions in reverse topological order, so that each node's gradient is complete before it is passed on.

The tests check values and derivatives of each operation, gradient accumulation (including a “diamond” graph), random expressions against numerical derivatives, and a graph 5,000 operations deep. Our solution adds about 50 lines, most of them in the seven operations.

Q2: Softmax, Cross-Entropy, and a Neuron (10 points)

Write softmax (subtract the largest logit before exponentiating, so large logits don't overflow), cross_entropy(logits, target) = −ln ptarget (the loss every language model in A7 minimizes), and Neuron.__call__ (weighted sum plus bias, then the activation). Layer and MLP are provided. The tests include a check that the gradient of the cross-entropy loss with respect to the logits is p − one_hot(target), and a numerical check of every gradient in a small MLP. About 12 lines.

Q3: XOR, Two Ways (10 points)

Write train_perceptron, using the training rule of the Perceptrons lecture (the same rule as A6 Exercise 10), and train_xor_mlp, which trains MLP(2, [4, 2]) on the four XOR examples by full-batch gradient descent: on each step, zero the gradients, compute the mean cross-entropy loss, call backward(), and move every parameter against its gradient. Then run

python tinygrad.py

to see the perceptron fail and the network succeed. The tests check one epoch of the perceptron rule step by step, that the perceptron learns AND but never classifies more than 3 of the 4 XOR points, and that your network classifies XOR perfectly for three random initializations. About 25 lines.

Part 2: n-gram Language Models and Sampling (20 points)

Characters are represented by integer ids (the provided Vocab class converts in both directions). Everything in lm_basics.py uses plain Python lists, so you can compare its results with the worked examples in lecture and in A6.

Q4: n-gram Models and Perplexity (10 points)

An n-gram model predicts the next character from the previous n−1 characters only, using counts from the training text, with add-k smoothing:

  P(x | ctx) = (count(ctx, x) + k) / (count(ctx) + k V)        V = vocabulary size

Without smoothing, any combination not seen in training would get probability 0, and so would any text containing it. A context never seen in training gets the uniform distribution 1/V. In NGramModel, write the counting in __init__, prob, next_distribution, log_prob (the log of the chain rule product above) and perplexity:

  perplexity = exp( −(1/N) · ln P(text) )        N = number of predicted characters

A model that chose uniformly among m characters at every step would have perplexity m; so perplexity is the model's “effective number of choices” per character. Its logarithm, the average negative log probability in nats, is the loss that BabyGPT reports during training, so the two kinds of model can be compared directly. When your code passes the tests, run

python lm_basics.py data/austen.txt          # or your corpus

to see validation perplexity and a sample for n = 1 to 5 (about 15 seconds). About 15 lines.

Q5: Temperature and Sampling (10 points)

Write softmax_with_temperature, sample_index, top_k_filter and sample_next. sample_index(probs, u) is the method of A6 Exercise 13(b): lay the probabilities end to end on [0, 1) and return the index whose piece contains u. sample_next chooses greedily when the temperature is 0 and otherwise draws exactly one random number with rng.random(). The provided generate calls your sample_next once per character, for any model; BabyGPT will use it too. The tests include one that draws 20,000 samples and compares their frequencies with the probabilities. About 20 lines.

Part 3: Predictions (5 points)

First choose your corpus for A7b from data/. If you work in a partnership, each partner chooses a different corpus: in A7b you will train one model on each, and also score each model on the other partner's text. Then fill in a7a_predictions.txt:

  • P1. Your corpus's n-gram table (from python lm_basics.py), and why perplexity falls as n grows while the largest-n samples go wrong.
  • P2. BabyGPT's validation loss after 100, 500 and 3,000 training steps, and whether it will beat your best n-gram model.
  • P3. What its generated text will look like at those steps.
  • P4. What its text will look like at temperature 0 and at temperature 2.
  • P5 (partners). Whose model will do better on its own text, and how much worse each will do on the other's.

The 5 points are awarded by the autograder, which checks only that P1–P4 are filled in, with numbers where we ask for numbers (run python autograder.py --part a to see the check before you submit). Your predictions are not graded on being right. Write them yourself, before you see BabyGPT train: in the A7b report you will compare them with what happened and explain the differences, and a wrong prediction with a good explanation is worth as much as a right one.

What to Turn In

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

tinygrad.py
lm_basics.py
a7a_predictions_firstname_lastname.txt

Before submitting, run the whole local test suite with python autograder.py. You will keep using tinygrad.py and lm_basics.py in A7b; you may improve them later, but they are graded once, in A7a.

Partnerships. If you are in a partnership, (1) fill in the partnership comment at the top of tinygrad.py and lm_basics.py, in this form:

# Partnership? YES
# Submitting partner: John Doe
# Other partner: Jane Smith

(2) when you submit to Gradescope, indicate that this is a group submission and add your partner, and (3) list both names and both corpora at the top of the predictions file. If you are working alone, write NO after Partnership?. The partnership retrospective is part of the A7b report.

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