CS231n A3: Sequences, Attention and Generation

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.

Caption the picture

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

The Garbage Caption

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.

The best a memoryless decoder can do

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.

Give the decoder a memory

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.

0.80

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.

The road

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.

  1. The RNN step: one equation forward, the tanh slope backward.
  2. Words in, loss out: embeddings, scores at every step, the mask.
  3. The LSTM cell: four gates and an additive highway.
  4. Attention: a soft lookup, and why it divides by the root of d.
  5. The Transformer decoder: position, the causal mask, residuals.
  6. Saliency and fooling: one input gradient, read or climbed.
  7. GANs: two losses that pull one number apart.
  8. SimCLR: pull two views together, push the rest apart.
  9. The showcase: watch a caption attend, word by word.
  10. The field guide: symptoms, numbers, code.
Why does a memoryless decoder write “a a a a a a”?

Chapter 1

The RNN Step and Its Backward Pass

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.

Say it aloud

h-t equals tanh of x-t times W-x, plus h-t-minus-1 times W-h, plus b.

ht
h-t the new hidden state, shape (N, H): one row per caption in the batch.
tanh
tanh squashes each number into the range −1 to 1.
xt
x-t this step's input, shape (N, D).
Wx
W-x the input weights, shape (D, H).
ht−1
h-t-minus-1 the state from the step before, shape (N, H).
Wh
W-h the recurrent weights, shape (H, H).
b
b the bias, shape (H,).
In plain words

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 numbers

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 backward pass

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.

Say it aloud

d-a equals one minus h-t squared, times d-next-h, number by number.

da
d-a the gradient at the pre-activation, shape (N, H).
1 − ht2
one minus h-t squared the slope of tanh at this step, between 0 and 1.
⊙
times, number by number multiply matching entries; no matrix product.
dnext_h
d-next-h the gradient arriving at h-t from above, shape (N, H).
In plain words

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 numbers

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.

Push a unit into the tails

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.

1.16

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.

In rnn_step_backward, why multiply dnext_h by (1 − next_h²) first?

Chapter 2

Words In, Loss Out

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.

  1. Word embedding. A matrix W of shape (V, D) holds one row per word of the vocabulary. Forward is a row lookup: out = W[x], from (N, T) indices to (N, T, D) vectors.
  2. Temporal affine. One linear layer maps every hidden state, shape (N, T, H), to vocabulary scores, shape (N, T, V). Reshape to (N·T, H), multiply, reshape back.
  3. Temporal softmax loss. Softmax turns each step's V scores into probabilities. The loss is minus the log of the probability of the true next word.

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].

The mask

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.

Say it aloud

L equals minus one over N, times the sum over n and t, of m-n-t times log p-n-t.

L
L the caption loss for the batch, in nats.
1/N
one over N divide by the number of captions, not the number of words.
Σn,t
the sum over n and t one term for each caption and each step.
mn,t
m-n-t the mask: 1 at a real word, 0 at <NULL>.
log pn,t
log p-n-t the log of the probability the model gave the true next word y-n-t.
In plain words

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 numbers

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.

Mask the padding

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.

Why does temporal_softmax_loss multiply each step's loss by a mask?

Chapter 3

The LSTM Cell Highway

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:

SliceSquashJob
i, the input gatesigmoidhow much of the candidate to write
f, the forget gatesigmoidhow much of the old cell to keep
o, the output gatesigmoidhow much of the cell to show in h
g, the candidatetanhthe 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.

Say it aloud

c-t equals f times c-t-minus-1, plus i times g, number by number.

ct
c-t the new cell, shape (N, H): the long memory.
f
f the forget gate, 0 to 1: the share of the old cell kept.
ct−1
c-t-minus-1 the cell from the step before.
i
i the input gate, 0 to 1: the share of the candidate written.
g
g the candidate, −1 to 1: what could be written.
In plain words

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 numbers

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.

Hold a memory in the cell

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.

0.90

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).

One step back along the LSTM cell, what multiplies the gradient?

Chapter 4

Scaled Dot-Product Attention

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.

Say it aloud

Attention of Q, K, V equals softmax of Q times K-transpose over root d, times V.

Attn(Q, K, V)
attention of Q, K, V the output: one blended value per query.
softmax
softmax along each row: exponentiate, then divide by the row sum, so the weights add to 1.
Q KT
Q times K-transpose every query dotted with every key: the match scores.
√d
root d the square root of the key size; it rescales the scores.
V
V the values, one row per position.
In plain words

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 numbers

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].

Why divide by root d

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].

Grow d, then scale it back

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.

Many heads

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.

Why divide the scores by √d before the softmax?

Chapter 5

The Transformer Decoder

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.

1. Positional encoding

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]

Read a position's fingerprint

Each row is a position, each column a dimension. Warm is positive, blue negative. Drag to pick a row and read its first numbers.

