3 Model Architecture 5 / 9
  1. In this chapter
  2. From RNNs to Attention
  3. Attention Basics
  4. Positional Encoding Explained
  5. Transformer Block Explained
  6. Modern LLM Architecture
  7. Efficient Attention
  8. Mixture of Experts (MoE)
  9. Long Context
  10. State Space Models and Hybrids
All chapters →

Chapter 3 · Model Architecture 3.5

Modern LLM Architecture: From GPT-2 to Llama, Qwen and DeepSeek

Almost every mainstream open LLM is a refined decoder-only Transformer: Pre-Norm with RMSNorm, a SwiGLU feed-forward network, RoPE positions and GQA attention, and some add mixture of experts (MoE) to grow parameters without growing compute in proportion.

Intermediate 15 min read Updated Companion code ↓

After this page you will be able to

  • Name the “standard recipe” of modern open LLMs: Pre-Norm with RMSNorm, SwiGLU, RoPE and GQA.
  • Explain why RMSNorm can replace LayerNorm and how SwiGLU's gate rewrites the feed-forward network.
  • Read the configuration of a few representative models, and change a setting in the interactive widget to see where the parameters go.
  • Say how MoE grows the parameter count without growing compute in proportion.
On this page
  1. The big picture: the “standard recipe” of modern LLMs
  2. Pre-Norm and RMSNorm
  3. Where to put the normalization
  4. RMSNorm instead of LayerNorm
  5. SwiGLU: a feed-forward network with a gate
  6. RoPE: writing position into a rotation angle
  7. GQA: fewer K/V heads for faster inference
  8. The complete structure of one block
  9. Configurations of a few representative models
  10. Try it: edit a configuration and see where the parameters go
  11. Mixture of experts (MoE): many parameters, but each token uses only part of them
  12. Other changes worth watching
  13. Summary and exercises
  14. Quick self-check
  15. FAQ

The big picture: the “standard recipe” of modern LLMs

The original 2017 Transformer was an encoder-decoder. Today’s general-purpose LLMs almost all keep only the decoder half: they take a sequence of tokens, pass it through a number of identical blocks, and output a distribution over the next token. The skeleton hasn’t changed, but nearly every part inside the block has been replaced:

ComponentOriginal Transformer / GPT-2Modern open models (the Llama family as the reference)Why it changed
Norm placementPost-Norm (original), Pre-Norm (GPT-2)Pre-NormMore stable training of deep networks
Norm typeLayerNormRMSNormSimpler and faster, same quality
Positional encodingSinusoidal / learned absolute positionsRoPERelative position information, better for long context
Feed-forward networkTwo-layer MLP + GELUSwiGLU (gated MLP)Better quality at the same parameter count
Attention headsMHA (independent K/V per head)GQA (several query heads share K/V)Smaller KV cache, faster inference
Linear-layer biasWith biasDropped in the Llama family; Qwen keeps only the QKV biasSimpler implementation, almost no effect on quality
Feed-forward layerDense FFNSome models use MoE (sparse experts)Larger total parameters, roughly the same per-token compute

Below we look at what each change does and why.

Pre-Norm and RMSNorm

Where to put the normalization

A block has two sublayers (attention and the feed-forward network), each wrapped in a residual connection. Whether normalization comes after or before the sublayer determines how stable training is:

Post-Norm:xl+1=Norm(xl+F(xl))Pre-Norm:xl+1=xl+F(Norm(xl))\text{Post-Norm:}\quad x_{l+1} = \mathrm{Norm}\big(x_l + F(x_l)\big) \qquad\qquad \text{Pre-Norm:}\quad x_{l+1} = x_l + F\big(\mathrm{Norm}(x_l)\big)

The residual path of Pre-Norm is an identity path with no transformation at all: gradients can flow back to the shallow layers along it almost losslessly, so deep networks are easier to train and less sensitive to learning-rate warmup. Post-Norm puts the normalization on the residual path, which makes training unstable once there are many layers. The price of Pre-Norm is that the output variance grows with depth, so a final normalization layer is needed at the end.

RMSNorm instead of LayerNorm

LayerNorm subtracts the mean, divides by the standard deviation, then scales and shifts. RMSNorm argues that “subtract the mean” and “shift” are not essential and keeps only the scaling by the root mean square:

RMSNorm(x)=x1d∑i=1dxi2+ϵ⊙g\mathrm{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \epsilon}} \odot g

