Simple Algorithm
Deep Learning · Emergence · 26 min

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

ComponentTransformer (2017)Typical open decoder, mid-2020sStated reason
Layoutencoder–decoderdecoder-onlyone stack for every task, prompts instead of task-specific inputs
NormalizationLayerNorm after each residual addition (post-LN)RMSNorm on the input of each sublayer (pre-norm)training stability; cheaper normalization
Feed-forwardReLU, dff=4dd_{\text{ff}}=4dSwiGLU, dff≈83dd_{\text{ff}}\approx\tfrac83d rounded for hardwarebetter quality at equal parameters
Positionsinusoids added to the embeddingsrotary embeddings in every layer, often with a larger base for long contextsrelative positions; context extension
Attention headsevery head has its own keys and valuesgrouped-query attention: query heads share a few key–value headssmaller KV cache, faster decoding
Biasesin every linear layer and normalizationnonetraining stability at scale
Vocabularyabout 37,000 shared BPE tokens (English–German)32,000 (LLaMA) to 128,000 (Llama 3) or morefewer tokens per text, better multilingual coverage
Contextsentences2,048 (LLaMA), 4,096 (Llama 2), 8K extended to 128K (Llama 3)longer documents and conversations
Extra stabilizersnonesometimes QK-norm, a z-loss on the output logits, norms on sublayer outputsfewer loss spikes
A summary of documented open recipes (LLaMA, Llama 2 and 3, PaLM, OLMo 2), not of any single model. Unpublished commercial models may differ in any row.

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 23⋅4d\tfrac23\cdot4d instead of 4d4d, 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,

RMSNorm⁡(x)=g⊙x1d∑ixi2+ϵ,\operatorname{RMSNorm}(\mathbf x)=\mathbf g\odot\frac{\mathbf x}{\sqrt{\tfrac1d\sum_ix_i^2+\epsilon}},

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 HkvH_{kv} key–value heads instead of HH, the KV cache shrinks by H/HkvH/H_{kv}; with Llama 3's 8 key–value heads and 32 query heads at d=4096d=4096, 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, h=x+RMSNorm⁡(Attn⁡(x))\mathbf h=\mathbf x+\operatorname{RMSNorm}(\operatorname{Attn}(\mathbf x)), a z-loss regularizer, no weight decay on embeddings, and a RoPE base raised to 500,000, all motivated by training stability.

python
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 hh query heads share the hkvh_{kv} key–value heads in groups of h/hkvh/h_{kv}. 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.

Check your understanding

Which of these changes is aimed mainly at the cost of decoding, rather than at training stability or quality?

  1. RMSNorm before each sublayer
  2. Removing biases
  3. QK-norm
  4. 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 H/HkvH/H_{kv} with little loss in quality. The other three were introduced for stable training.

Counting a 7-billion-parameter model

DerivationParameters of a LLaMA-2-7B-style configuration
  1. 4d2=67,108,864,3 d dff=3⋅4096⋅11,008=135,266,3044d^2=67{,}108{,}864,\qquad3\,d\,d_{\text{ff}}=3\cdot4096\cdot11{,}008=135{,}266{,}304

    Take d=4096d=4096, L=32L=32 layers, 32 heads of size 128 with full key–value heads, a SwiGLU width dff=11,008d_{\text{ff}}=11{,}008 (that is 83⋅4096≈10,923\tfrac83\cdot4096\approx10{,}923 rounded up to a multiple of 256), a 32,000-token vocabulary, untied input and output embeddings, no biases. Attention and SwiGLU per layer:

  2. N=32×202,383,360+2×32,000×4096+4096=6,738,415,616N=32\times202{,}383{,}360+2\times32{,}000\times4096+4096=6{,}738{,}415{,}616

    Two RMSNorm gain vectors add 2d=8,1922d=8{,}192, so a layer holds 202,383,360202{,}383{,}360 parameters and the stack 6.4766.476 billion. Add the embedding and output matrices and a final norm:

  3. C≈6ND≈6×6.74×109×2×1012≈8.1×1022 FLOPsC\approx6ND\approx6\times6.74\times10^9\times2\times10^{12}\approx8.1\times10^{22}\ \text{FLOPs}

    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

  4. 2×128,256×4096≈1.05×1092\times128{,}256\times4096\approx1.05\times10^9

    plus attention's share T/12d=4096/49,152≈8%T/12d=4096/49{,}152\approx8\% at the full context (The Transformer Block). Llama 3 8B keeps dd and LL 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.

Predict before you look

A decoder has d=5120d=5120, L=40L=40, full multi-head attention, SwiGLU with dff=13,824d_{\text{ff}}=13{,}824, 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 4d2+3d dff=104.9M+212.3M=317.2M4d^2+3d\,d_{\text{ff}}=104.9\text{M}+212.3\text{M}=317.2\text{M}; times 40 is 12.6912.69B. The two embedding matrices add 2×32,000×5120=0.332\times32{,}000\times5120=0.33B, for about 13.0213.02B: 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 d/Ld/L 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 d/L≈100d/L\approx100–130130 (LLaMA 7B: 4096/32=1284096/32=128; LLaMA 65B: 8192/80≈1028192/80\approx102; Llama 3 405B: 16,384/126≈13016{,}384/126\approx130), 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.

Check your understanding

What did Narang et al. (2021) conclude after reimplementing many proposed transformer modifications in one codebase?

  1. Nearly all modifications improved performance across tasks
  2. Most modifications did not meaningfully improve performance; the few that did were mostly minor or came from the same codebase
  3. Only changes to the attention mechanism mattered
  4. 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 H/HkvH/H_{kv} (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 32×(4d2+3d dff+2d)+2∣V∣d+d=6,738,415,61632\times(4d^2+3d\,d_{\text{ff}}+2d)+2|\mathcal V|d+d=6{,}738{,}415{,}616 parameters, 64% in the FFNs, and costs about 8×10228\times10^{22} 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.

Question 1

How does RMSNorm differ from LayerNorm?

  1. It normalizes over the batch instead of over features
  2. It skips subtracting the mean and has no bias, rescaling by the root mean square alone
  3. It is applied after the residual addition
  4. 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

RMSNorm⁡(x)=g⊙x/mean⁡(xi2)+ϵ\operatorname{RMSNorm}(\mathbf x)=\mathbf g\odot\mathbf x/\sqrt{\operatorname{mean}(x_i^2)+\epsilon}. 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.

Question 2

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?

  1. It shrinks by a factor of 8
  2. It shrinks by a factor of 64
  3. It is unchanged, since the number of query heads is unchanged
  4. 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: 64/8=864/8=8 times fewer. Multi-query attention, with a single key–value head, would shrink it 64-fold at a larger cost in quality.

Question 3

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?

  1. Grouped-query attention
  2. The larger RoPE base
  3. 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
  4. 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 2×32,000×4096≈0.262\times32{,}000\times4096\approx0.26B to 2×128,256×4096≈1.052\times128{,}256\times4096\approx1.05B, and the FFN from 3⋅4096⋅11,0083\cdot4096\cdot11{,}008 to 3⋅4096⋅14,3363\cdot4096\cdot14{,}336 per layer, +1.31+1.31B over 32 layers. Grouped-query attention removes about 0.80.8B of key and value weights.

Question 4

At a fixed number of non-embedding parameters, what did Kaplan et al. (2020) find about depth versus width?

  1. Deeper is always better
  2. Wider is always better
  3. The loss is nearly unchanged over a wide range of aspect ratios
  4. 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 d/L≈128d/L\approx128 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).