Tokenwerk · The LLM textbook

Chapter 22 · V · Modern language models · 7 minutes

RMSNorm, RoPE and SwiGLU

Our transformer is at the level of 2019. Today's models have swapped out three components: small changes with a big effect. Here you get to know them; in part VII you build them in: RMSNorm, RoPE and SwiGLU.

Tuning, not a rebuild

The transformer block from chapter 17 roughly matches GPT-2 from 2019. Since then, three improvements have caught on in almost all large models:

  • RMSNorm: a simpler normalization.
  • RoPE: a clever way of telling the model the position of a token, by rotating.
  • SwiGLU: an improved version of the small network in the block.

None of them changes the basic principle. Embedding, attention, MLP and predicting the next token stay as they are. It is more tuning than rebuilding.

A warning up front: anyone who builds in all three at once and then says “each one helped” is cheating. To measure the effect of one component, you swap only that one and keep everything else the same.

RMSNorm: normalizing, but simpler

Remember LayerNorm? First subtract the average, then divide by the spread. RMSNorm simply drops the first step: no average is subtracted; it only divides by a typical size of the numbers.

An example with [3,4]: squaring gives [9,16], average 12.5, square root of that about 3.536. Each number is divided by 3.536: about [0.849; 1.131]. The numbers are now “normal sized”, but unlike with LayerNorm they are not centered around zero. Less calculation, and in practice it works just as well. RMS stands for “root mean square”, by the way.

python
class RMSNorm(nn.Module):
    def __init__(self, dim, eps=1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(dim))
        self.eps = eps

    def forward(self, x):
        xf = x.float()
        y = xf * torch.rsqrt(xf.square().mean(-1, keepdim=True) + self.eps)
        return y.to(x.dtype) * self.weight.to(x.dtype)

To be safe, we compute the statistic in Float32, even if the rest runs in smaller number formats. Original paper on RMSNorm.

RMSNorm as a formula

RMSNorm⁡(x)i=γixi1D∑jxj2+ϵ.\operatorname{RMSNorm}(x)_i=\gamma_i\frac{x_i}{\sqrt{\frac1D\sum_jx_j^2+\epsilon}}.

x is the list of numbers of one position, i a component, D the length of the list. The index j runs over all components; the sum of squares divided by D is the mean square. Epsilon is the safety number, gamma a learnable multiplier per component. For x=[3,4]x=[3,4] the RMS is (9+16)/2≈3.536\sqrt{(9+16)/2}\approx3.536.

Position as rotation

Now it gets really clever. In the classic model we added a learned position table to the embeddings. RoPE (“rotary position embedding”) does something completely different: it rotates the query and key lists depending on their position.

Picture each pair of numbers in the list as a clock hand. At position 0 nothing is rotated. At position 1 it is rotated a bit, at position 2 twice as far, and so on. The length of the hand always stays the same; only its direction reveals the position.

The clever part: attention compares query and key with the dot product. And the dot product of two rotated hands only depends on how far they are rotated relative to each other. So for the comparison, what counts is not “position 7 and position 5” but “two positions apart”. The model automatically gets a feel for distances, exactly what matters for language. “The adjective right before the noun” works the same way at the start of a sentence as on page 3.

And because different pairs of numbers are rotated at different speeds (some like a second hand, some like an hour hand), the model can distinguish both short and long distances.

python
even, odd = x[..., 0::2], x[..., 1::2]
y_even = even * cos - odd * sin
y_odd  = even * sin + odd * cos
y = torch.stack((y_even, y_odd), dim=-1).flatten(-2)

Q and K are rotated, not V. The width of a head must be even, because two numbers always form a pair. RoFormer / RoPE.

The rotation as a formula

Sine and cosine give the coordinates of a rotated arrow of length 1: cosine the horizontal, sine the vertical one. Angles are measured in radians: a full turn is 2π, a quarter turn π/2. For a pair [x1,x2][x_1,x_2] and angle θ\theta:

Rθx=[x1cos⁡θ−x2sin⁡θ, x1sin⁡θ+x2cos⁡θ].R_\theta x=[x_1\cos\theta-x_2\sin\theta,\ x_1\sin\theta+x_2\cos\theta].

For a quarter turn, cos θ = 0 and sin θ = 1: [1,0] becomes [0,1]. Q at position mm and K at position nn give a dot product that depends only on n−mn-m.

The rotation speed per pair is ωi=base−2i/d\omega_i=base^{-2i/d}: i is the number of the pair from 0, d the head width, base a fixed number greater than 1. With base = 100 and d = 4, pair 0 turns by 1 radian per position, pair 1 only by 0.1. The angle at position t is tωit\omega_i.

RoPE doesn't mean an infinitely long context

With RoPE you can also compute positions far beyond the training window. That doesn't mean the model works well there; it has never seen such distances. For longer contexts, people adjust the rotation speeds (for example with position interpolation or YaRN) and briefly train further on longer texts. Our teaching model stays at its configured context length.

SwiGLU: the MLP with a bouncer

The classic MLP in the block: widen, kink, narrow again. SwiGLU adds a second path. The input is widened twice, with two different weight tables. One path delivers values (“up”). The other goes through an activation function and acts like a bouncer (“gate”): for each component it decides how much of the first path gets through. Both are multiplied position by position, then narrowed again.

Not a hard on/off switch but a continuous dial: let a little through, let a lot through, or even flip it. This flexibility measurably helps models.

The activation in the bouncer is SiLU: the input is multiplied by a value between 0 and 1 that is close to 1 for large inputs and close to 0 for strongly negative ones. For 1, SiLU gives about 0.731; for −1 about −0.269.

python
h = F.silu(self.gate(x)) * self.up(x)
out = self.down(h)

SwiGLU has three big tables instead of two. So the parameter count stays comparable, the intermediate width is made smaller than the classic 4D, roughly 8D/3, rounded. Our project rounds to a multiple of 32. GLU variants.

SwiGLU as a formula

SwiGLU⁡(x)=Wdown(SiLU⁡(Wgatex)⊙Wupx).\operatorname{SwiGLU}(x)=W_{down}\left(\operatorname{SiLU}(W_{gate}x)\odot W_{up}x\right).

⊙\odot means position-by-position multiplication: [2,3] and [4,5] give [8,15]. SiLU is xσ(x)x\sigma(x), where sigma here means the sigmoid function σ(x)=1/(1+exp⁡(−x))\sigma(x)=1/(1+\exp(-x)), not the standard deviation.

A modern training run

In step 8 of part VII you build all three components into your own model and compare honestly. On TinyStories the best validation loss drops from 2.55 to 2.34, with even slightly fewer parameters. Small changes, measurable effect.

Comparing fairly

Write down the parameter count, processed tokens, runtime, validation loss and fixed example texts. If you swapped several parts at once, all you can say is: “The overall package is better or worse.” If you want to know what a single part brings, you need an ablation: the same experiment with exactly that one difference.

Key points

  • RMSNorm normalizes without subtracting the average: simpler, just as good.
  • RoPE rotates query and key depending on position. That way attention automatically compares distances instead of absolute positions.
  • SwiGLU gives the MLP a second path as a continuous bouncer. None of this is a rebuild, just better tuning.