LLM Masterclass / Module 3 of 10 Phase 1: Foundations, Tokenization & Transformer Internals

Modern Transformer Architecture — GQA/MLA Attention, RoPE, SwiGLU, RMSNorm & Sparse MoE

32 min study + 2 Live Wasm Labs + Interactive KV-Cache Simulator
⚡ Answer-First Executive Summary (TL;DR) Module 3 Key Takeaways
  • ✓ Modern frontier LLMs replace four components of the original 2017 Vaswani Transformer: Post-LayerNorm → Pre-RMSNorm; Sinusoidal absolute positions → Rotary Position Embeddings (RoPE); ReLU 2-matrix FFN → SwiGLU 3-matrix gated FFN; and MHA → Grouped-Query Attention (GQA) or Multi-Head Latent Attention (MLA).
  • ✓ Grouped-Query Attention (GQA) shares 1 Key and 1 Value head across G Query heads (e.g., 64 Q heads sharing 8 KV heads), slashing KV-Cache VRAM and memory-bandwidth bottleneck during decoding by 8x.
  • ✓ Rotary Position Embeddings (RoPE) encode relative token distance (m - n) by rotating Query and Key vectors in 2D complex frequency planes before the dot product: ⟨R_m q, R_n k⟩ = g(q, k, m - n).
  • ✓ Sparse Mixture-of-Experts (MoE) replaces the dense FFN with N expert FFNs plus a lightweight linear router that activates only Top-K experts per token (e.g., Llama 4 Maverick has 400B total parameters but activates only 17B per token).

01. 2017 Original Transformer vs. 2026 Frontier Decoder Block

Table 3.1 — Component Evolution: 2017 Vaswani Transformer vs. 2026 Frontier LLM Block
Block Subsystem 2017 Vaswani Transformer 2026 Frontier Standard (Llama 4 / DeepSeek / Qwen) Engineering & Mathematical Advantage
Normalization Post-LayerNorm: xl+1 = LN(xl + F(xl)) Pre-RMSNorm: xl+1 = xl + F(RMSNorm(xl)) Unobstructed residual gradient highway across 80–120 layers + ~10% faster norm kernel (no mean calculation).
Positional Encoding Additive Absolute Sinusoidal at Layer 0 Rotary Position Embeddings (RoPE) + YaRN at every layer Injects relative distance (m - n) via 2D rotation matrices on Q, K; extrapolates to 1M–10M context windows.
Attention & KV Cache Multi-Head Attention (nKV = nQ) Grouped-Query (GQA, nKV = nQ/8) or Latent (MLA) Reduces KV-Cache HBM footprint and decode memory bandwidth by 8× to 16×.
Feed-Forward (FFN) 2-Matrix ReLU: max(0, xW₁ + b₁)W₂ 3-Matrix SwiGLU (No bias) or Sparse Routed MoE SwiGLU(x) = (SiLU(xWgate) ⊙ xWup)Wdown; MoE decouples total knowledge capacity from per-token FLOPs.

02. Interactive KV-Cache Memory Calculator (MHA vs. GQA-8 vs. DeepSeek MLA)

Live 70B-Class Model KV-Cache VRAM Estimator (80 Layers, 64 Q Heads, d_head=128, BF16)

Slide to simulate total sequence context length (T tokens, Batch=1):

128,000 Tokens
1. Legacy MHA (64 KV Heads)
40.00 GB
327,680 B/token — OOMs a single 80GB GPU alongside weights!
2. GQA-8 (8 KV Heads • BF16)
5.00 GB (-87.5%)
40,960 B/token — Standard in Llama 3/4 & Qwen 3
3. GQA-8 + FP8 KV Quant
2.50 GB (-93.8%)
20,480 B/token — vLLM --kv-cache-dtype fp8
4. DeepSeek MLA Latent KV
1.41 GB (-96.5%)
Compressed rank dc = 512 + 64D decoupled RoPE

💻 Hands-On WebAssembly LLM Engineering Labs (Module 3)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 3.1: Implementing RMSNorm, RoPE (Rotary Embeddings), Grouped-Query Attention (GQA) & SwiGLU in Python

Execute every mathematical building block of a modern Llama-4/Qwen-3 Transformer layer from first principles and inspect tensor dimensions.

import math

# 1. Pre-Norm RMSNorm: x / sqrt(mean(x^2) + eps) * weight
def rms_norm(x: list[float], weight: list[float], eps: float = 1e-6) -> list[float]:
    ms = sum(v * v for v in x) / len(x)
    inv_rms = 1.0 / math.sqrt(ms + eps)
    return [v * inv_rms * w for v, w in zip(x, weight)]

# 2. Rotary Position Embedding (RoPE) on a 2D frequency pair (x0, x1) at position m
def apply_rope_1d(vec: list[float], pos: int, base: float = 10000.0) -> list[float]:
    d = len(vec)
    out = [0.0] * d
    for i in range(0, d, 2):
        theta = pos / (base ** (i / d))
        cos_t, sin_t = math.cos(theta), math.sin(theta)
        x0, x1 = vec[i], vec[i + 1]
        out[i]     = x0 * cos_t - x1 * sin_t
        out[i + 1] = x0 * sin_t + x1 * cos_t
    return out

