Abstract

Trace the five exact structural mutations—Pre-RMSNorm, RoPE, Grouped-Query Attention, SwiGLU, and Top-K Sparse MoE—that turned the 2017 Transformer into modern open-weights frontier models.

1.Five mutations between 2017 and modern frontier decoders#

Every modern open-weights language model—whether Llama-3, Qwen, Mixtral, or DeepSeek—remains a decoder-only descendant of Vaswani et al.'s 2017 Transformer. Yet if you compare a 2017 block against a 2024–2026 production block line by line, not a single sub-layer is left untouched. Four distinct systems bottlenecks forced five standardized mutations:

  1. Deep residual gradient instability and memory-bound normalization drove the shift from Post-LayerNorm to Pre-RMSNorm.
  2. Length extrapolation failure and entangled position-content projections replaced additive sinusoidal embeddings with Rotary Position Embeddings (RoPE).
  3. Autoregressive KV cache memory capacity and HBM bandwidth saturation compressed Multi-Head Attention (MHA) into Multi-Query (MQA) and Grouped-Query Attention (GQA).
  4. Expressivity bottlenecks in dense point-wise feed-forward layers replaced two-matrix ReLU blocks with three-matrix bias-free SwiGLU gates.
  5. The strict coupling between total parameter capacity and per-token FLOPs split dense feed-forward networks into Top-KK Sparse Mixture-of-Experts (MoE) layers.
Architectural Component 2017 Vanilla Transformer Modern Standard (Llama-3 / Mixtral) Primary Systems & Numerical Payoff
Normalization Placement Post-LN: LN(x+F(x))\text{LN}(x + F(x)) Pre-RMSNorm: x+F(RMSNorm(x))x + F(\text{RMSNorm}(x)) Unimpeded identity gradient highway; single-pass variance reduction
Positional Encoding Additive Sinusoidal at input Multiplicative RoPE inside each Q,KQ, K layer Exact relative-distance dot product ⟨Rmq,Rnk⟩=g(q,k,m−n)\langle R_m q, R_n k \rangle = g(q, k, m-n)
Attention KV Heads MHA (nkv=nqn_{\text{kv}} = n_q) GQA (nkv=nq/Gn_{\text{kv}} = n_q / G, e.g. 88 vs 3232) 4×4\times smaller KV cache footprint and 4×4\times less HBM decode traffic
Feed-Forward Network ReLU(xW1+b1)W2+b2\text{ReLU}(xW_1 + b_1)W_2 + b_2 SwiGLU: (SiLU(xWgate)⊙xWup)Wdown(\text{SiLU}(xW_{\text{gate}}) \odot xW_{\text{up}})W_{\text{down}} Multiplicative gating with zero bias parameters
Parameter Sparsity Dense (100%100\% weights active) Top-KK Sparse MoE (e.g. K=2K=2 of E=8E=8) Decouples model knowledge capacity (46.7B46.7\text{B}) from active compute (12.9B12.9\text{B})
Figure 1: Scaling comparison of KV cache memory across MHA, GQA, MLA, and MQA at Batch=16 alongside total versus active parameter counts in Sparse MoE models.
Figure 1: Scaling comparison of KV cache memory across MHA, GQA, MLA, and MQA at Batch=16 alongside total versus active parameter counts in Sparse MoE models.

2.From Post-LayerNorm to Pre-RMSNorm#

The 2017 Transformer applied LayerNorm after the residual addition:

xℓ+1=LayerNorm(xℓ+Fℓ(xℓ))x_{\ell+1} = \text{LayerNorm}\big(x_\ell + F_\ell(x_\ell)\big)
(1)

During backpropagation, the gradient with respect to the bottom layer x1x_1 must pass through the Jacobian of every intermediate LayerNorm operator. Near initialization, variance rescaling compounds across depth LL, amplifying gradients near the output layer while attenuating gradients in early layers. Training deep Post-LN stacks required fragile learning-rate warmup schedules.