Here gg is a learnable scale vector and ϵ\epsilon is a small constant that avoids division by zero. With one fewer mean computation and no bias parameter, it is simpler to implement and cheaper to compute, and on large models it matches LayerNorm in quality.

import torch
import torch.nn as nn


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

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        inv_rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt()
        return x * inv_rms * self.weight

SwiGLU: a feed-forward network with a gate

A traditional feed-forward network is two linear maps with an activation in between:

FFN(x)=W2 σ(W1x)\mathrm{FFN}(x) = W_2\,\sigma(W_1 x)

SwiGLU introduces a “gate”: one linear branch weights the activated output of the other branch element by element, and the result is projected back to the original dimension.

FFNSwiGLU(x)=W2(SiLU(W1x)⊙W3x),SiLU(z)=z⋅σ(z)\mathrm{FFN}_{\text{SwiGLU}}(x) = W_2\big(\mathrm{SiLU}(W_1 x) \odot W_3 x\big),\qquad \mathrm{SiLU}(z) = z \cdot \sigma(z)

It has one extra matrix W3W_3, so to keep the parameter count roughly equal to the original two-matrix MLP (hidden dimension 4d4d), the hidden dimension shrinks to about 23⋅4d≈83d\tfrac{2}{3}\cdot 4d \approx \tfrac{8}{3}d. Llama 2 7B, for example, has d=4096d = 4096 and uses a feed-forward hidden dimension of 11008 (8d/3≈109238d/3 \approx 10923, rounded up to a multiple of 256). At the same parameter budget, the gated structure usually beats a plain MLP.

import torch.nn as nn
import torch.nn.functional as F


class SwiGLU(nn.Module):
    def __init__(self, dim: int, hidden: int):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden, bias=False)  # gate
        self.w3 = nn.Linear(dim, hidden, bias=False)  # value
        self.w2 = nn.Linear(hidden, dim, bias=False)  # project back to dim

    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))

RoPE: writing position into a rotation angle

RoPE (rotary position embedding) does not add a position vector to the input. Instead, in the attention of every layer it splits the dimensions of the query and key into pairs and rotates each pair by an angle proportional to the position. The key property is that after rotation the dot product depends only on the relative distance between the two positions:

⟨Rm q,  Rn k⟩=⟨q,  Rn−m k⟩\langle R_m\, q,\; R_n\, k \rangle = \langle q,\; R_{n-m}\, k \rangle

So the model gets relative position information naturally, and it is easier to extend to longer contexts than with absolute positional encodings by adjusting the rotation frequencies. Positional Encoding Explained: Absolute, Relative and RoPE has the full derivation.

GQA: fewer K/V heads for faster inference

In standard multi-head attention (MHA), every query head has its own key and value head. Grouped-query attention (GQA) splits the HH query heads into GG groups, and each group shares one pair of K/V heads:

SchemeKV headsKV cache size relative to MHA
MHAHH1×
GQAGG (1<G<H1 < G < H)G/HG/H
MQA11/H1/H

Llama 3 8B has 32 query heads and 8 KV heads, so its cache is only 1/4 of MHA’s. Because the bottleneck of the decode phase is the memory bandwidth for reading the KV cache, a smaller cache means lower latency and higher concurrency, which is why GQA has become almost the default for new models. For concrete cache estimates see KV Cache and Inference Performance, where the calculator also lets you compare MHA and GQA. For what GQA costs in quality, how MQA and MLA work, and FlashAttention, see Efficient Attention.

The complete structure of one block

Put these parts together and a modern decoder block looks like this:

def block(x, layer):
    # Sublayer 1: RMSNorm -> GQA attention (with RoPE and causal mask) -> residual
    h = x + attention(rmsnorm(x, layer.attn_norm), layer)
    # Sublayer 2: RMSNorm -> SwiGLU feed-forward network -> residual
    return h + swiglu(rmsnorm(h, layer.ffn_norm), layer)


def model(token_ids):
    x = embedding[token_ids]
    for layer in layers:
        x = block(x, layer)
    return rmsnorm(x, final_norm) @ output_matrix  # a score for every token in the vocabulary

The parameter count of the whole model can be computed directly from the configuration. Let the hidden dimension be dd, the number of layers LL, the number of query heads HH, the number of KV heads HkvH_{kv}, the per-head dimension dh=d/Hd_h = d/H, the feed-forward hidden dimension ff and the vocabulary size VV. The parameters per layer are about

