A caption decoder with no memory sees the same image at every step, so it picks the same word every time: “a a a a a a”. On “a dog on a beach” its best possible loss is 1.56 nats a word. A hidden state, or attention, lets each word depend on the words before it.
Pick a decoder and press Caption. Then we build, piece by piece, the RNN step, the caption loss, the LSTM, attention and the Transformer. After that we turn the gradient on the pixels, and end with a GAN and SimCLR.
You need a matrix multiply, the chain rule and softmax (scores in, probabilities out; see Backpropagation). We build the rest from zero.
A practice companion to Assignment 3 of Stanford CS231n: Deep Learning for Computer Vision: image captioning with RNNs, LSTMs and Transformers, network visualization, GANs and self-supervised learning. Every function is re-taught in our own words and checked in numpy. It follows A2, ConvNets.
Illustrative toy. The no-memory numbers are exact: the best fixed guess for the caption is the word counts, a 2/6 and each other token 1/6. The RNN and attention probabilities are made up to show a trained decoder; the attention spot is drawn, not learned.
Chapter 0
See why a decoder that forgets its own words repeats one word
You feed a photo of a dog on a beach to a caption model. It writes “a a a a a a”. The picture was fine: a convolutional network already turned it into a feature vector, a list of numbers that describes the image. The failure is on the language side.
The decoder picks each word from the image alone. The image is the same at every step, so the input is the same at every step. One input gives one output, so the top word wins every time.
Say the true caption is “a dog on a beach”, then an end token: six tokens. A decoder with no memory must give one probability list for all six steps. The best list is the word counts: “a” gets 2/6, every other token 1/6.
The cross-entropy loss of a step is minus the log of the probability given to the true word. So “a” costs −ln(1/3) = 1.099 and each other token costs −ln(1/6) = 1.792. The mean over six tokens is (2 × 1.099 + 4 × 1.792) / 6 = 1.561 nats a word. No training gets below that floor.
Each bar is the loss on one true token. Grey is the memoryless floor. Drag how well the memory predicts the next word and watch the mean fall.
The grey floor is exact for this caption. The teal bars assume the decoder gives the same probability to every true next word, an illustrative simplification.
A decoder with memory carries a running summary of the words so far. That summary is the hidden state, and a network that updates it once per step is a recurrent neural network (RNN). With it, the step after “dog” and the step after “beach” see different inputs.
Symptom: the decoder repeats one or two words, and the training loss stops at a floor.
Measure: feed the same image with different word prefixes. If the output does not change, the state carries nothing.
Fix: pass the hidden state from step to step, and feed the previous word in as input.
Assignment 3 has two halves. The first builds caption decoders. The second turns a trained network around: its gradient shows what it sees, and two new losses teach it to generate and to represent.
Chapter 1
Write one step forward, then send the gradient back through the tanh
An RNN runs one small rule at every step. Name the parts first. The input at step t is a vector of D numbers, called x-t. The old hidden state is a vector of H numbers, called h-t-minus-1. Two weight matrices mix them: W-x (D by H) for the input and W-h (H by H) for the old state. A bias b of length H shifts each unit.
h-t equals tanh of x-t times W-x, plus h-t-minus-1 times W-h, plus b.
Multiply the input x-t by W-x. Multiply the old state h-t-minus-1 by W-h. Add both and b, then squash each number with tanh. That is h-t.
With made-up numbers: x-t = [1, 0.5], h-t-minus-1 = [0.2, −0.4], W-x = [[0.5, −0.3], [0.8, 0.2]], W-h = [[0.1, 0.4], [−0.6, 0.3]], b = [0, 0.1]. Then x-t W-x = [0.9, −0.2] and h-t-minus-1 W-h = [0.26, −0.04]. The sum is [1.16, −0.14], so h-t = [0.821, −0.139].
The same W-x, W-h and b run at every step. So a caption of 5 words and one of 50 use the same weights. In the backward pass, each shared weight adds up its gradient from every step.
The gradient arrives from above as dnext-h: how much the loss moves when each number of h-t moves. First it must pass back through the tanh. The slope of tanh at a pre-activation is one minus tanh squared, and tanh of the pre-activation is h-t itself. Call the gradient at the pre-activation da.
d-a equals one minus h-t squared, times d-next-h, number by number.
Square each number of h-t and take it from 1. Multiply by the matching number of dnext-h. The rest is matrix products: dx = da W-x transposed, dprev-h = da W-h transposed, dW-x = x-t transposed da, dW-h = h-t-minus-1 transposed da, db = da summed over the batch.
With the step above and dnext-h = [1, 1]: the slopes are 1 − 0.821² = 0.326 and 1 − 0.139² = 0.981, so da = [0.326, 0.981]. Then dx = da W-x transposed = [−0.131, 0.457]. A finite-difference check gives the same dx to 10 decimals.
Teal is tanh. Warm is its slope, the share of the gradient that passes. Drag the pre-activation and watch the slope fall in the tails.
Exact tanh and slope. The starting value 1.16 is the first unit of the worked example.
Symptom: the gradient check fails by a factor of 1 to 3, and the RNN learns slowly or not at all.
Measure: compare analytic dx to a centred finite difference. Without the slope, this example gives dx = [0.2, 1.0] against the true [−0.131, 0.457].
Fix: multiply by (1 − next_h**2) before any matrix product.
Chapter 2
Turn word indices into vectors, score every step, and mask the padding out of the loss
The RNN works on vectors, but a caption is a list of word indices. Three small functions connect them. Each is one function you write in the assignment.
The embedding backward has a trap. A word can appear twice in a batch, so two gradients go to the same row. In numpy, dW[x] += dout keeps only the last one. np.add.at(dW, x, dout) adds both. With word 0 at two places and gradients [1, 2] and [5, 6], add.at gives row 0 = [6, 8]; the plain form gives [5, 6].
Captions have different lengths. Short ones are padded to length T with a <NULL> token. Call the true next word of caption n at step t y-n-t, and the model's probability for it p-n-t. A mask m-n-t is 1 at a real word and 0 at padding. N is the number of captions.
L equals minus one over N, times the sum over n and t, of m-n-t times log p-n-t.
At each step, take minus the log of p-n-t. Multiply by the mask m-n-t, so padded steps give 0. Add all steps of all captions and divide by N.
With made-up numbers: caption 1 has 3 real words with p = 0.5, 0.25, 0.4; caption 2 has 2 with p = 0.6, 0.2. Their losses are 0.693, 1.386, 0.916 and 0.511, 1.609. The sum is 5.116, and L = 5.116 / 2 = 2.558. Without the mask the two padded steps add 2.303 and 2.996 + 3.912 more, and L = 7.163.
Each bar is one step's loss, two captions of four steps. Outlined bars are <NULL> padding. Turn the mask on and off.
The probabilities are the made-up ones of the worked example. The padded steps have low probability because <NULL> targets are noise.
Symptom: the loss is large and falls slowly, and the model learns to emit <NULL>.
Measure: compute the loss with and without the mask on one batch. Equal values mean the mask is not applied.
Fix: multiply each step's loss by the mask before the sum, and the gradient dx by the mask too.
Chapter 3
Add a second state that changes by addition, so the gradient can travel far
In a vanilla RNN, one step back multiplies the gradient by a tanh slope and by W-h. If that factor is about 0.45, twenty steps leave 0.45 to the 20th, about 1.2 × 10−7. The first word of a long caption gets no credit. This is the vanishing gradient. See RNN & GRU for the full story.
The LSTM (long short-term memory) adds a second state, the cell c, and three gates. One affine layer, x-t W-x + h-t-minus-1 W-h + b, gives a block of shape (N, 4H). The assignment slices it in this order:
| Slice | Squash | Job |
|---|---|---|
| i, the input gate | sigmoid | how much of the candidate to write |
| f, the forget gate | sigmoid | how much of the old cell to keep |
| o, the output gate | sigmoid | how much of the cell to show in h |
| g, the candidate | tanh | the new content offered to the cell |
A sigmoid maps any number into 0 to 1, so a gate is a soft valve. Call the old cell c-t-minus-1 and the new cell c-t.
c-t equals f times c-t-minus-1, plus i times g, number by number.
Keep the share f of the old cell c-t-minus-1. Add the share i of the candidate g. The result is c-t. Then h-t = o times tanh of c-t: the output gate o decides how much of the cell to show.
With made-up pre-activations 0.5, 2.0, 1.0, −0.4 and c-t-minus-1 = 0.6: i = 0.622, f = 0.881, o = 0.731, g = −0.380. So c-t = 0.881 × 0.6 + 0.622 × (−0.380) = 0.528 − 0.237 = 0.292, and h-t = 0.731 × tanh(0.292) = 0.208.
Look at the path from c-t-minus-1 to c-t. It has no squash and no weight matrix: one step back multiplies the gradient by f only. With f = 0.9, twenty steps keep 0.9 to the 20th = 0.12 of the gradient, against 1.2 × 10−7 for the vanilla RNN.
Step 0 writes 1.0 into the cell; after that nothing is written. Teal bars are the cell. The grey line is a vanilla RNN at 0.45 a step. Drag f.
Illustrative: one cell unit, f held fixed, i times g = 1 at step 0 and 0 after. The bars also show how much gradient flows back along the cell. The 0.45 vanilla factor is an assumed typical value.
Symptom: the LSTM does no better than the vanilla RNN on long captions.
Measure: check the slice order and the cell line. A slice in the wrong order puts a tanh where a sigmoid belongs.
Fix: slice i, f, o, g in that order; write next_c = f * prev_c + i * g and next_h = o * np.tanh(next_c).
Chapter 4
Let each position look up every other position, and keep the scores at a sane size
An RNN or LSTM squeezes all past words into one state vector. To pick word 20, the decoder gets a lossy summary of words 1 to 19. Attention removes that squeeze: each position looks at every position and takes a weighted blend.
Each position makes three vectors. A query q says what it looks for. A key k says what it offers. A value v is the content it hands over. Stack them as matrices Q, K and V, one row per position. Each key and query has d numbers.
Attention of Q, K, V equals softmax of Q times K-transpose over root d, times V.
Dot each query with every key. Divide the scores by root d. Softmax each row into weights. Blend the rows of V with those weights.
With made-up numbers: q = [1, 0, 1, 0], keys [1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0], so d = 4. The scores are [2, 0, 1]; over root 4 they are [1, 0, 0.5]. Softmax gives weights [0.507, 0.186, 0.307]. With values [1, 0], [0, 1], [0.5, 0.5], the output is [0.660, 0.340].
If the entries of q and k are random with variance 1, their dot product has variance d. At d = 64 a typical score is about 8 in size. Softmax of [8, 0, −8] is [0.9997, 0.0003, 0.0000], a near one-hot. Its gradient is close to zero, so training stalls. Divided by 8 the scores are [1, 0, −1], and softmax gives [0.665, 0.245, 0.090].
Rows are queries, columns are keys; bright means a large weight. Pick a key size, then turn the scale off and on.
Illustrative: queries and keys are random normal vectors from a fixed seed, recomputed for each d. The weights are exact softmax of those scores.
Multi-head attention splits the E numbers of each position into h heads of E/h numbers. Each head runs the equation on its slice, and the results are joined. With batch N, S queries and T keys:
(N, S, E) → (N, S, h, E/h) → (N, h, S, E/h) → scores (N, h, S, T)the scale is 1/√(E/h): the head size, not E
Symptom: attention maps are near one-hot from the first step and the loss barely moves.
Measure: print the size of the raw scores. Values near √d mean the scale is missing.
Fix: divide the scores by np.sqrt(head_dim) before softmax.
Chapter 5
Give attention a sense of order, stop it seeing the future, and stack it safely
Shuffle the words of a caption and run attention. Each output moves with its word but does not change. Attention has no sense of order. A caption decoder needs three more parts.
Before the first layer, add a fixed pattern to each word vector. For position pos and dimension pair i, of D dimensions in all, the even dimension gets sin(pos / 100002i/D) and the odd one gets cos of the same angle. Low dimensions turn fast; high ones turn slowly. Every position gets a different pattern, and nothing is learned.
D = 4, pos = 1: [sin 1, cos 1, sin 0.01, cos 0.01] = [0.841, 0.540, 0.010, 1.000]pos = 0 is [0, 1, 0, 1]; pos = 2 is [0.909, −0.416, 0.020, 1.000]
Each row is a position, each column a dimension. Warm is positive, blue negative. Drag to pick a row and read its first numbers.
Exact sinusoidal encoding with D = 32 and 20 positions.
In training, the decoder sees the whole true caption at once. Without a rule, word 3 could attend to word 4, the answer it must predict. The causal mask adds minus infinity to every score above the diagonal before the softmax. Exp of minus infinity is 0, so position t only sees positions 0 to t.
“Add the input back” is a residual connection: out = x + sublayer(x). Its gradient path is a plain addition, the same trick as the LSTM cell. Layer norm rescales each position's vector to mean 0 and variance 1, so a deep stack keeps a steady scale.
Symptom: the training loss falls near zero, but greedy captions at test time are garbage.
Measure: change the last word of a training caption. If earlier predictions change, they see the future.
Fix: fill the upper triangle of the scores with minus infinity before softmax.
Chapter 6
Freeze the weights, take the gradient of a class score with respect to the pixels, then read it or climb it
A trained classifier says “dog”. Which pixels made it say so? Normally you take the gradient of the loss with respect to the weights. Here you freeze the weights and take the gradient of one class score with respect to the input image X.
A pixel whose small change moves the score a lot matters. The saliency map is the size of that gradient: the absolute value of d-score-y by d-X, where y is the correct class. For a colour image, take the largest of the three channels at each pixel. It costs one forward and one backward pass.
Now pick a wrong class, the target. Call its score s-target, the image X, and a step size η (eta). Call the gradient of s-target with respect to X g, and its length ‖g‖.
X becomes X plus eta times g over the norm of g.
Backprop the target score s-target to the pixels to get g. Divide g by its length, so each step has the same size eta. Add it to X. Repeat until the model predicts the target.
With a made-up linear model on two pixels X = [0.5, 0.8]: dog = 1.0 x1 + 0.5 x2 = 0.9 and cat = −0.5 x1 + 1.0 x2 = 0.55. For target cat, g = [−0.5, 1.0] and ‖g‖ = 1.118. With eta = 0.3, one step raises cat to 0.885; two steps raise it to 1.221, above dog's 0.9. Fooled.
Left: the image. Middle: the saliency map for the class you pick. Right: the three scores. Press Step to climb toward cat; turn on the wrong sign to see the bug.
Illustrative linear classifier with made-up weights, so the gradient of a score is that class's weight map. A real CNN has a gradient that depends on the image. Step size 0.4.
In a real 224 by 224 colour image there are 150,528 numbers. A step of length 0.3 spread over all of them moves each pixel by about 0.3 / √150,528 = 0.0008 on average. The image looks the same to you, and the model is sure it is a cat. These are adversarial examples.
Symptom: the fooling loop runs forever and the target score falls.
Measure: print s-target after each step. It should rise.
Fix: add the gradient (ascent), differentiate the target class, not the true class, and keep the weights frozen.
Chapter 7
Train a forger and a detector on the same fake images, with opposite labels
A generative adversarial network (GAN) has two networks. The generator G turns random noise z into a fake image. The discriminator D looks at an image and outputs a score s, a logit. Sigmoid of s is its probability that the image is real.
D is a binary classifier: real images get label 1, fakes get label 0. Call the score of a real image s-real and of a fake s-fake. Binary cross-entropy with label 1 is minus log sigmoid of s; with label 0 it is minus log of one minus sigmoid of s.
L-D equals minus log sigma of s-real, minus log of one minus sigma of s-fake.
Score a real batch and a fake batch. Push s-real up toward label 1 and s-fake down toward label 0. The generator's loss uses the same fakes with the label flipped: L-G = −log σ(s-fake).
With made-up scores s-real = 2.0 and s-fake = −1.0: sigma gives 0.881 and 0.269. L-D = −log 0.881 − log 0.731 = 0.127 + 0.313 = 0.440. L-G = −log 0.269 = 1.313. D is winning, and G has a large loss to push down.
G could minimise log(1 − σ(s-fake)) instead, the exact opposite of D. Early in training D spots fakes easily, so s-fake is low. At s-fake = −3, that loss has slope −0.047: almost no signal. The label-1 form, −log σ(s-fake), has slope −0.953 there. Same goal, twenty times the gradient.
The x axis is s-fake. Yellow is D's loss on the fakes, pink is G's loss. Drag s-fake; switch to the least-squares form.
Exact loss formulas for one fake image. Least squares: D's fake term is ½ s², G's loss is ½(s − 1)².
The least-squares GAN (LS-GAN) swaps cross-entropy for squared error: L-D = ½(s-real − 1)² + ½ s-fake² and L-G = ½(s-fake − 1)², each averaged over the batch. With the scores above, L-D = 0.5 + 0.5 = 1.0 and L-G = 2.0. Its slope never flattens on the fake side.
Symptom: the generator loss falls while the samples get worse.
Measure: check the labels in both losses on one fixed batch.
Fix: D: real to 1, fake to 0. G: fake to 1. Use a stable BCE on logits, not log of a sigmoid.
Chapter 8
Make two views of each image agree, and every other image disagree
You have a million photos and no labels. SimCLR makes its own task. Take an image and make two random augmentations: crop, flip, colour jitter. Embed both. Two views of the same image are a positive pair; every other view in the batch is a negative.
Each embedding is scaled to length 1, so the dot product of two is their cosine similarity, from −1 to 1. With a batch of N images there are 2N views. Call the similarity of views i and k sim-i-k, the positive partner of view i j, and a temperature τ (tau).
ell-i equals minus log of: exp of sim-i-j over tau, divided by the sum over k not equal to i of exp of sim-i-k over tau.
It is a softmax classifier where the right answer is the partner j and the wrong answers are the other views. Divide each sim-i-k by tau, exponentiate, and take the partner's share. Minus its log is ell-i.
With made-up 2-D embeddings at 0°, 30°, 120°, 150° (pairs 0–1 and 2–3) and tau = 0.5: for view 0 the terms are exp(1.732) = 5.652, exp(−1.0) = 0.368, exp(−1.732) = 0.177. So ell-0 = −log(5.652 / 6.197) = 0.092. The mean over the four views is 0.154.
Two pairs of views on the unit circle, joined by green lines. Drag the alignment to close each pair. Turn on the self-term bug and watch the floor.
Illustrative 2-D embeddings, tau = 0.5. Pair centres are fixed at 15° and 135°; alignment 0.5 is the worked example. The loss is the exact NT-Xent mean over four views.
This loss is called NT-Xent, normalised temperature-scaled cross-entropy. A small tau sharpens the softmax, so the closest negatives dominate. A large tau spreads the push over all negatives.
Symptom: the loss never drops below about 0.69, even when pairs align.
Measure: check whether the denominator includes k = i. That term is exp(1/tau), the largest possible, so the partner's share can never pass one half: the loss stays above ln 2 = 0.693.
Fix: set sim[i, i] to minus infinity, or mask the diagonal, before the sum.
Chapter 9
Generate a caption one word at a time and see each new word look back
Here the parts meet. A decoder writes “a dog runs on the beach”. Each new row of the map is one new word, attending over the words before it. The triangle is the causal mask from Chapter 5. The softness is the root-d scale from Chapter 4.
Press Play to write the caption. Click a row to read it. Turn off the scale, then the mask, and compare.
Illustrative: queries and keys are fixed random vectors with d = 32 plus a small made-up bias toward related words (runs to dog, beach to the). The weights are exact softmax of those scores.
Turn the scale off: the rows snap to one bright cell each, and training would stall. Turn the mask off: the upper triangle fills, and each word can read the word it must predict.
Chapter 10
Keep the symptoms, the numbers and the code for every function in one place
Assignment 3 is four ideas. Sequences need memory: a state, a cell highway, or attention. Attention is a scaled soft lookup. The input gradient is a lens: read its size, or climb it. And two losses teach a network to generate and to represent without labels.
| Symptom | Cause | Fix |
|---|---|---|
| Gradient check off by a factor of 1 to 3 | no tanh slope in rnn_step_backward | da = (1 − next_h**2) * dnext_h |
| Loss high, model emits <NULL> | mask missing in temporal_softmax_loss | multiply each step's loss by the mask |
| Repeated words lose gradient | dW[x] += dout in the embedding backward | np.add.at(dW, x, dout) |
| LSTM no better than RNN | wrong slice order or no f * prev_c | slice i, f, o, g; next_c = f*prev_c + i*g |
| Attention one-hot from the start | no 1/√d scale | divide scores by np.sqrt(head_dim) |
| Train loss near zero, test captions garbage | no causal mask | minus infinity above the diagonal |
| Fooling target score falls | descent, or the true class | X += lr * g / norm(g) on the target score |
| G loss falls, samples worsen | flipped labels | D: real 1, fake 0; G: fake 1 |
| SimCLR loss stuck above 0.69 | self-term in the denominator | mask the diagonal of the similarity matrix |
| Quantity | Value | Where |
|---|---|---|
| Memoryless floor on “a dog on a beach” | 1.561 nats a word | Chapter 0 |
| tanh slope at a = 2 | 0.071 | Chapter 1 |
| Masked against unmasked loss | 2.558 against 7.163 | Chapter 2 |
| Gradient after 20 steps, f = 0.9 against 0.45 | 0.12 against 1.2 × 10−7 | Chapter 3 |
| Typical raw score at d = 64 | about 8 | Chapter 4 |
| Generator slope at s-fake = −3, two forms | 0.047 against 0.953 | Chapter 7 |
| NT-Xent floor with the self-term | ln 2 = 0.693 | Chapter 8 |
pythonimport numpy as np def rnn_step(x, h, Wx, Wh, b): # (N,D),(N,H) -> (N,H) nh = np.tanh(x @ Wx + h @ Wh + b) return nh, (x, h, Wx, Wh, nh) def rnn_step_backward(dnh, cache): x, h, Wx, Wh, nh = cache da = (1 - nh**2) * dnh # the tanh slope return da @ Wx.T, da @ Wh.T, x.T @ da, h.T @ da, da.sum(0) def temporal_softmax_loss(s, y, mask): # s (N,T,V), y (N,T), mask (N,T) N = s.shape[0] p = np.exp(s - s.max(-1, keepdims=True)); p /= p.sum(-1, keepdims=True) py = np.take_along_axis(p, y[..., None], -1)[..., 0] return -np.sum(mask * np.log(py)) / N def lstm_step(x, h, c, Wx, Wh, b): H = h.shape[1]; a = x @ Wx + h @ Wh + b # (N, 4H) sg = lambda z: 1 / (1 + np.exp(-z)) i, f, o, g = sg(a[:, :H]), sg(a[:, H:2*H]), sg(a[:, 2*H:3*H]), np.tanh(a[:, 3*H:]) c = f * c + i * g return o * np.tanh(c), c def attention(Q, K, V, causal=False): # (S,d),(T,d),(T,dv) s = Q @ K.T / np.sqrt(Q.shape[-1]) if causal: s = np.where(np.triu(np.ones_like(s), 1) > 0, -np.inf, s) w = np.exp(s - s.max(-1, keepdims=True)); w /= w.sum(-1, keepdims=True) return w @ V def nt_xent(z, tau=0.5): # z (2N,d), rows 2k and 2k+1 are a pair z = z / np.linalg.norm(z, axis=1, keepdims=True) s = z @ z.T / tau; np.fill_diagonal(s, -np.inf) # drop the self-term pos = np.arange(len(z)) ^ 1 lse = np.log(np.exp(s).sum(1)) return np.mean(lse - s[np.arange(len(z)), pos])
Credit: this is a practice companion to Assignment 3 of Stanford CS231n: Deep Learning for Computer Vision. The function names follow the assignment's starter code. The explanations, toys and numbers are our own, checked in numpy. The ⚒ Build studio lets you write all nine functions on live instruments.
Now press Present or Teach and explain from memory: the tanh slope, the mask, the cell highway, the root-d scale, the fooling step, the flipped label and the masked diagonal. Then go back to the picture and say why the memoryless decoder repeats “a”.