Moving normalization inside the residual branch (Pre-Norm) creates a clean identity path from the loss all the way to the embedding layer:

xℓ+1=xℓ+Fℓ(RMSNorm(xℓ))  ⟹  ∂xL∂x1=I+∑ℓ=1L−1∂Fℓ(RMSNorm(xℓ))∂x1x_{\ell+1} = x_\ell + F_\ell\big(\text{RMSNorm}(x_\ell)\big) \implies \frac{\partial x_L}{\partial x_1} = I + \sum_{\ell=1}^{L-1} \frac{\partial F_\ell(\text{RMSNorm}(x_\ell))}{\partial x_1}
(2)

Simultaneously, Zhang and Sennrich showed that LayerNorm's mean-centering step (μ=1d∑i=1dxi\mu = \frac{1}{d}\sum_{i=1}^d x_i) and additive bias β\beta contribute negligible accuracy gains while requiring two sequential reduction passes over High Bandwidth Memory (HBM). RMSNorm discards mean centering and normalizes strictly by the root mean square:

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

A critical production detail appears in mixed-precision (bfloat16 or float16) kernels: squaring activations xi2x_i^2 can easily overflow the float16 dynamic range (max⁡≈65504\max \approx 65504) or lose precision during reduction. Industrial implementations always cast xx to float32 before computing the reciprocal square root rsqrt, then cast the normalized tensor back to the working precision before multiplying by γ\gamma.

3.Rotary Position Embeddings and complex-plane invariance#

Adding a positional vector pmp_m to the input token embedding xmx_m entangles semantics and position. Once (xm+pm)(x_m + p_m) is multiplied by WQW_Q and WKW_K across dozens of layers, the attention logit expands into four cross-terms where positional distance is mixed with arbitrary projection matrices.

Su et al. (RoFormer, arXiv:2104.09864[3][3] · RoPE · 2021RoFormer: Enhanced Transformer with Rotary Position EmbeddingOpen arXiv:2104.09864 ↗) formulated a cleaner requirement: find an operator f(q,m)f(q, m) and f(k,n)f(k, n) such that the inner product depends exclusively on the vectors q,kq, k and their relative distance m−nm - n:

⟨f(q,m), f(k,n)⟩=g(q,k,m−n)\big\langle f(q, m),\, f(k, n) \big\rangle = g(q, k, m - n)
(4)

In two dimensions, rotation in the complex plane satisfies this identity immediately. If we rotate q∈R2q \in \mathbb{R}^2 by angle mθm\theta and k∈R2k \in \mathbb{R}^2 by angle nθn\theta, the orthogonal rotation matrices Rm,RnR_m, R_n obey Rm⊤Rn=Rn−mR_m^\top R_n = R_{n - m}:

(q0′q1′)=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)(q0q1)\begin{pmatrix} q_0' \\ q_1' \end{pmatrix} = \begin{pmatrix} \cos m\theta & -\sin m\theta \\ \sin m\theta & \cos m\theta \end{pmatrix} \begin{pmatrix} q_0 \\ q_1 \end{pmatrix}
(5)

For a head dimension dheadd_{\text{head}} (such as 128128 in Llama-3), RoPE partitions the feature vector into dhead/2=64d_{\text{head}}/2 = 64 independent two-dimensional subspaces. Each pair i∈{0,…,d/2−1}i \in \{0, \dots, d/2 - 1\} rotates at a geometric frequency θi=base−2i/d\theta_i = \text{base}^{-2i/d} (where base=10000\text{base} = 10000 in standard RoFormer and 500000500000 in Llama-3 to support 128K128\text{K} context):

Represent each 2D feature pair (q2i,q2i+1)(q_{2i}, q_{2i+1}) as a complex number zq,i=q2i+i q2i+1∈Cz_{q,i} = q_{2i} + \mathrm{i}\,q_{2i+1} \in \mathbb{C}. Applying RoPE at position mm multiplies zq,iz_{q,i} by eimθie^{\mathrm{i} m \theta_i}. The inner product between rotated query at position mm and rotated key at position nn is:

⟨Rmq,Rnk⟩=∑i=0d/2−1Re⁡ ⁣((zq,ieimθi)(zk,ieinθi)‾)=∑i=0d/2−1Re⁡ ⁣(zq,izk,i‾ ei(m−n)θi)\langle R_m q, R_n k \rangle = \sum_{i=0}^{d/2 - 1} \operatorname{Re}\!\left( \big(z_{q,i} e^{\mathrm{i} m \theta_i}\big) \overline{\big(z_{k,i} e^{\mathrm{i} n \theta_i}\big)} \right) = \sum_{i=0}^{d/2 - 1} \operatorname{Re}\!\left( z_{q,i} \overline{z_{k,i}}\, e^{\mathrm{i}(m - n)\theta_i} \right)
(6)

Because the right-hand side depends on mm and nn strictly through their difference (m−n)(m - n), any two token pairs separated by the same offset Δ=m−n\Delta = m - n experience the exact same positional rotation operator.

python
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: Tensor) -> Tensor:
        # Accumulate mean-square in float32 to prevent BF16/FP16 overflow before scaling.
        orig_dtype = x.dtype
        x_fp32 = x.float()
        rms = torch.rsqrt(x_fp32.pow(2).mean(dim=-1, keepdim=True) + self.eps)
        return (x_fp32 * rms).to(orig_dtype) * self.weight


def precompute_rope_cos_sin(head_dim: int, max_seq_len: int, base: float = 10000.0) -> tuple[Tensor, Tensor]:
    if head_dim % 2 != 0:
        raise ValueError("head_dim must be even for 2D complex-plane rotation")
    inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
    positions = torch.arange(max_seq_len, dtype=torch.float32)
    angles = torch.outer(positions, inv_freq)
    return torch.cos(angles), torch.sin(angles)