2d2+2 d Hkv dh⏟attention: WQ, WO, WK, WV+3 d f⏟SwiGLU+2d⏟norms\underbrace{2d^2 + 2\,d\,H_{kv}\,d_h}_{\text{attention: }W_Q,\,W_O,\,W_K,\,W_V} + \underbrace{3\,d\,f}_{\text{SwiGLU}} + \underbrace{2d}_{\text{norms}}

plus the input and output vocabulary matrices 2Vd2Vd (if the weights are not shared). Let’s verify it in code:

def count_params(d, L, H, H_kv, f, V):
    d_head = d // H
    per_layer = 2 * d * d + 2 * d * H_kv * d_head + 3 * d * f + 2 * d
    return L * per_layer + 2 * V * d + d  # the final +d is the final norm


# Llama 3 8B: d=4096, 32 layers, 32 query heads, 8 KV heads, f=14336, V=128256
print(f"{count_params(4096, 32, 32, 8, 14336, 128256) / 1e9:.2f}B")  # 8.03B
# Llama 2 7B: d=4096, 32 layers, 32 KV heads (MHA), f=11008, V=32000
print(f"{count_params(4096, 32, 32, 32, 11008, 32000) / 1e9:.2f}B")  # 6.74B

The output matches the published parameter counts of both models. For Llama 3 8B, about 70% of the parameters sit in the feed-forward networks, attention takes only about 17%, and the remaining 13% or so are the two vocabulary matrices, so “making the model bigger” is to a large extent widening and deepening the feed-forward layers.

Configurations of a few representative models

The table lists the main configuration of three common open models. All of them are variants of the recipe above, differing mainly in size, vocabulary and the number of KV heads:

ModelLayersHidden dimQuery / KV headsFFN dimVocabularyParameters
Llama 3 8B32409632 / 814336128256about 8.03B
Mistral 7B32409632 / 81433632000about 7.24B
Qwen2.5 7B28358428 / 418944152064about 7.6B

Among models of 7B–8B parameters, the larger the vocabulary, the more parameters the embedding matrices take; Qwen2.5 has only 4 KV heads, so its cache is even smaller than Llama 3 8B’s.

Try it: edit a configuration and see where the parameters go

The widget below counts parameters with the formulas above; the presets come from each model’s published config. Change the layers, hidden size, KV heads or vocabulary and watch the total, the split and the KV cache move.

  1. Llama 3 8B. 8.03B in total: feed-forward 70.2%, attention 16.7%, the two vocabulary matrices 13.1%, norms just 0.003%.
  2. Switch to Llama 2 7B. It uses MHA (32 KV heads), so attention rises to 31.9%, and with a 32,000-token vocabulary the matrices drop to 3.9%. Its KV cache is 512 KiB per token, four times Llama 3 8B’s 128 KiB.
  3. Switch to Llama 3 70B. Feed-forward grows to 79.9% and the vocabulary matrices shrink to 3.0%: the larger the model, the smaller the vocabulary’s share. With 80 layers and 8 KV heads the cache is 320 KiB per token; with 64 KV heads (plain MHA) it would be 2560 KiB.

Mixture of experts (MoE): many parameters, but each token uses only part of them

In a dense model every token passes through all parameters. The idea of MoE is to replace each feed-forward network with NN parallel “expert” feed-forward networks plus a router, which picks only the kk highest-scoring experts to compute for each token:

y=∑i∈TopK(g(x))gi(x)  Ei(x),g(x)=softmax(Wr x)y = \sum_{i \in \mathrm{TopK}(g(x))} g_i(x)\; E_i(x),\qquad g(x) = \mathrm{softmax}(W_r\, x)

Here EiE_i is the ii-th expert and WrW_r is the router’s parameter matrix. The result: total parameters can grow a lot (more capacity), while per-token compute grows only with the number of activated experts.

ModelTotal parametersActive parameters per tokenExpert setup
Mixtral 8x7Babout 46.7Babout 12.9B8 experts, 2 chosen per token
DeepSeek-V3671Babout 37Beach MoE layer has 1 shared expert and 256 routed experts, 8 of which are activated per token