# Verify RoPE Relative Distance Invariant: dot(RoPE(q, m), RoPE(k, n)) depends ONLY on (m - n)!
q = [0.6, -0.3, 0.8, 0.2]
k = [0.4, 0.5, -0.2, 0.9]
dot_pos_2_5   = sum(a * b for a, b in zip(apply_rope_1d(q, 2), apply_rope_1d(k, 5)))
dot_pos_12_15 = sum(a * b for a, b in zip(apply_rope_1d(q, 12), apply_rope_1d(k, 15)))
print("[1] RoPE Relative Position Invariant Check (distance m - n = -3):")
print(f"    ⟨RoPE(q, pos=2),  RoPE(k, pos=5)⟩  = {dot_pos_2_5:.8f}")
print(f"    ⟨RoPE(q, pos=12), RoPE(k, pos=15)⟩ = {dot_pos_12_15:.8f} (Exact match!)")

# 3. SwiGLU Activation: SiLU(gate) * up where SiLU(x) = x * sigmoid(x)
def silu(x: float) -> float:
    return x / (1.0 + math.exp(-x))

def swiglu_ffn_elem(gate_val: float, up_val: float) -> float:
    return silu(gate_val) * up_val

normed = rms_norm([1.5, -0.5, 2.0, -1.0], [1.0, 1.0, 1.0, 1.0])
print("\n[2] RMSNorm Output:", [round(v, 4) for v in normed])
print("    RMS of Normalized Vector:", round(math.sqrt(sum(v*v for v in normed)/len(normed)), 4))
print("[3] SwiGLU(gate=1.2, up=0.8):", round(swiglu_ffn_elem(1.2, 0.8), 5))
▶ Interactive Wasm Lab

Lab 3.2: Sparse Mixture-of-Experts (MoE) Top-K Router & Load Balancing

Simulate a DeepSeek-V3 / Llama-4 Maverick Sparse MoE layer routing tokens across 1 Always-On Shared Expert + Top-2 of 8 Routed Experts.

import math

def softmax(logits: list[float]) -> list[float]:
    m = max(logits)
    exps = [math.exp(x - m) for x in logits]
    s = sum(exps)
    return [e / s for e in exps]

def route_token_moe(router_logits: list[float], top_k: int = 2) -> list[tuple[int, float]]:
    probs = softmax(router_logits)
    ranked = sorted(enumerate(probs), key=lambda x: x[1], reverse=True)
    top_experts = ranked[:top_k]
    # Renormalize selected Top-K gate weights to sum to 1.0
    norm = sum(w for _, w in top_experts)
    return [(exp_id, round(w / norm, 4)) for exp_id, w in top_experts]

tokens = [
    ("def",       [0.1, 2.4, 0.3, -0.5, 1.9, 0.0, -0.2, 0.4]),
    ("SELECT",    [2.1, 0.2, 1.8, -0.4, 0.1, -0.1, 0.3, 0.0]),
    ("∫_0^∞",     [-0.3, 0.1, 0.2, 2.7, -0.1, 2.2, 0.0, -0.2]),
]

print("SPARSE MoE ROUTER (1 Shared Expert + Top-2 of 8 Routed Specialists):")
print("-" * 70)
for tok, logits in tokens:
    selected = route_token_moe(logits, top_k=2)
    print(f"  Token {tok:<8} -> Shared_Expert_0 (1.0) + Routed Top-2: {selected}")

Frequently Asked Staff LLM Interview Questions (Module 3)

Why do we divide QK^T by sqrt(d_k) in Scaled Dot-Product Attention? ▸

If components of q and k are independent random variables with mean 0 and variance 1, their dot product q · k has mean 0 and variance d_k (standard deviation sqrt(d_k)). For d_k = 128, unscaled dot products easily reach magnitudes of ±25, pushing softmax into saturated regions where one weight is 0.999999 and all gradients vanish to ~0. Dividing by sqrt(d_k) restores unit variance.

How does Grouped-Query Attention (GQA) differ from Multi-Head (MHA) and Multi-Head Latent Attention (MLA)? ▸

In MHA, every Query head has its own Key and Value head (n_kv = n_q). In MQA, all Query heads share a single K and V head (n_kv = 1). GQA (Llama 3/4, Qwen) partitions Query heads into g groups (typically g = 8), giving each group 1 K and 1 V head—achieving MHA quality with an 8x smaller KV cache. MLA (DeepSeek-V2/V3/R1) projects K and V jointly into a low-rank latent vector c_t^KV before caching, compressing the KV cache by >90%.

Why did frontier Transformers switch from LayerNorm + ReLU to Pre-RMSNorm + SwiGLU? ▸

RMSNorm drops the mean-centering subtraction of LayerNorm and only normalizes by the Root Mean Square, saving ~7–10% compute with identical training stability when placed in Pre-Norm residual position. SwiGLU uses a multiplicative gate (Swish(xW_g) ⊙ xW_up)W_down that provides smooth non-zero gradients for negative values and consistently outperforms ReLU/GELU at matched FLOPs.