Stacking without losing what lies below
32 min read
Attention is now missing nothing: it has its three projections, its divisor, its heads and, since the previous lesson on positional encoding, rows that know where they are. What doesn't exist yet is a layer that can be put on top of another. And the paper puts six, with what leaves each one serving as the input to the next.
Repeating an operation that already works six times sounds like doing nothing, and it is exactly where Block 3 came to grief. There, what was repeated was a step of the recurrence, and composing a function with itself multiplies derivatives: a product of many similar factors goes to zero or blows up, and what came in at the bottom doesn't reach the top. A Transformer's depth is set not by the sentence but by the layers, and there are six however long the text grows. But six products are still six products. This lesson is what has to be put around a sublayer for that calculation to come out differently, and it is two things.
Go back to the diagram from the lesson that said goodbye to recurrence and look at the boxes it left unexplained. Five of the fifteen are called Add and layer norm, and from each one a line runs down the outside of its column and comes back in below the sublayer that box closes. Click one: that line is half of what the box adds.
No sublayer replaces what it receives
The residual connection is the line in the drawing written in symbols, and there is nothing more to it than this:
where is a slot (like Block 2's or the previous block's ) filled by multi-head attention in the first sublayer and by the position-wise perceptron in the second. The interesting part is in its derivative. Stack the rows of one below another, as in the lesson on why the MLP (multilayer perceptron) fails on sequences, and call that column . Differentiating a sum is differentiating each term:
That is everything. The sublayer's Jacobian depends on its parameters and can be worth anything, even zero; the other term is the identity and depends on nothing. And since the chain rule from its lesson turns a composition into a product of Jacobians, stacking blocks multiplies brackets like this one, each with its identity inside.
Two blocks, multiplied
With two blocks, and subscripts to tell each one's sublayer apart, the product opens up like this:
Four terms: one that crosses no sublayer, two that cross one and one that crosses both. With blocks there are , one for each way of choosing in each bracket between the identity and the sublayer, and among them there is always exactly one that crosses nothing.
In the lesson on the vanishing gradient there were no brackets: each factor was a bare product and the only path between step and step crossed them all. The LSTM answered by opening an additive path alongside. The residual connection is that same idea with depth in the place of time: what gets stacked here is not positions, it is layers.
That settles the previous lesson's debt. Positional encoding is added once, at the very bottom, and no box afterwards recalls where each token was: the term equal to is what carries it to the top.
One width from the bottom to the top
The sum brings a hidden constraint: and are added entry by entry, so the sublayer is forbidden from returning any shape other than . Neither of the two respects it inside, and both make the return trip: multi-head attention drops to per head and brings it back (the job the lesson on multi-head attention flagged it for), and the position-wise perceptron rises to and comes back down.
That turns into the only number to be chosen for the whole model. In Block 2's multilayer perceptron each layer had its width and could narrow at will; here, if one layer changed width, the next would have nothing to add it to. The paper's are the same in the first layer and in the sixth, and that rigidity is the price of stacking.
Each row is normalised with its own coordinates
The sum creates a problem of its own: if every sublayer adds without taking anything away, what flows grows layer by layer, and the lesson on the scaled dot-product has already measured what happens to a softmax when large numbers reach it. The scale has to go back to where it was after each sum, and that is the layer norm.
Let's fix the row at position , with its coordinates . Its mean and its standard deviation are those of these numbers and of no others:
With them the row is centred and scaled, and then two learned vectors come in, and , both of coordinates:
is a small constant ( in almost every implementation) that avoids dividing by zero if a row has all its coordinates equal. The other two seem to undo the normalisation, and in part they do: leaving every row with mean and deviation is a condition nobody asked for, and and give that freedom back as parameters. They can't undo it completely: and change from row to row, and these two vectors are the same in all of them.
Why the row and not the batch
Averaging across the row is a decision, and the alternative is the opposite one: normalising each coordinate down the column, which is batch normalisation. On sequences it fails in three places. What came out at position would depend on which other sentences had landed in the same batch; it would depend on and on what was at the other positions, including the padding positions, which say nothing; and you would have to store statistics from training to answer a single sentence later.
With the row none of the three appears, because and come from row and nothing else. One consequence is worth keeping: the Add and layer norm box doesn't mix positions, and that is why the claim of the lesson that said goodbye to recurrence (three of the fifteen boxes look beyond their own row) still stands now that we know what the other twelve do.
The sublayer that looks at no other position
The second sublayer is still missing: the one the paper calls FFN (feed-forward network) and this course calls the position-wise perceptron (the two names are the same box). Inside, it is Block 2's multilayer perceptron with two layers and a ReLU in between, applied to one row at a time:
with and , and with the subscript naming which of the two layers it is. is Block 2's column of ones, which here repeats the bias once per position instead of once per example, and the ReLU is the paper's .
The two matrices are the same for every position: row and row go through the same parameters, so the sublayer has no way of finding out which one it is transforming. That is what position-wise means, and what keeps it out of the boxes that mix.
What attention cannot compute
A box that doesn't look at the other positions needs a reason to be there, and the reason lies in what attention does not do. Let's write for the weight head gives position when computing row , and for the rows of that multiply what that head returns. Opening up the of the lesson on multi-head attention, row of is
The softmax lives entirely inside the , and what the decide is where to read from. What is done with what was read is another matter: a weighted average of rows, each passed through two matrices. With the weights already decided, row is a linear function of the rows of . So is the sum of the first section. The layer norm is non-linear, but it has no parameters with which to learn a combination: it centres the row, divides all of it by one and the same number, and and work coordinate by coordinate. None of its parameters looks at two coordinates at once.
Go back to the four phrases of the lesson on XOR and hidden layers: it's good, it's bad, not good and not bad. Here not and good occupy different rows, and bringing to the row of good the news that there is a not in front is attention's job. But once it has brought it, that row holds the two coordinates of that lesson's square, and that lesson showed that no single neuron separates its diagonals: not brings no sign of its own, it flips that of the word after it. Composing linear functions gives another linear function, so stacking more attention doesn't fix it. The two facts are together, and attention has no piece made for combining them.
The position-wise perceptron is the hidden layer that square asked for, put in every block and applied to every row. Its ReLU lets the output depend on whether a combination of coordinates is positive, which is what no linear function does, and its units are new coordinates, in which the square stops being an XOR.
Attention gathers; the position-wise perceptron computes.
The concession: I have argued with the weights already decided, and they don't come decided. The come from , so attention as a whole is non-linear in what it receives, and nothing stops a trained network from making use of that. But that non-linearity is there to choose where to read from, and using it to combine the coordinates of one row is asking one piece to do another's job.
That it is the piece that computes shows in how the parameters are split, which is not the way the drawing suggests. With and :
On the left the two matrices of the position-wise perceptron, on the right the four of the attention added together: the box that looks like plumbing carries twice the parameters of the one that gives the architecture its name. Neither number mentions .
The whole block, in two lines
With the three pieces in place, an encoder block is the same line twice:
with in the slot the first time and the second, and with the output of the first serving as the of the second. Biases and normalisation vectors included, that is parameters per block, and the paper's encoder stacks : some million, none of them dependent on the length of the text.
And now the concession. The paper normalises after adding, and that leaves the layer norm on top of the identity path: the term equal to is inside the bracket, but what leaves the box has also been through a normalisation, so the clean path of the first section isn't quite so clean. Almost every implementation today writes (normalise what goes into the sublayer and leave the sum untouched), which is what is known as pre-norm. Which one trains better is outside this course; that they are two different operations is not.
The three pieces in NumPy
The first cell is the layer norm over five positions. Look at three things: the mean and standard deviation of each row, what and give back, and what happens to row when row is touched.
rng = np.random.default_rng(7)
X = rng.normal(loc=3.0, scale=2.0, size=(5, 8)) # 5 positions, d_model = 8
def layer_norm(X, gamma, beta, eps=1e-5):
mu = X.mean(axis=1, keepdims=True) # one mean per row
s = X.std(axis=1, keepdims=True) # one deviation per row
return gamma * (X - mu) / np.sqrt(s**2 + eps) + beta
gamma, beta = np.ones(8), np.zeros(8)
Y = layer_norm(X, gamma, beta)
print("in mean per row:", np.round(X.mean(axis=1), 3))
print(" deviation :", np.round(X.std(axis=1), 3))
print("out mean per row:", np.round(Y.mean(axis=1), 3))
print(" deviation :", np.round(Y.std(axis=1), 3))
Z = layer_norm(X, np.full(8, 4.0), np.full(8, -1.0))
print("\nwith gamma = 4 and beta = -1:", np.round(Z.mean(axis=1), 3), np.round(Z.std(axis=1), 3))
# Touch ONLY row 4 and look at what happens to row 0.
X2 = X.copy()
X2[4] += 10.0
by_columns = lambda M: (M - M.mean(axis=0)) / M.std(axis=0)
print("\ntouch row 4; how far row 0 moves")
print(" normalising by rows :",
round(float(np.abs(layer_norm(X2, gamma, beta)[0] - Y[0]).max()), 12))
print(" normalising by columns:",
round(float(np.abs(by_columns(X2)[0] - by_columns(X)[0]).max()), 3))
The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.
The five rows go in with means between and and come out with mean and deviation ; with and they come out with mean and deviation , which is what those two vectors mean. The last two lines are the previous section checked: touching row moves row by by rows and by by columns.
The second measures what the sum does, and to see it alone I take the layer norm and the attention out of the block: what is left is position-wise perceptrons, one on top of another, with and without the line that goes round them. I have set the scale of the matrices low on purpose, : at the start, a sublayer is a small correction.
rng = np.random.default_rng(0)
T, d_model, d_ff, N = 8, 16, 32, 12
matrices = [(rng.normal(size=(d_model, d_ff)) * 0.15,
rng.normal(size=(d_ff, d_model)) * 0.15) for _ in range(N)]
def stack(X, n, with_sum):
for W1, W2 in matrices[:n]:
sub = np.maximum(0.0, X @ W1) @ W2 # the position-wise perceptron
X = X + sub if with_sum else sub
return X
X = rng.normal(size=(T, d_model))
h = 1e-5
Xh = X.copy()
Xh[0, 0] += h # move ONE coordinate of row 0
print("layers with the sum without the sum")
for n in (1, 2, 4, 6, 8, 12):
on = np.linalg.norm((stack(Xh, n, True) - stack(X, n, True)) / h)
off = np.linalg.norm((stack(Xh, n, False) - stack(X, n, False)) / h)
print(f"{n:6d} {on:12.4f} {off:15.3e}")
The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.
Each number is a derivative measured by a numerical probe: how far the whole output moves when a single coordinate of the input is pushed. Without the sum it falls from with one layer to with twelve, because it is a product of twelve small factors: seven orders of magnitude, and with twelve layers, not twelve thousand. With the sum it stays between and the whole way: the term that crosses no matrix is worth , and the rest only correct it.
The third puts the position-wise perceptron to the test with the XOR phrases, lengthened with filler
words between the not and the evaluative word. I have set the attention head by hand: the last
position reads all of them equally and copies, into a free coordinate, the one that marks whether a
word is not. Then I try to read the sentiment off that last row with a single neuron, fitted
with np.linalg.lstsq (the weights with the least mean squared error, computed in one go), first on
the row as it is and then on the row passed through the perceptron's first layer and its ReLU. As in the
previous cell, I take the layer norm out to see the piece alone, and I draw and
at random: only the readout is fitted.
rng = np.random.default_rng(3)
d_model, d_ff = 8, 32
# Coordinate 0: "this word is not". Coordinate 1: +1 if it is good, -1 if it is bad.
# Coordinate 2: free, the attention writes it. The rest: filler (it's, really, today...).
def phrase():
negated, good = rng.random() < 0.5, rng.random() < 0.5
filler = rng.normal(size=(rng.integers(1, 4), d_model)) * 0.5
filler[:, :3] = 0.0
not_row = np.eye(d_model)[[0]] if negated else np.zeros((0, d_model))
evaluative = np.zeros((1, d_model))
evaluative[0, 1] = 1.0 if good else -1.0
return np.vstack([not_row, filler, evaluative]), negated, good
# The head: the last position reads all of them equally and copies their coordinate 0 into 2.
W_VO = np.zeros((d_model, d_model))
W_VO[0, 2] = 1.0
def last_row(X):
alpha = np.full(len(X), 1 / len(X)) # the weights of the last row
return X[-1] + alpha @ X @ W_VO # the sum: x_t + MultiHead(X)_t
data = [phrase() for _ in range(800)]
H = np.array([last_row(X) for X, _, _ in data])
neg = np.array([n for _, n, _ in data])
pos = np.array([g for _, _, g in data])
y = (pos != neg).astype(float) # 1 if the phrase speaks well
W1, b1 = rng.normal(size=(d_model, d_ff)), rng.normal(size=d_ff)
readouts = {"the row as it is": H,
"after the ReLU": np.maximum(0.0, H @ W1 + b1)}
kinds = [(False, True), (False, False), (True, True), (True, False)]
labels = ["it's good", "it's bad", "not good", "not bad"]
widths = (11, 10, 10, 9)
print(" " * 18 + "".join(f"{s:>{w}s}" for s, w in zip(labels, widths)))
for name, F in readouts.items():
F = np.hstack([F, np.ones((len(F), 1))]) # column of ones: the bias
w = np.linalg.lstsq(F[:500], y[:500], rcond=None)[0]
ok = ((F @ w > 0.5) == (y > 0.5))[500:] # hits on 300 unseen phrases
n, g = neg[500:], pos[500:]
hits = [ok[(n == a) & (g == c)].mean() for a, c in kinds]
print(f"{name:18s}" + "".join(f"{x:{w}.2f}" for x, w in zip(hits, widths)))
The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.
Each number is the fraction of phrases of that kind the neuron classifies correctly, out of it didn't see while being fitted. On the row as it is, it gets every one of three kinds right and none of not bad: that is the most a straight line can get out of the corners of an XOR, leaving one out. After the ReLU it gets all four, with a first layer that has learned nothing. Thirty-two random units already give the readout coordinates in which the square separates; training is choosing which ones.
Test your intuition
Six questions: what the sum adds to the derivative, what it demands of the sublayer, which numbers go into normalising a row, what the position-wise perceptron is for, where its parameters are and what changes when the layer norm is moved.
Each sublayer is wrapped in . When you compose blocks and differentiate, what appears that was not in Block 3's calculation?
What does the fact that its output is added to its own input demand of a sublayer?
The block's layer norm normalises each row with its own coordinates. Tick what is true of the output at position .
Select every correct option. This is graded all-or-nothing: there is no partial credit.
In the phrase not bad, attention has already brought to the row of bad the news that there is a not in front. Why is the position-wise perceptron still needed?
With and , how many parameters do the two matrices of the position-wise perceptron have, not counting the biases?
A margin of ±0 is accepted.
Normalising the sublayer's output and adding the input afterwards, , is a different operation from the paper's.
Assemble the whole block from the lesson's two pieces.
layer_norm(X, gamma, beta, eps=1e-5) receives X of shape and returns
another of the same shape: each row centred with its own mean and divided by
, with the standard deviation of that same row, and then
multiplied coordinate by coordinate by gamma and added to beta.
block(X, attention, p) applies the two sublayers. attention is a function that receives X
and returns something of the same shape; p is a dictionary with W1 of shape
, b1 of , W2 of
, b2 of and the four vectors
gamma1, beta1, gamma2, beta2, all of .
Each sublayer is wrapped the same way: what went in is added to what came out, and the result is normalised. The second sublayer is the position-wise perceptron, .
The first run downloads the Python interpreter (~15 MB); after that it stays in the browser cache. This challenge is much easier to solve on a physical keyboard: on a phone, read it and come back later.
The block is complete and stackable, and with that one of the drawing's two columns is finished. Look at it again: the one on the right has three sublayers where the left has two, the middle one receives an arrow that crosses over from the other column, and the bottom one is called Masked self-attention: masked is a word that has not come up in these six lessons.
The three things are the same thing, and it is what separates reading a text from writing one. An encoder can look at the whole sentence because it has it in front of it; a decoder produces the output token by token, and while writing the fourth it cannot look at the fifth, which doesn't exist yet. That is the next lesson, on the encoder, the decoder and the masks, and the good news is that it doesn't touch a single line of what we have so far: blanking out the future is done by adding to the grid of scores a matrix of zeros and minus infinities before the softmax.
Further reading5 sources · 5 papers
Where this lesson comes from, and where to go next. None of it is needed to carry on with the course.
- Attention Is All You Need
Its §3.1 gives the LayerNorm(x + Sublayer(x)) wrapper and the N = 6 stack; its §3.3, the position-wise perceptron with d_ff = 2048. Each in one sentence: why the sum rescues the stacking that sank Block 3 is yours to work out.
- Layer Normalization
Normalises each example with its own units instead of with the batch column, and for your very reasons: it works in recurrent networks and keeps no statistics to answer a single sentence. It is tested on RNNs, not on a Transformer.
- Identity Mappings in Deep Residual Networks
Analyses what you derive here: with the identity connection the gradient carries a term that goes straight down between blocks and never cancels. On image networks, and it wants the identity after the sum too, which the Transformer lacks.
- On Layer Normalization in the Transformer Architecture
Answers what the lesson leaves open: normalising before the sublayer (pre-norm) rather than after keeps the gradient healthy at the start and removes the learning-rate warm-up. The paper's post-norm needs it. Measured, not proved.
- Transformer Feed-Forward Layers Are Key-Value Memories
Looks at what the position-wise perceptron's parameters store: each column of W1 fires on a pattern in the text, and its row of W2 pushes towards the words that usually follow it. It studies language models, not an encoder.