MoE brings three new problems:

  1. Load balancing. If the router keeps sending tokens to a few experts, the others learn nothing and the compute is uneven. The classic fix is an auxiliary loss that encourages balance (Switch Transformers); DeepSeek-V3 proposed a balancing strategy that does not rely on an auxiliary loss.
  2. Memory. Although each token computes only part of the model, the weights of all experts must sit in memory, so MoE saves compute but not necessarily memory.
  3. Communication. Experts are usually spread over different GPUs, so tokens must be dispatched and gathered across devices, and communication becomes a bottleneck for training and inference.

How the gate weights are normalized differs between models (a softmax over all experts followed by top-kk, or top-kk first and a softmax over the kk selected scores). The page Mixture of Experts (MoE): Routing, Load Balancing and Sparse Activation computes total and active parameters, compares the three balancing methods and lets you try capacity overflow and bias balancing; the paper background is in the explainer Switch Transformers.

Other changes worth watching

  • Attention variants that shrink the KV cache. DeepSeek-V2/V3 use multi-head latent attention (MLA), which compresses K/V into a low-dimensional latent vector before caching it, greatly reducing the cache while keeping quality; Mistral 7B uses sliding-window attention, limiting each position to the most recent span of tokens. The formulas and a cache-size comparison are in Efficient Attention.
  • Sequence modeling beyond attention. State space models (such as Mamba) replace attention with a linear-complexity recurrence, and hybrid architectures combine the two; see State Space Models and Hybrid Architectures, and the Mamba paper walkthrough for the paper’s side.
  • Rewiring the residual connection itself. Hyper-connections widen the residual stream into nn streams mixed by a matrix; mHC constrains that matrix to be doubly stochastic so the gain of many composed layers stays bounded, see the mHC paper breakdown; Kimi’s Attention Residuals takes a different route, keeping a single stream but replacing the fixed weight-1 sum over earlier layers with softmax attention over their outputs, see the Attention Residuals breakdown.
  • Longer contexts. By adjusting the RoPE frequency base and doing staged continued training on long contexts, modern models have extended their context length from a few thousand to hundreds of thousands or even a million tokens.

Summary and exercises

Key points of this page:

  1. Modern LLMs are decoder-only Transformers; the changes are concentrated inside the block: Pre-Norm, RMSNorm, SwiGLU, RoPE and GQA.
  2. Every change has a clear motivation: stable training, cheaper compute, better quality, or cheaper inference.
  3. MoE trades “many total parameters, few active parameters” for capacity, but introduces problems of load balancing, memory and communication.
  4. The parameter count can be computed directly from the configuration, and most parameters sit in the feed-forward networks.

Quick self-check

1. Why is Pre-Norm easier to train in very deep networks than Post-Norm?

  • Because Pre-Norm keeps the output variance of every layer constant
  • Because the residual path carries no transformation at all, an identity path along which gradients flow back to shallow layers almost undamaged
  • Because Pre-Norm needs no final normalization layer
  • Because Pre-Norm has fewer parameters

Post-Norm puts the normalization on the residual path, so gradients become problematic as depth grows. The price of Pre-Norm is exactly that the output variance accumulates with depth, which is why a final normalization layer is added at the end; the first and third options are the opposite of the facts.

2. Which of these are changes in Llama-style models relative to GPT-2? (multiple answers)

  • LayerNorm replaced by RMSNorm
  • The two-layer GELU MLP replaced by SwiGLU
  • Learned absolute positional embeddings replaced by RoPE
  • Pre-Norm replaced by Post-Norm
  • Decoder-only replaced by encoder-decoder

GPT-2 is already a Pre-Norm decoder-only model, so those two are not changes, and the last two options also point in the wrong direction. The changes concentrate inside the block: the normalization type, the feed-forward network, the positional encoding, and how K/V heads are shared (GQA).

3. SwiGLU has one more matrix than a two-matrix MLP. To keep the parameter count about equal to an original MLP with hidden dimension 4d, what hidden dimension should it use?

  • About 4d
  • About 2d
  • About 8d/3 (about 2.67d)
  • About d/3

The original MLP has two d×4d matrices, so 8d² parameters; SwiGLU has three d×h matrices, so 3dh. Setting 3dh = 8d² gives h = 8d/3. Llama 2 7B uses 11008, which is 8×4096/3 ≈ 10923 rounded up to a multiple of 256.

4. Llama 3 8B has 32 query heads and 8 KV heads. Compared with MHA with the same number of heads, how large is its KV cache?

  • The same size
  • Half
  • A quarter
  • An eighth

The KV cache is proportional to the number of KV heads, and 8/32 = 1/4. The bottleneck in the decode phase is the memory bandwidth for reading the KV cache, so a smaller cache means lower latency and higher concurrency.