1

Exact sinusoidal encoding with D = 32 and 20 positions.

2. The causal mask

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.

3. The block

  1. Masked self-attention over the words, then add the input back and normalise.
  2. Cross-attention: the words are the queries, the projected image feature is the key and value. Add and normalise.
  3. Feed-forward: a small two-layer network on each position alone. Add and normalise.

“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.

Why does a Transformer add positional encodings to the word vectors?

Chapter 6

The Input Gradient: Saliency and Fooling

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.

Climb it: a fooling image

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‖.

Say it aloud

X becomes X plus eta times g over the norm of g.

X ←
X becomes replace the image with the new one.
X
X the current image, every pixel of every channel.
η
eta the step size: how far the image moves in one step.
g
g the gradient of the target score s-target with respect to X; same shape as X.
‖g‖
the norm of g its length: the square root of the sum of its squares.
In plain words

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 numbers

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.

Read the gradient, then climb it

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.

What one computation do a saliency map and a fooling image share?

Chapter 7

GANs: Two Losses, One Game

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.

Say it aloud

L-D equals minus log sigma of s-real, minus log of one minus sigma of s-fake.

LD
L-D the discriminator loss, averaged over the batch in code.
log σ(sreal)
log sigma of s-real the log of D's probability that a real image is real; sigma is the sigmoid.
log(1 − σ(sfake))
log of one minus sigma of s-fake the log of D's probability that a fake is fake.
In plain words

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 numbers

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.

Why the generator uses label 1

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.

Pull one score two ways

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.

−1.00

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.

How do the discriminator and generator losses treat the same fake images?

Chapter 8

SimCLR: Learning Without Labels

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).

Say it aloud

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.

ℓi
ell-i the loss for view i; the batch loss is the mean over all 2N views.
exp(simi,j/τ)
exp of sim-i-j over tau the positive pair's similarity, divided by tau and exponentiated.
Σk≠i
the sum over k not equal to i every other view, the positive included; view i itself is left out.
exp(simi,k/τ)
exp of sim-i-k over tau the same for view k; tau is the temperature, 0.5 here.
In plain words

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 numbers

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.

Pull pairs together

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.

0.50

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.

What goes wrong if the NT-Xent denominator keeps the term k = i?

Chapter 9

Showcase: Watch a Caption Attend

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.

Generate, then break it

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.

Why is the map lower-triangular while the caption is generated?

Chapter 10

Field Guide

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 to cause

SymptomCauseFix
Gradient check off by a factor of 1 to 3no tanh slope in rnn_step_backwardda = (1 − next_h**2) * dnext_h
Loss high, model emits <NULL>mask missing in temporal_softmax_lossmultiply each step's loss by the mask
Repeated words lose gradientdW[x] += dout in the embedding backwardnp.add.at(dW, x, dout)
LSTM no better than RNNwrong slice order or no f * prev_cslice i, f, o, g; next_c = f*prev_c + i*g
Attention one-hot from the startno 1/√d scaledivide scores by np.sqrt(head_dim)
Train loss near zero, test captions garbageno causal maskminus infinity above the diagonal
Fooling target score fallsdescent, or the true classX += lr * g / norm(g) on the target score
G loss falls, samples worsenflipped labelsD: real 1, fake 0; G: fake 1
SimCLR loss stuck above 0.69self-term in the denominatormask the diagonal of the similarity matrix

Numbers to keep

QuantityValueWhere
Memoryless floor on “a dog on a beach”1.561 nats a wordChapter 0
tanh slope at a = 20.071Chapter 1
Masked against unmasked loss2.558 against 7.163Chapter 2
Gradient after 20 steps, f = 0.9 against 0.450.12 against 1.2 × 10−7Chapter 3
Typical raw score at d = 64about 8Chapter 4
Generator slope at s-fake = −3, two forms0.047 against 0.953Chapter 7
NT-Xent floor with the self-termln 2 = 0.693Chapter 8

Checklist

  1. Grad-check every backward pass against a centred finite difference.
  2. Print shapes at each function boundary: (N, T, D), (N, T, H), (N, T, V).
  3. Confirm the mask and the causal mask on one hand-made batch.
  4. Watch the size of raw attention scores; it should be near 1.
  5. For fooling and saliency, freeze the weights and check the sign.

The core in numpy

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])

Keep going

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.

The takeaway. Each function in A3 has one line that matters: the tanh slope, the mask, f times the old cell, the root-d scale, the causal mask, the sign of the fooling step, the flipped label, the masked diagonal. Get that line right and the rest is shapes.
Your SimCLR loss sits at 0.70 and will not fall, though the pairs look aligned. What do you check first?

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”.

CS231n A3: Sequences, Attention and Generation
Previous: A2, ConvNets · Back to Gleams