Anatomy of a Modern LLM
RMSNorm, SwiGLU, rotary embeddings and grouped-query attention: what changed since 2017.
Put the 2017 transformer next to an open language model of the mid-2020s and the outline is the same: embeddings, a stack of attention and feed-forward blocks, an output layer. Almost every component inside has been swapped, though: the normalization, its position, the feed-forward nonlinearity, the way position enters, the number of key–value heads, even the biases. This lesson takes the modern decoder apart, weighs the evidence for each change, and counts every parameter of a published 7-billion-parameter configuration.
What you’ll learn
- List the changes from the 2017 transformer to a typical open decoder of the mid-2020s (pre-RMSNorm, SwiGLU, RoPE, no biases, grouped-query attention, larger vocabularies and contexts, QK-norm) and the reason given for each.
- Implement a LLaMA-style block, and explain what RMSNorm and grouped-query attention save.
- Count the parameters and training FLOPs of a LLaMA-2-7B-style configuration and check them against the published size.
- Weigh the evidence on which modifications transfer, and on how much the shape (depth versus width) matters at a fixed parameter count.
From 2017 to the mid-2020s
| Component | Transformer (2017) | Typical open decoder, mid-2020s | Stated reason |
|---|---|---|---|
| Layout | encoder–decoder | decoder-only | one stack for every task, prompts instead of task-specific inputs |
| Normalization | LayerNorm after each residual addition (post-LN) | RMSNorm on the input of each sublayer (pre-norm) | training stability; cheaper normalization |
| Feed-forward | ReLU, | SwiGLU, rounded for hardware | better quality at equal parameters |
| Position | sinusoids added to the embeddings | rotary embeddings in every layer, often with a larger base for long contexts | relative positions; context extension |
| Attention heads | every head has its own keys and values | grouped-query attention: query heads share a few key–value heads | smaller KV cache, faster decoding |
| Biases | in every linear layer and normalization | none | training stability at scale |
| Vocabulary | about 37,000 shared BPE tokens (English–German) | 32,000 (LLaMA) to 128,000 (Llama 3) or more | fewer tokens per text, better multilingual coverage |
| Context | sentences | 2,048 (LLaMA), 4,096 (Llama 2), 8K extended to 128K (Llama 3) | longer documents and conversations |
| Extra stabilizers | none | sometimes QK-norm, a z-loss on the output logits, norms on sublayer outputs | fewer loss spikes |
LLaMA (Touvron et al., 2023) documented the now-common core and credited its sources: pre-normalization of each sublayer's input with RMSNorm "to improve the training stability", from GPT-3; SwiGLU with hidden width instead of , from PaLM; and rotary embeddings in every layer instead of absolute positions, from GPT-Neo. PaLM (Chowdhery et al., 2023) had dropped all biases from its dense layers and normalizations, reporting that this increased training stability for large models, and used multi-query attention and a 256,000-token vocabulary. Llama 2 added grouped-query attention to its largest models and doubled the context to 4,096 tokens; Llama 3 used grouped-query attention with 8 key–value heads at every size, a 128,000-token vocabulary, a RoPE base of 500,000 instead of 10,000, and an attention mask that keeps different documents in one training sequence from attending to each other.
The pieces, one by one
RMSNorm (Zhang & Sennrich, 2019) drops LayerNorm's centering and bias and rescales by the root mean square alone,
keeping LayerNorm's invariance to rescaling the input while skipping the mean; the authors reported running-time reductions of 7% to 64% across models, with comparable quality. Grouped-query attention (Ainslie et al., 2023) lets groups of query heads share one key–value head. With key–value heads instead of , the KV cache shrinks by ; with Llama 3's 8 key–value heads and 32 query heads at , a 16-bit cache needs 128 KiB per token across 32 layers instead of 512 KiB. Ainslie et al. also turned existing multi-head checkpoints into grouped-query ones by continued pretraining ("uptraining") on about 5% of the original compute. Serving Language Models works through the memory arithmetic.
QK-norm normalizes queries and keys before their dot product, so attention logits cannot grow without bound; Dehghani et al. (2023) used it to train a 22-billion-parameter vision transformer stably. OLMo 2 (Team OLMo, 2024) combines it with RMSNorm applied to the outputs of the attention and MLP sublayers inside the residual branch, , a z-loss regularizer, no weight decay on embeddings, and a RoPE base raised to 500,000, all motivated by training stability.
import torch, torch.nn as nn, torch.nn.functional as F
def rope(x, base=10000.0): # x: (B, H, T, dh); rotate pairs (0,1), (2,3), ...
T, dh = x.shape[-2:]
ang = torch.arange(T, device=x.device)[:, None] * base ** (-torch.arange(0, dh, 2, device=x.device) / dh)
x1, x2, c, s = x[..., 0::2], x[..., 1::2], ang.cos(), ang.sin()
return torch.stack((x1 * c - x2 * s, x1 * s + x2 * c), dim=-1).flatten(-2)
class Block(nn.Module): # pre-RMSNorm, RoPE, GQA, SwiGLU, no biases
def __init__(self, d, h, h_kv, d_ff):
super().__init__()
self.h, self.h_kv, self.dh = h, h_kv, d // h
self.n1, self.n2 = nn.RMSNorm(d), nn.RMSNorm(d)
self.wq, self.wo = nn.Linear(d, d, bias=False), nn.Linear(d, d, bias=False)
self.wkv = nn.Linear(d, 2 * h_kv * self.dh, bias=False)
self.w1, self.w3 = nn.Linear(d, d_ff, bias=False), nn.Linear(d, d_ff, bias=False)
self.w2 = nn.Linear(d_ff, d, bias=False)
def forward(self, x): # x: (B, T, d)
B, T, d = x.shape
a = self.n1(x)
q = self.wq(a).view(B, T, self.h, self.dh).transpose(1, 2)
k, v = self.wkv(a).view(B, T, 2, self.h_kv, self.dh).permute(2, 0, 3, 1, 4)
z = F.scaled_dot_product_attention(rope(q), rope(k), v, is_causal=True, enable_gqa=True)
x = x + self.wo(z.transpose(1, 2).reshape(B, T, d))
b = self.n2(x)
return x + self.w2(F.silu(self.w1(b)) * self.w3(b))enable_gqa=True lets the query heads share the key–value heads in groups of . Implementations differ in how they pair coordinates for RoPE (adjacent pairs here, first half with second half in others); the two are equivalent up to a fixed permutation of the head dimensions.
Which of these changes is aimed mainly at the cost of decoding, rather than at training stability or quality?
- RMSNorm before each sublayer
- Removing biases
- QK-norm
- Grouped-query attention
Show the answer
D. Grouped-query attention
Decoding reads the whole KV cache for every new token, so its speed is bound by memory traffic. Sharing key–value heads shrinks the cache by with little loss in quality. The other three were introduced for stable training.
Counting a 7-billion-parameter model
Take , layers, 32 heads of size 128 with full key–value heads, a SwiGLU width (that is rounded up to a multiple of 256), a 32,000-token vocabulary, untied input and output embeddings, no biases. Attention and SwiGLU per layer:
Two RMSNorm gain vectors add , so a layer holds parameters and the stack billion. Add the embedding and output matrices and a final norm:
That is the "7B" model's published size. The FFNs hold 64% of it, attention 32%, embeddings under 4%. Training on 2 trillion tokens costs about
plus attention's share at the full context (The Transformer Block). Llama 3 8B keeps and but widens the FFN to 14,336, uses 8 key–value heads and a 128,000-token vocabulary; its embeddings alone grow to about a billion parameters, for about 8.0 billion in total.
A decoder has , , full multi-head attention, SwiGLU with , a 32,000-token vocabulary, untied embeddings and no biases (the LLaMA 13B shape). How many parameters does it have, in billions, ignoring the norms?
Show the answer
13.02 B
Per layer ; times 40 is B. The two embedding matrices add B, for about B: the published "13B".
Which changes matter: the evidence
Proposed improvements to the transformer number in the hundreds. Narang et al. (2021) reimplemented dozens of them in one codebase and evaluated them on the same pretraining, fine-tuning and translation tasks. "Surprisingly," they wrote, "we find that most modifications do not meaningfully improve performance." The ones that helped were mostly relatively minor changes or had been developed in the same codebase they used, among them the gated (GLU-family) feed-forward layers and RMSNorm, and the authors conjectured that reported gains often depend on implementation details.
Shape. How should a fixed parameter budget be split between depth and width? Kaplan et al. (2020) found that "network width or depth have minimal effects within a wide range": at fixed non-embedding parameter count, the aspect ratio could vary by a factor of 40 while only slightly affecting the loss, and a 6-layer model of width 4,288 came within 3% of the loss of a 48-layer model of width 1,600. Published configurations cluster around – (LLaMA 7B: ; LLaMA 65B: ; Llama 3 405B: ), with heads of size 128. Within the flat region, engineering decides: depth adds sequential latency and pipeline stages, width suits tensor parallelism, and head sizes of 64 to 128 suit attention kernels.
What did Narang et al. (2021) conclude after reimplementing many proposed transformer modifications in one codebase?
- Nearly all modifications improved performance across tasks
- Most modifications did not meaningfully improve performance; the few that did were mostly minor or came from the same codebase
- Only changes to the attention mechanism mattered
- Modifications helped only at the largest scales they tested
Show the answer
B. Most modifications did not meaningfully improve performance; the few that did were mostly minor or came from the same codebase
Their conjecture: performance improvements may depend strongly on implementation details. GLU-style feed-forward layers and RMSNorm were among the changes that did hold up, and they are part of today's standard recipe.
Key takeaways
- A mid-2020s open decoder keeps the 2017 outline but swaps the parts: pre-norm RMSNorm, SwiGLU feed-forward layers, rotary positions, no biases, grouped-query attention, larger vocabularies and contexts, and sometimes QK-norm and a z-loss.
- RMSNorm drops centering and bias; grouped-query attention shrinks the KV cache by (128 instead of 512 KiB per token for Llama 3 8B); both trade little quality for cost or stability.
- A LLaMA-2-7B-style configuration has parameters, 64% in the FFNs, and costs about FLOPs to train on 2 trillion tokens.
- Most proposed modifications did not transfer across implementations (Narang et al., 2021); GLU-style FFNs and RMSNorm did. At fixed size the loss depends only weakly on depth versus width, so shape is chosen largely for engineering reasons.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How does RMSNorm differ from LayerNorm?
- It normalizes over the batch instead of over features
- It skips subtracting the mean and has no bias, rescaling by the root mean square alone
- It is applied after the residual addition
- It has no learned parameters
Show the answer
B. It skips subtracting the mean and has no bias, rescaling by the root mean square alone
. It keeps the learned gain and LayerNorm's invariance to rescaling the input, and drops the re-centering, which costs computation and turned out not to be needed.
A model has 64 query heads and switches from full multi-head attention to grouped-query attention with 8 key–value heads. What happens to the KV cache?
- It shrinks by a factor of 8
- It shrinks by a factor of 64
- It is unchanged, since the number of query heads is unchanged
- It grows, because the groups need extra keys
Show the answer
A. It shrinks by a factor of 8
The cache stores keys and values per key–value head: times fewer. Multi-query attention, with a single key–value head, would shrink it 64-fold at a larger cost in quality.
Llama 3 8B has the same width and depth as Llama 2 7B. Which change accounts for most of its roughly 1.3 billion extra parameters?
- Grouped-query attention
- The larger RoPE base
- The larger vocabulary (about 0.8 billion more embedding parameters) and the wider SwiGLU layers (about 1.3 billion more), partly offset by smaller key–value projections
- Adding biases back to the linear layers
Show the answer
C. The larger vocabulary (about 0.8 billion more embedding parameters) and the wider SwiGLU layers (about 1.3 billion more), partly offset by smaller key–value projections
Embeddings grow from B to B, and the FFN from to per layer, B over 32 layers. Grouped-query attention removes about B of key and value weights.
At a fixed number of non-embedding parameters, what did Kaplan et al. (2020) find about depth versus width?
- Deeper is always better
- Wider is always better
- The loss is nearly unchanged over a wide range of aspect ratios
- The optimal aspect ratio is exactly 128
Show the answer
C. The loss is nearly unchanged over a wide range of aspect ratios
The aspect ratio could vary by a factor of 40 with only a slight effect on loss; a (6-layer, width 4,288) model came within 3% of a (48-layer, width 1,600) one. Common configurations near sit inside this flat region and are chosen for engineering reasons.
Further reading
- H. Touvron et al., "LLaMA: Open and efficient foundation language models," arXiv:2302.13971 (2023).
- A. Grattafiori et al. (Llama Team), "The Llama 3 herd of models," arXiv:2407.21783 (2024).
- S. Narang et al., "Do transformer modifications transfer across implementations and applications?," EMNLP (2021).
- B. Zhang & R. Sennrich, "Root mean square layer normalization," NeurIPS (2019).
- J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón & S. Sanghai, "GQA: Training generalized multi-query transformer models from multi-head checkpoints," EMNLP (2023).