5. Taking Llama 3 8B as an example, which part holds the most parameters?

  • The attention layers
  • The feed-forward networks
  • The vocabulary (embedding and output) matrices
  • The normalization layers

By the formula on this page, the feed-forward networks hold about 70%, attention about 17%, the two vocabulary matrices about 13%, and normalization is negligible. Making a model bigger is therefore largely a matter of widening and deepening the feed-forward layers.

6. Why does an MoE model “save compute but not necessarily memory”?

  • Because the expert weights can live on the CPU and are not needed at inference time
  • Because each expert is much larger than the feed-forward network of a dense model
  • Because each token passes through only the top-k experts, so compute follows the active parameters, but all expert weights must fit in GPU memory, so memory follows the total parameters
  • Because MoE does not use a KV cache

For example, Mixtral 8x7B has about 46.7B total parameters and about 12.9B active per token. Storing the weights in FP16 takes about 93 GB, while the compute per token is only that of a dense model of about 12.9B.

Exercises:

  1. Use count_params to estimate the parameter count of Llama 3 70B (d=8192d=8192, 80 layers, 64 query heads, 8 KV heads, f=28672f=28672, V=128256V=128256) and compare it with the published figure of about 70.6B.
  2. Take the Llama 3 8B configuration (32 layers, head dimension 128, FP16), change the number of KV heads from 8 to 32 (that is, fall back to MHA), and compute how the KV cache changes for 8192 tokens at batch size 16.
  3. Explain why an MoE model “saves compute but not necessarily memory”.
Reference answers
  1. count_params(8192, 80, 64, 8, 28672, 128256) gives 70,553,706,496, about 70.55B, in line with the published figure of about 70.6B. The feed-forward networks hold 79.9%, attention 17.1% and the two vocabulary matrices only 3.0%: the larger the model, the smaller the share of the vocabulary and the more the parameters concentrate in the feed-forward layers.

  2. The KV cache per token is 2×L×Hkv×dh×22 \times L \times H_{kv} \times d_h \times 2 bytes (one copy each for K and V, 2 bytes per FP16 number).

    KV headsPer token8192 tokens × batch 16
    8 (GQA, original)128 KiB16 GiB
    32 (back to MHA)512 KiB64 GiB

    The cache grows 4×, by 48 GiB. For comparison, the FP16 weights of Llama 3 8B are only about 15 GiB, so the MHA version’s KV cache is already more than four times the weights. This is why GQA became the default choice.

  3. Compute depends on the parameters each token actually passes through (the active parameters); MoE sends each token through only the top-kk experts, so its FLOPs are far lower than a dense model with the same total parameters. Memory depends on all the weights that must be available at any moment; the router does not know in advance which experts the next token will pick, so every expert has to stay resident in GPU memory. For Mixtral 8x7B, with about 46.7B total parameters, the FP16 weights take about 93 GB, while the compute per token is only that of a dense model of about 12.9B. With a larger batch, a batch of tokens touches almost all experts, and the memory traffic rises accordingly.

Next, read Scaling Laws to see how model size and data should be balanced.

FAQ

Are all of today's large language models decoder-only?
The mainstream general-purpose LLMs (the GPT series, Llama, Qwen, DeepSeek, Mistral and others) are essentially all decoder-only, trained for next-token prediction with a causal mask. Encoder-decoder models (such as T5) and encoder-only models (such as BERT) are still used for particular tasks, but they are not the mainstream for general chat models.
Why can RMSNorm replace LayerNorm?
RMSNorm only rescales by the root mean square and drops the mean-centering and the bias term, so it is simpler to compute and uses less memory bandwidth. In practice its training stability and quality on large models match LayerNorm, so Llama and many other models use it.
How should I read the parameter count and inference cost of an MoE model?
An MoE model has two numbers, "total parameters" and "active parameters". Total parameters determine how much memory is needed to hold all the experts; active parameters are the ones that actually take part in computing each token, that is, the per-token compute cost. DeepSeek-V3, for example, has 671B total parameters and about 37B active per token.
Does GQA hurt model quality?
Compared with full multi-head attention, GQA lets several query heads share one set of keys and values, which costs a small amount of quality but shrinks the KV cache and memory traffic proportionally, so inference is faster and uses less memory. In practice the loss is usually far smaller than the gain, which is why it has become the default for large models.