def apply_rope(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
    # x shape: [B, H, T, D]
    seq_len = x.shape[2]
    cos_t = cos[:seq_len, :][None, None, :, :]
    sin_t = sin[:seq_len, :][None, None, :, :]
    x_even = x[..., 0::2]
    x_odd = x[..., 1::2]
    rot_even = x_even * cos_t - x_odd * sin_t
    rot_odd = x_even * sin_t + x_odd * cos_t
    return torch.stack([rot_even, rot_odd], dim=-1).flatten(-2)

In our companion CPU verification (labs/llm/modern-transformer), evaluating ⟨R10q,R5k⟩\langle R_{10} q, R_5 k \rangle versus ⟨R85q,R80k⟩\langle R_{85} q, R_{80} k \rangle for identical vectors at distance Δ=5\Delta = 5 yields inner products that agree to within 1.5×10−51.5 \times 10^{-5} in float32 and 10−1510^{-15} in float64. Notice also that RoPE is applied only to QQ and KK at every layer—never to VV—preserving pure content aggregation in the value weighted sum.

4.Breaking the KV cache wall: MHA to MQA and GQA#

Autoregressive inference splits into two hardware regimes. During Prefill, all SS prompt tokens are processed in parallel via dense matrix-matrix multiplications (GEMM), easily saturating GPU Tensor Cores. During Decode, the model generates one token at a time; every step must stream the entire model weight parameters plus all historical Key and Value tensors (KV Cache) from HBM for a single token's matrix-vector product (GEMV).

The exact BF16 KV cache capacity ledger is:

BytesKV=2 (K and V)×L×B×S×nkv×dhead×2 Bytes\text{Bytes}_{\text{KV}} = 2 \text{ (K and V)} \times L \times B \times S \times n_{\text{kv}} \times d_{\text{head}} \times 2\text{ Bytes}
(7)

Consider a 32-layer Llama-3-8B architecture (L=32,nq=32,dhead=128L=32, n_q=32, d_{\text{head}}=128) serving a batch of B=16B=16 sequences at context length S=32768S=32768:

  • Vanilla MHA (nkv=32n_{\text{kv}} = 32): Requires 2×32×16×32768×32×128×2=256.0 GB2 \times 32 \times 16 \times 32768 \times 32 \times 128 \times 2 = \mathbf{256.0\text{ GB}} of KV cache—more than 16×16\times the 15 GB15\text{ GB} footprint of the model weights themselves, overflowing three 80 GB H100 GPUs.
  • Multi-Query Attention (MQA, Shazeer 2019, nkv=1n_{\text{kv}} = 1): All 3232 query heads share a single Key and Value head. The KV cache drops 32×32\times to 8.0 GB\mathbf{8.0\text{ GB}}, at the cost of measurable quality degradation on complex reasoning tasks.
  • Grouped-Query Attention (GQA, Ainslie et al. 2023, nkv=8n_{\text{kv}} = 8): Queries are partitioned into G=8G = 8 groups of 44 heads each; every group shares one Key and Value head. The KV cache shrinks by 75%75\% to 64.0 GB\mathbf{64.0\text{ GB}}, matching MHA perplexity while cutting decode HBM traffic by 4×4\times.

5.SwiGLU and Top-K Sparse Mixture-of-Experts#

In a Llama-3-8B block, the GQA module holds 41.94M41.94\text{M} parameters (WQ,WO∈R4096×4096W_Q, W_O \in \mathbb{R}^{4096 \times 4096} and WK,WV∈R4096×1024W_K, W_V \in \mathbb{R}^{4096 \times 1024}), whereas the SwiGLU feed-forward network holds 176.16M176.16\text{M} parameters—over 80%80\% of every transformer layer:

SwiGLU(x)=(SiLU⁡(xWgate)⊙(xWup))Wdown,SiLU⁡(z)=z1+e−z\text{SwiGLU}(x) = \Big(\operatorname{SiLU}(x W_{\text{gate}}) \odot (x W_{\text{up}})\Big) W_{\text{down}}, \quad \operatorname{SiLU}(z) = \frac{z}{1 + e^{-z}}
(8)

Because the feed-forward network stores the vast majority of parametric knowledge, scaling a dense model forces compute FLOPs (≈2N\approx 2N per token) to grow linearly with total parameter count NN. Sparse Mixture-of-Experts (MoE)—pioneered at trillion-parameter scale by Switch Transformer (K=1K=1) and standardized for open weights by Mixtral 8x7B (E=8,K=2E=8, K=2)—replaces the single dense FFN with EE parallel SwiGLU experts gated by a lightweight router Wr∈RH×EW_r \in \mathbb{R}^{H \times E}:

y=∑i∈Top-⁡K(xWr)Softmax⁡ ⁣(Top-⁡K(xWr))i⋅Ei(x)y = \sum_{i \in \operatorname{Top-}K(x W_r)} \operatorname{Softmax}\!\big(\operatorname{Top-}K(x W_r)\big)_i \cdot E_i(x)
(9)
python
class GroupedQueryAttention(nn.Module):
    def __init__(self, hidden_size: int, num_q_heads: int, num_kv_heads: int, head_dim: int):
        super().__init__()
        if num_q_heads % num_kv_heads != 0:
            raise ValueError("num_q_heads must be divisible by num_kv_heads")
        self.num_q_heads = num_q_heads
        self.num_kv_heads = num_kv_heads
        self.group_size = num_q_heads // num_kv_heads
        self.head_dim = head_dim
        self.wq = nn.Linear(hidden_size, num_q_heads * head_dim, bias=False)
        self.wk = nn.Linear(hidden_size, num_kv_heads * head_dim, bias=False)
        self.wv = nn.Linear(hidden_size, num_kv_heads * head_dim, bias=False)
        self.wo = nn.Linear(num_q_heads * head_dim, hidden_size, bias=False)

    def forward(self, x: Tensor, cos: Tensor, sin: Tensor) -> tuple[Tensor, int]:
        b, s, _ = x.shape
        q = self.wq(x).view(b, s, self.num_q_heads, self.head_dim).transpose(1, 2)
        k = self.wk(x).view(b, s, self.num_kv_heads, self.head_dim).transpose(1, 2)
        v = self.wv(x).view(b, s, self.num_kv_heads, self.head_dim).transpose(1, 2)
        q = apply_rope(q, cos, sin)
        k = apply_rope(k, cos, sin)
        # Only the unexpanded KV heads are stored in the persistent KV cache (2 bytes per BF16 element).
        kv_cache_bytes = 2 * k.numel() * 2
        if self.group_size > 1:
            k = k.repeat_interleave(self.group_size, dim=1)
            v = v.repeat_interleave(self.group_size, dim=1)
        scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
        mask = torch.triu(torch.full((s, s), float("-inf"), device=x.device), diagonal=1)
        probs = F.softmax((scores + mask).float(), dim=-1).to(x.dtype)
        out = (probs @ v).transpose(1, 2).contiguous().view(b, s, -1)
        return self.wo(out), kv_cache_bytes


class SwiGLUFFN(nn.Module):
    def __init__(self, hidden_size: int, intermediate_size: int):
        super().__init__()
        self.w_gate = nn.Linear(hidden_size, intermediate_size, bias=False)
        self.w_up = nn.Linear(hidden_size, intermediate_size, bias=False)
        self.w_down = nn.Linear(intermediate_size, hidden_size, bias=False)

    def forward(self, x: Tensor) -> Tensor:
        return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))


