Key takeaways
- In a deep network, the size of the numbers gets multiplied and added up layer after layer, and drifts further and further. Normalization rescales each token's vector to a fixed size at the entrance of every layer, which keeps gradients from exploding or vanishing and stabilizes training.
- RMSNorm divides by the root mean square (RMS), then multiplies by a learnable gain γ. Compared with LayerNorm it drops the mean subtraction and the bias β: cheaper, and about as good.
- Modern models use pre-norm: normalize right before each sublayer (attention and the feed-forward network), keep the residual "main road" clear, and add one final norm after the last layer.
- Gating: one path computes the content, another computes a valve, and multiplying them element by element decides how much of each feature gets through. SwiGLU uses Swish as the valve and has three matrices.
- Set SwiGLU's hidden width to F=38D and it has the same parameter count, and the same compute, as the classic 4D feed-forward network.
Numbers that drift, layer after layer
A large language model is usually a stack of dozens of layers. Every token's vector travels through all of them, and each layer does some computation on it.
Suppose each layer makes the vector just 10% bigger. After one layer you'd hardly notice. After 50 layers:
1.150≈117
about 117 times the original size. Flip it around: if every layer shrinks it by 10%, then after 50 layers only 0.950≈0.005 is left, half a percent, practically zero.
A tiny difference per layer, stacked dozens of times, turns into a huge one. This is an old problem with deep networks: the size of the numbers keeps drifting.
Why we need normalization
Plot the three cases on a log scale (each step up the vertical axis means multiplying by 10): multiply by 1.1 per layer and the line shoots straight up, multiply by 0.9 and it sinks straight down. Only multiplying by exactly 1 keeps it level.
Training has the same problem. In backpropagation the gradient is multiplied layer by layer on its way back from the last layer, so it can explode or vanish too.
There's a second problem. Each layer only handles its input well if that input stays within a certain range. Take the sigmoid: it responds most sensitively near zero, but once the input reaches ten or twenty the curve is almost flat, the gradient is close to zero, and the parameters basically stop learning. (Recall from episode 1 that the sigmoid's derivative σ(x)(1−σ(x)) never exceeds 0.25.)
So we put a small component at the entrance of every layer: however big the incoming vector is, first rescale it to a fixed size. That's normalization, and it stabilizes training by preventing exploding and vanishing gradients.
This episode covers two components of the Transformer:
- RMSNorm, the normalization method almost every large model uses today. It's about stability.
- SwiGLU, an upgraded feed-forward network. It's about expressive power.
Change the length, keep the direction
Start in two dimensions. Each arrow is a vector, some long, some short. Normalization stretches or shrinks every arrow so they all end up the same length, landing on the same circle.
Intuition: No arrow changes direction at all; only its length changes. The ratios between the components are kept exactly. The only thing made uniform is the overall size.
Another useful property: make an arrow three times longer, then normalize it, and it lands on exactly the same point. So however big the earlier layers push the numbers, after normalization they all come back to the same size.
So how do we measure the "size" of a vector with thousands of dimensions?
Measuring "size": the root mean square
Inside the model every token in the sentence has its own vector, and normalization handles each one separately. Follow one four-dimensional vector, x=[7,−1,5,5]:
- Square every component: [49,1,25,25]. Squaring removes the minus sign; we only care how big each number is, not its sign.
- Average: 49+1+25+25=100, divided by 4 gives 25.
- Square root: 25=5.
This 5 is the vector's root mean square (RMS). Read the name backwards and it spells out the recipe: square, mean, root. Think of it as how big the components are, on average.
With that in hand, normalizing is a single division: divide every component by 5 to get [1.4,−0.2,1,1].
Check: the squares of the new vector are 1.96, 0.04, 1, 1. They add up to 4, the average is 1, and the square root is still 1. The RMS is exactly one.
As a formula
Let the vector have D dimensions, with xi the i-th component. Add up the D squares, divide by D to average, take the square root:
RMS(x)=D1i=1∑Dxi2
Divide every component by the RMS to get the normalized vector x^:
x^i=RMS(x)xi
Why not just use the vector's length?
The length is the square root of the sum of squares: the same recipe minus the "divide by D" step. Without that step, the length grows with the number of dimensions. A vector of all ones has length 4=2 in 4 dimensions, but 4096=64 in 4096 dimensions.
Its RMS, though, is always 1. So whatever the dimension, "RMS equals 1" means each component is about 1 in size, on average.
Scaling the input changes nothing
Double x to get [14,−2,10,10]. The RMS doubles too, to 10, and dividing gives [1.4,−0.2,1,1] again, exactly the same as before. That's the "three times longer, same point" property from the arrows.
Watch out: In real code we also add a tiny positive number ϵ (epsilon), say 10−5, inside the square root, so that even an all-zero vector never causes a division by zero. You may also see ϵ written outside the root, as RMS(x)+ϵ; it's there for the same reason.
The learnable gain γ
Forcing every vector's RMS to exactly one has a price: the normalization step destroys any scale information the network has learned. Every vector ends up the same size, whether or not the network wanted that. Uniform scaling is too restrictive, because different features may need different magnitudes.
So RMSNorm has one last step. Each dimension gets its own learnable multiplier γi, called the gain. γ∈RD is just D numbers, a learned per-dimension rescaling:
- γi>1 amplifies dimension i;
- γi=1 leaves it alone;
- γi<1 suppresses it;
- γi≈0 switches that dimension off entirely.
For example, multiplying the normalized [1.4,−0.2,1,1] by γ=[1.5,1,0.5,0] gives [2.1,−0.2,0.5,0].
At the start of training every γi is set to 1; from then on gradient descent adjusts them along with all the other parameters.
Intuition: Normalization takes care of stability, and γ hands back to the network the job of deciding how big each dimension should be. Together you get the stability of normalization plus per-dimension control over magnitude.
Put it all together and you have the complete RMSNorm:
RMSNorm(x)=D1∑i=1Dxi2+ϵx⊙γ
The circle with a dot, ⊙, means element-wise multiplication: multiply the numbers in matching positions, e.g. [a1,a2]⊙[b1,b2]=[a1b1, a2b2].
LayerNorm vs RMSNorm
RMSNorm is a simplified version of an older method, LayerNorm (layer normalization), introduced in 2016. The original Transformer and GPT-2 both used it.
Run the same vector [7,−1,5,5] through both:
| Step |
LayerNorm |
RMSNorm |
| Subtract mean |
mean 4 → [3,−5,1,1] |
skipped |
| Divide by |
std. dev. 3 |
RMS 5 |
| Result |
[1,−1.67,0.33,0.33] |
[1.4,−0.2,1,1] |
| Finally |
⊙γ+β |
⊙γ |
LayerNorm's standard deviation: after subtracting the mean, the squares are 9,25,1,1; their average is 9 and its square root is 3. At the end LayerNorm multiplies by γ and also adds a second set of learnable numbers, a bias called β.
Compare the results. LayerNorm moves the mean to zero; RMSNorm ignores the mean and only fixes the scale (its output here has mean 0.8). If a vector already averages to zero, the two give identical results, apart from that β.
As formulas (μ is the mean, σ the standard deviation), RMSNorm simply leaves out the "−μ" and the "+β":
LayerNorm(x)=σ2+ϵx−μ⊙γ+β
RMSNorm(x)=D1∑ixi2+ϵx⊙γ
The 2019 paper that introduced RMSNorm argued that what really makes LayerNorm work is the scaling, and the mean subtraction can go. Drop it and you get about the same quality, less computation, and half the parameters (only γ, no β). That's why most large models today, like Llama, Qwen and Mistral, use RMSNorm.
Where it goes: pre-norm
Recall the residual stream: every token's vector travels along a main road. Each sublayer takes the vector off the road, computes a change, and adds it back on.
Modern models run an RMSNorm right before each sublayer: one in front of attention, one in front of the feed-forward network. This is pre-norm:
hx′=x+Attn(RMSNorm(x))=h+FFN(RMSNorm(h))
Notice that the main road itself is never normalized. The vectors on it are free to keep growing, but the input each sublayer receives always has an RMS of about one.
That's great for training. In backpropagation the gradient flows back along the additions on the main road, and an addition passes the gradient through unchanged, so it isn't rescaled over and over, layer after layer.
The original Transformer used post-norm instead: the normalization comes after the addition and sits right on the main road:
x′=Norm(x+F(x))
Now the gradient has to pass through a normalization at every layer. With many layers, training gets tricky and needs a very careful learning rate warmup. From GPT-2 on, most models switched to pre-norm.
One more detail: since the main road is never normalized, after the last layer the vector gets one final RMSNorm (the final norm) before it's handed to the output layer, which scores every word in the vocabulary.
Watch out: Some models also apply an optional QK norm: one more RMSNorm on the query and key vectors inside attention, to control the size of the vectors going into the dot product.
While we're here, count the parameters: each layer has two RMSNorms with D gammas each, plus one more at the very end. With D=4096, that's only 2×4096=8192 per layer, while a single D×D matrix has over 16 million. Normalization costs almost nothing in parameters.
What the feed-forward network does
Now to the home of this episode's second star: the feed-forward network (FFN).
Inside each layer, the work is split:
- Attention lets tokens talk to each other. In "The fat cat sat", the "sat" position can gather what it needs from "The", "fat" and "cat".
- The feed-forward network lets each token digest on its own. It processes every token's vector separately, with no communication between them, and every position uses the very same network with the same parameters.
The classic FFN is the multilayer perceptron from episode 1. A matrix W1 widens the D-dimensional vector to 4D, an activation function such as ReLU turns every negative number into zero, and W2 squeezes it back to D dimensions before it's added onto the residual stream:
FFN(x)=ReLU(xW1)W2
What is it actually doing? Each hidden neuron acts like a feature detector: when its pattern shows up in the input it lights up, and writes a matching vector back. Some researchers see the feed-forward layer as a kind of "key-value memory".
It has plenty of parameters: two matrices of size D×4D, for 8D2 in total. That's twice the 4D2 in attention's four D×D matrices, about two thirds of each layer's parameters.
Gating: a valve for every number
The most important recent upgrade to the FFN comes from an idea called gating. Start with an analogy.
Picture a row of water pipes, each carrying one number: the content we want to pass along. Call it u, say u=[2,−1.5,3,0.8].
Now fit each pipe with a valve. How far it opens is decided by another set of numbers, g, squashed through a sigmoid to between 0 and 1. One means fully open, zero means fully shut:
- at g=2.2, σ(g)≈0.9: almost wide open;
- at g=−4.6, σ(g) is only about 0.01: practically closed.
What flows out is the content times the valve, element by element:
h=u⊙σ(g)
So 2×0.9=1.8, 3×0.5=1.5, and the fourth pipe lets almost nothing through.
The key: u and g are both computed from the same input x, just with two different matrices. So for every token, the network decides, based on that token's content, which features to let through and which to hold back. This is the gated linear unit (GLU):
GLU(x)=(xWup)⊙σ(xWgate)
xWup is the content and σ(xWgate) is the gate.
Intuition: ReLU is a gate too: positive numbers pass, negative numbers are blocked. But there the number's own sign decides whether the gate opens, and it can only be fully open or fully shut. GLU splits "what to pass" and "how far to open" into two separately learned paths, and its valve can open partway.
Swish: a number that gates itself
The sigmoid inside the gate can be swapped for other functions. SwiGLU uses Swish, which we met in episode 1 under its other name, SiLU:
Swish(z)=z⋅σ(z)
In other words, z's own sigmoid is the valve that controls how much of z gets through.
Here's how it's built: start with the line y=z and multiply by the valve σ(z). On the positive side the valve is almost fully open, so little changes; on the negative side it's almost shut, so the curve is squashed toward zero.
The result looks a lot like ReLU, but it's smooth everywhere, with no sharp corner, and on the negative side it has a small dip, bottoming out at about −0.28, so it isn't monotonic (the notes call it "smooth, non-monotonic"). Think of it as a "soft" ReLU: instead of a hard on/off switch, it smoothly decides how much to let through based on the input's size.
For the record, its derivative appears in episode 2's table of common derivatives: Swish′(x)=σ(x)+Swish(x)(1−σ(x)).
Putting it together: SwiGLU
Combine gating and Swish and you get SwiGLU. The name is the two parts glued together: "Swi" from Swish, "GLU" from the gated linear unit.
- Multiply the input x by Wgate to get the gate scores g, and by Wup to get the content u. Both matrices widen D dimensions to a larger F: g=xWgate, u=xWup.
- Put g through Swish and multiply element-wise by u: h=Swish(g)⊙u.
- Wdown squeezes h back to D dimensions, and the result is added back onto the residual stream: y=hWdown.
On one line:
FFN(x)=(Swish(xWgate)⊙xWup)Wdown
Compared with the classic FFN, we've gone from two matrices to three.
Running the numbers
|
four components |
| g |
2.2, −2.2, 0, −4.6 |
| Swish(g) |
1.98, −0.22, 0, −0.05 |
| u |
2, −1.5, 3, 0.8 |
| h |
3.96, 0.33, 0, −0.04 |
Both G and U carry content
Look closely at the product:
Swish(g)⊙u=g⊙u⊙σ(g)
Intuition: g and u both contribute content: u is one learned representation and g is another. And σ(g) is like g's confidence in itself: the bigger g, the more confident it is and the more it lets through; when g is very negative, the whole path is shut off. In the notes' words, g is "self-gated by its own confidence".
In 2020, Noam Shazeer compared a whole family of gated variants and found that ones like SwiGLU made language models better. As for why, the paper cheerfully admits it has no explanation and credits their success to "divine benevolence". Since then PaLM, Llama, Qwen, Mistral and nearly every other big model have adopted SwiGLU; it's now the standard FFN in modern Transformers.
Why 8/3 · D?
An extra matrix means extra parameters. If the hidden width F stayed at 4D, SwiGLU would have 3×4D2=12D2 parameters, 50% more than the classic FFN's 8D2.
For a fair comparison we want equal parameter counts. What should F be?
- Classic FFN: two D×4D matrices, 8D2 in total.
- SwiGLU: three D×F matrices, 3DF in total.
Set them equal, divide both sides by 3D, and cancel one D:
3DF=8D2⟹F=3D8D2=38D≈2.67D
In pictures: three narrower matrices have exactly the same total area as two wider ones.
And it's not just the parameters: the compute matches too, because the work in a matrix multiplication is proportional to the number of parameters in the matrix (next episode works this out). In his experiments, Shazeer cut the hidden width from 3072 to 2048: exactly two thirds.
Real models also round this to a tidy number that hardware likes. Llama 7B: D=4096, 38D≈10,923, and rounding up to a multiple of 256 gives 11,008.
Putting the parts back
Here's one Transformer layer with this episode's parts in place:
- RMSNorm → attention with RoPE → add back onto the residual stream;
- RMSNorm → SwiGLU feed-forward network → add back onto the residual stream.
Stack dozens of these, run one last RMSNorm, and hand the result to the output layer.
Deep dive: the full layer in matrix form (from the notes)
The notes write the hidden states for a whole sequence as a matrix X (one row per token). The FFN half of a layer: RMSNorm with γffn gives Xˉ; two expanding projections Wup,Wgate∈RD×F; SwiGLU; a down projection Wdown∈RF×D; then the residual:
U=XˉWup,G=XˉWgate
H=Swish(G)⊙U,Swish(G)=G⊙σ(G)
F=HWdown,X(ℓ+1)=X(ℓ)+F
After the last layer comes the final RMSNorm (with γfinal), then multiplication by Wu∈RD×V to get logits over the vocabulary.
Recap
In a deep network the numbers drift layer after layer and gradients can explode or vanish, so every sublayer normalizes its input. RMSNorm does one thing: divide by the root mean square so each token vector has RMS 1 (length changes, direction doesn't), then multiply by a learnable γ that gives the network back per-dimension control. It drops LayerNorm's mean subtraction and β, saving compute without losing quality. Modern models use pre-norm: the main road is never normalized, gradients flow back through the additions untouched, and a final norm comes at the end. The FFN lets each token digest on its own and holds about two thirds of each layer's parameters; SwiGLU upgrades it with gating, "content times a Swish valve", using three matrices with hidden width 38D so parameters and compute match the classic FFN (Llama 7B uses 11,008). We counted parameters several times this episode; next time we tally the parameters, compute and memory of a whole model.