class SparseMoEBlock(nn.Module):
    def __init__(self, hidden_size: int, intermediate_size: int, num_experts: int = 8, top_k: int = 2):
        super().__init__()
        self.num_experts = num_experts
        self.top_k = top_k
        self.router = nn.Linear(hidden_size, num_experts, bias=False)
        self.experts = nn.ModuleList([SwiGLUFFN(hidden_size, intermediate_size) for _ in range(num_experts)])

    def forward(self, x: Tensor) -> tuple[Tensor, Tensor]:
        b, s, h = x.shape
        flat = x.view(-1, h)
        logits = self.router(flat)
        top_logits, top_indices = torch.topk(logits, self.top_k, dim=-1)
        weights = F.softmax(top_logits.float(), dim=-1).to(x.dtype)
        out = torch.zeros_like(flat)
        for idx in range(self.num_experts):
            token_idx, k_pos = torch.where(top_indices == idx)
            if token_idx.numel() > 0:
                expert_out = self.experts[idx](flat[token_idx])
                out.index_add_(0, token_idx, expert_out * weights[token_idx, k_pos].unsqueeze(-1))
        counts = torch.bincount(top_indices.view(-1), minlength=self.num_experts).float()
        return out.view(b, s, h), counts / counts.sum()

In Mixtral 8x7B, each layer contains 88 experts, but every token routes to only K=2K=2 experts. Total model parameters reach 46.7B\mathbf{46.7\text{B}} (which must reside in HBM), yet each token executes only 12.9B\mathbf{12.9\text{B}} active parameters—delivering the knowledge capacity of a 47B47\text{B} model at the latency and FLOP budget of a 13B13\text{B} model.

Run the complete CPU verification suite to inspect RoPE invariance, GQA cache compression, and Top-KK MoE routing:

bash
labs/.venv/bin/python -m unittest discover -s labs/llm/modern-transformer -p 'test_*.py' -v
labs/.venv/bin/python labs/llm/modern-transformer/modern_blocks.py

6.References and next chapter#

References

  1. [1]
  2. [2]
  3. [3]
  4. [4]
  5. [5]
  6. [6]
  7. [7]

Share