CS336: Language Modeling from Scratch Lecture 3 — LM Architecture and Hyperparameters

Stanford University
Updated Edition, Late 2026

What We Will Cover

  1. Normalization & residual paths
    • Pre-norm vs. post-norm, RMSNorm vs. LayerNorm, non-residual post-norm, and multi-stream hyper-connections (mHC)
  2. Feed-forward blocks & topology
    • Activations and *GLU gating, sparse MoE & MTP scaling, serial vs. parallel layers
  3. Positional embeddings
    • Sine, absolute, relative, RoPE, partial RoPE, and RoPE/NoPE hybrids
  4. Hyperparameters & regularization
    • FFN ratio, head dimensions, aspect ratio, vocabulary size, dropout & weight decay
  5. Stability at scale & attention efficiency
    • z-loss, QK-Norm, QK-Clip, gated attention, Muon; MQA/GQA/MLA and sparse/hybrid attention

Theme: learn from ablations and what frontier open models converge on — and where they deliberately diverge.

Starting Point: The Original Transformer (2017)

Softmax / Linear N× Add & LayerNorm FFN (ReLU + bias) Add & LayerNorm Masked Multi-HeadAttention Token Emb + Sine PE Decoder stack (Vaswani et al., 2017)
  • Position encoding: additive sines and cosines
    • $PE_{(pos,2i)} = \sin(pos / 10000^{2i/d_{\text{model}}})$
    • $PE_{(pos,2i+1)} = \cos(pos / 10000^{2i/d_{\text{model}}})$
  • Feed-forward network: ReLU with biases
    • $\text{FFN}(x) = \max(0, x W_1 + b_1) W_2 + b_2$
  • Normalization: post-norm LayerNorm inside the residual stream
  • Attention: standard dense multi-head attention

Every one of these four choices has been revised in modern large language models.

The Modern Dense Backbone ("LLaMA-like")

Final RMSNorm → LM Head + SwiGLU FFN (no bias) RMSNorm + Causal Attentionw/ RoPE (no bias) RMSNorm Token Embedding Unobstructed residual highway on the left
  • Pre-norm RMSNorm: normalization moves off the residual path; mean-centering and bias removed
  • Rotary position embeddings (RoPE): applied to $Q$ and $K$ inside every attention layer
  • SwiGLU FFN: gated feed-forward replaces ReLU
  • No bias terms in linear projections or norms
Why did the field converge on this backbone — and what changed on top of it by late 2026?

Three Waves of LM Architecture (2020–Late 2026)

EraRepresentative ModelsDefining Architectural Pattern
Historical baselines
2020–2024
GPT-3 (2020), PaLM (2022), Llama 2 (2023), Llama 3 (July 2024), DeepSeek-V3 (Dec 2024) Dense Transformer converges on Pre-RMSNorm + RoPE + SwiGLU + GQA; DeepSeek-V3 introduces 671B/37B MoE + MLA + MTP
2025–early-2026 wave
Apr 2025–Feb 2026
Llama 4, DeepSeek-V3.2, Qwen 3.5, Kimi K2, GLM-4.7, Nemotron 3, Gemma 4, OLMo 3 Pre-norm RMSNorm backbone; QK-Norm & QK-Clip; interleaved local/full or DeltaNet+full attention; Nemotron 3 LatentMoE; DeepSeek DSA & MTP
Late-2026 frontier
June–Oct 2026
DeepSeek-V4 / V4.1-Flash, Kimi K3 / K3.1, GLM-5.3, Qwen3.8-Flash-Next, MiniMax-M3, Nemotron 3.5 Ultra-sparse MoE (up to 896 experts); 1M-context sparse + linear hybrids (CSA2, DSA, QSA, DeltaNet/Mamba); mHC & Attention Residuals; Muon + gated stability

Most late-2026 models keep the dense block fundamentals (RMSNorm, *GLU, RoPE variants) while innovating on sparsity, attention compression, residuals, and stability.

Pre-Norm vs. Post-Norm: Protecting the Residual Path

Post-LN (2017) Pre-LN (Modern) Norm Add FFN Norm Add Attn xl Add FFN Norm Add Attn Norm xl
  • Post-LN puts normalization directly on the residual spine:
    • $x_{l+1} = \text{Norm}\big(x_l + F(x_l)\big)$
  • Pre-LN keeps a clean identity highway (with one final norm at the output):
    • $x_{l+1} = x_l + F\big(\text{Norm}(x_l)\big)$
  • Consensus: pre-norm is standard across Llama 4, Nemotron 3, DeepSeek-V3.2, and late-2026 models
    • Historical exceptions: original Transformer, BERT, and OPT-350M

Diagram adapted from Xiong et al. (2020).

Why Pre-Norm Wins: Gradient Flow and Stability

Expected Gradient Norm of FFN W¹ at Init (Xiong 2020) Gradient Expectation Layer (1 = earliest, 6 = deepest) 0.0 0.5 1.0 1 2 3 4 5 6 Pre-LN (init): uniform across depth Post-LN (init): explodes near output
  • Uniform gradients: Pre-LN keeps gradient magnitudes balanced across layers (Xiong et al., 2020)
    • Post-LN creates huge output-layer gradients and attenuated early-layer gradients at initialization
  • Fewer gradient spikes: Salazar & Nguyen (2019) observed far lower global gradient norm spikes under Pre-LN
  • Original motivation: training without learning-rate warmup
  • Modern motivation: stability and larger learning rates in deep networks

Non-Residual Post-Norm ("Double Norm")

Double Norm (Outside Residual) Add Post-Norm (branch) FFN Pre-Norm Add Post-Norm (branch) Attention Pre-Norm xl
  • Idea: if normalizing the residual stream hurts gradient flow, put the second norm on the sublayer output before addition:
    • $x_{l+1} = x_l + \text{Norm}\big(F(\text{Norm}(x_l))\big)$
  • Bounds each block's contribution to the residual stream without breaking the identity highway
  • Adoption:
    • Pre + non-residual post-norm: Grok, Gemma 2, Gemma 3
    • Non-residual post-norm only: OLMo 2

Rule of thumb: everyone now keeps normalization off the main residual spine.

Widening the Residual Stream: mHC Hyper-Connections

DeepSeek-V4 mHC (n ≈ 4 parallel streams) Learned Mix Hl (Sinkhorn–Knopp proj.) Attention / FFN (reads weighted sum) Add to 4 streams 4 × dmodel residual state
  • Motivation: a single $d_{\text{model}}$ residual stream bottlenecks cross-layer communication
  • mHC (DeepSeek-V4, 2026): widen the residual into ~4 streams mixed by a learned $n \times n$ matrix
    • Projected toward doubly stochastic via Sinkhorn–Knopp (rows & cols sum to 1)
    • Preserves the identity / signal-conservation property of standard residuals while adding capacity
  • Systems cost: $n\times$ residual memory traffic
  • Related late-2026 direction: Kimi K3 uses Attention Residuals across depth

LayerNorm vs. RMSNorm

LayerNorm (original Transformer)
$$y = \frac{x - \mathbb{E}[x]}{\sqrt{\operatorname{Var}[x] + \epsilon}} \odot \gamma + \beta$$
  • Normalizes mean and variance across $d_{\text{model}}$
  • Historical models: GPT-1/2/3, OPT, GPT-J, BLOOM
RMSNorm (modern standard)
$$y = \frac{x}{\sqrt{\frac{1}{d}\|x\|_2^2 + \epsilon}} \odot \gamma$$
  • Drops mean subtraction and bias $\beta$
  • Models: LLaMA family, PaLM, Chinchilla, T5; 2025–2026 wave (Llama 4, Nemotron 3, DeepSeek-V3.2) and late-2026 frontier

Fewer operations and fewer parameters — but matrix multiplies dominate FLOPs. Why would changing normalization speed up training at all?

Why RMSNorm Matters: FLOPs Are Not Runtime

Operator Class% FLOPs% Runtime
Tensor contraction (matmuls)99.80%61.0%
Statistical normalization0.17%25.5%
Element-wise ops0.03%13.5%
  • Normalization & element-wise ops are 0.20% of FLOPs yet 39.0% of runtime!
  • They have tiny FLOP-to-memory ratios and bottleneck on data movement
  • RMSNorm removes the mean pass and $\beta$ loads/stores
Left badge: FLOPs · Right badge: FLOP/byte ratio MHA 43G 153 Dropout 4M 1/3 + 4M 1/3 LayerNorm 29M 3.5

Source: Ivanov et al., "Data Movement Is All You Need", MLSys 2021.

RMSNorm Validation & Dropping Bias Terms

Model (223M, 11.1T ops)Step/sEarly LossFinal LossSGLUEXSumWebQWMT EnDe
Vanilla Transformer3.502.182 ± 0.0051.83871.6617.7823.0226.62
RMSNorm3.682.167 ± 0.0081.82175.4517.9424.0727.14
ReZero3.512.262 ± 0.0031.93961.6915.6420.9026.37
ReZero + RMSNorm3.342.221 ± 0.0091.87570.3317.3223.0226.19
Fixup2.952.382 ± 0.0122.06758.5614.4223.0226.31

FFN Activations: From ReLU and GeLU to *GLU

x σ(x) ReLU: max(0, x) GeLU: x·Φ(x) Swish: x·σ(x)
  • ReLU: $\text{FF}(x) = \max(0, x W_1) W_2$
    • Original Transformer, T5, Gopher, Chinchilla, OPT
  • GeLU: $\text{FF}(x) = \text{GELU}(x W_1) W_2$, $\;\text{GELU}(x) = x\Phi(x)$
    • GPT-1/2/3, GPT-J, GPT-NeoX, BLOOM
  • Outlier: Squared ReLU in Nemotron-4 340B
  • Modern consensus: gated variants (SwiGLU / GeGLU)

Non-gated activations still work (e.g., GPT-3), but gated FFNs consistently outperform them at matched parameter counts.

Gated Linear Units: ReGLU, GeGLU, and SwiGLU

Parameter budget: *GLU uses 3 matrices ($W, V, W_2$) instead of 2 $\Rightarrow$ shrink $d_{\text{ff}}$ by $\mathbf{2/3}$ (from $4 d_{\text{model}}$ to $\frac{8}{3} d_{\text{model}}$) to hold parameters and FLOPs constant.

Empirical Evidence: Gated FFNs Consistently Win

Shazeer (2020) — T5-style eval

VariantAvgCoLASST-2
$\text{FFN}_{\text{ReLU}}$83.8051.3294.04
$\text{FFN}_{\text{GELU}}$83.8653.4894.04
$\text{FFN}_{\text{Swish}}$83.6049.7993.69
$\text{FFN}_{\text{GLU}}$84.2049.1694.27
$\text{FFN}_{\text{GEGLU}}$84.1253.6593.92
$\text{FFN}_{\text{SwiGLU}}$84.3651.5993.92
$\text{FFN}_{\text{ReGLU}}$84.6756.1694.38

Raffel et al. (2019) baseline: 83.28 ± 0.235.

Narang et al. (2020) — 223M params, 11.1T ops

VariantStep/sFinal LossSGLUEXSum
Vanilla (ReLU)3.501.83871.6617.78
GeLU3.581.83875.7917.86
Swish3.621.84773.7717.74
GLU3.591.81474.2017.42
GeGLU3.551.79275.9618.27
ReGLU3.571.80376.1718.36
SwiGLU3.531.78976.0018.20

All *GLU rows beat ReLU/GeLU/Swish on final loss at equal compute.

Scaling FFNs Today: Sparse MoE and MTP

Token hidden x Router (top-k) SharedExpert(s) E1 E2 Ek … Weighted Sum

LatentMoE is Nemotron 3's (early-2026 wave); MTP (multi-token prediction) is DeepSeek's.

Model (Wave)Total / ActiveExperts (Active + Shared)
DeepSeek-V3 (Dec '24)671B / 37B256 routed (8 + 1 shared), MTP
Kimi K2 (July '25 wave)1T total384 routed (8 active)
DeepSeek-V4.1-Flash (Sept '26)552B / 16B dec, 8B pre384 routed (6 + 1 shared), 3 MTP
Kimi K3 / K3.1 (July '26)2.8T / 104B896 routed (16 + 2 shared), Stable LatentMoE
GLM-5.3 (2026)78L, $d=6144$256 routed (8 + 1 shared), 1 MTP
Qwen3.8-Flash-Next (Aug '26)125B / 6B512 routed (10 + 1 shared)

Late-2026 frontier models activate only a small fraction of parameters per token while keeping SwiGLU-style expert FFNs (Kimi K3 also applies MXFP4 QAT to experts).

Serial vs. Parallel Transformer Blocks

Serial (Standard) Parallel (GPT-J / PaLM) MLP Norm Attn Norm Shared Norm Attn MLP
  • Serial: $y = x + \text{MLP}(\text{Norm}(x + \text{Attn}(\text{Norm}(x))))$
  • Parallel: $y = x + \text{MLP}(\text{Norm}(x)) + \text{Attn}(\text{Norm}(x))$
    • Shared norm + fused input matmuls gave ~15% faster training in PaLM
  • PaLM ablation: small quality drop at 8B, neutral at 62B; 540B was extrapolated, not tested
  • Usage: GPT-J, GPT-NeoX, PaLM, Falcon 2 11B, Command R+, Command A — but serial remains the default

Position Embeddings: Sine, Absolute, and Relative

TypeFormulationHistorical Models
Sinusoidal$\text{Embed}(x, i) = v_x + \text{PE}_i$Original Transformer
Learned absolute$\text{Embed}(x, i) = v_x + u_i$GPT-1/2/3, OPT
Relative (additive)$e_{ij} = \dfrac{x_i W^Q (x_j W^K + a_{ij}^K)^T}{\sqrt{d_z}}$T5, Gopher, Chinchilla
RoPE (rotary)Rotate $Q_i, K_j$ by angles $i\Theta, j\Theta$GPT-J, PaLM, LLaMA, modern consensus

RoPE Intuition: Relative Position via Rotation

Unrotated Embeddings we know No position information "we know that" we (0) know (1) Rotate "we" by 0θ, "know" by 1θ Relative offset = +1θ "of course we know" we (2) know (3) Rotate "we" by 2θ, "know" by 3θ Exact same inner product!

RoPE Mathematics and Modern Variants

Apply block-diagonal $2\times 2$ rotations to $Q$ and $K$ at position $m$: $\; f_{\{q,k\}}(x_m, m) = R_{\Theta, m}^d W_{\{q,k\}} x_m$

$$R_{\Theta, m}^d = \begin{pmatrix} \cos m\theta_1 & -\sin m\theta_1 & 0 & 0 & \cdots & 0 & 0 \\ \sin m\theta_1 & \cos m\theta_1 & 0 & 0 & \cdots & 0 & 0 \\ 0 & 0 & \cos m\theta_2 & -\sin m\theta_2 & \cdots & 0 & 0 \\ 0 & 0 & \sin m\theta_2 & \cos m\theta_2 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & 0 & \cdots & \cos m\theta_{d/2} & -\sin m\theta_{d/2} \\ 0 & 0 & 0 & 0 & \cdots & \sin m\theta_{d/2} & \cos m\theta_{d/2} \end{pmatrix}$$

Implementing RoPE in Attention

# 1. Project hidden_states to Q, K, V and reshape to (bsz, heads, seq_len, head_dim)
q = self.q_proj(x).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(x).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(x).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)

# 2. Compute per-position cos/sin tables and rotate Q and K (never V)
cos, sin = self.rotary_emb(v, position_ids)
q, k = apply_rotary_pos_emb(q, k, cos, sin)

# 3. Proceed with standard scaled dot-product attention (q, k, v)

Hyperparameter 1: Feed-Forward Ratio ($d_{\text{ff}} / d_{\text{model}}$)

  • Non-gated default: $d_{\text{ff}} = 4\, d_{\text{model}}$
  • GLU default ($\frac{2}{3}$ scaling for 3 matrices): $$d_{\text{ff}} = \frac{8}{3}\, d_{\text{model}} \approx 2.67\, d_{\text{model}}$$
  • Several dense models push GLU ratios up to 3.5–4.0 (Llama 2/3 70B, Mistral 7B, PaLM)

Note: the 2.68 ratio is LLaMA 1 65B; Llama 2 and Llama 3 70B use 3.5.

Model (GLU)$d_{\text{ff}} / d_{\text{model}}$
PaLM (540B)4.0
Mistral 7B3.5
Llama 2 / Llama 3 70B3.5
Yi 34B2.85
LLaMA 1 65B2.68
DeepSeek 67B2.68
Qwen 14B2.67
T5 v1.12.5

FFN Ratio: Bold Exceptions and the Empirical Basin

Loss Increase vs. dff/dmodel (Kaplan+ 2020, 50M) Near-optimal basin [1, 10] Loss Increase (%) Feed-Forward Ratio dff / dmodel (log) 0% 4% 8% 10⁰ 10¹ 40
  • Empirical basin: near-optimal loss anywhere between $1\times$ and $10\times$, rising steeply past $10\times$
  • Extreme outlier — T5 11B (Raffel et al., 2020):
    • $d_{\text{ff}} = 65{,}536$, $d_{\text{model}} = 1024$ $\Rightarrow$ $64\times$ multiplier!
    • Chosen to maximize large dense matmul efficiency on accelerators
    • T5 v1.1 reverted to 2.5× GeGLU, confirming $64\times$ was suboptimal
  • Other larger ratios: Gemma 2 (8×), SmolLM / Gemma 3 / Gemma 4 (4× GLU)

Hyperparameter 2: Attention Head Dimensions

  • Standard convention: $n_{\text{head}} \cdot d_{\text{head}} = d_{\text{model}}$ (ratio = 1)
    • Convenient for reshaping $X Q \in \mathbb{R}^{n \times d} \to \mathbb{R}^{n \times h \times d/h}$
    • Treats heads as an extra batch axis
  • Not a hard requirement: several Google models and Qwen 3.5 (27B) use ratios $> 1$
  • Late-2026 decoupled heads: DeepSeek-V4.1-Flash uses 64 query heads with head_dim = 512 alongside compressed KV
ModelHeads$d_{\text{head}}$$d_{\text{model}}$Ratio
GPT-396128122881
LLaMA 26412881921
T5 v1.1646440961
T5 11B128128102416
LaMDA12812881922
PaLM48258184321.48
Qwen 3.5 (27B)2425651201.2

Ratio = 1 is the clean default, though empirical validation against ratio $> 1$ is sparse.

Hyperparameter 3: Aspect Ratio ($d_{\text{model}} / n_{\text{layer}}$)

Model$d_{\text{model}} / n_{\text{layer}}$
BLOOM205
T5 v1.1171
PaLM (540B)156
GPT-3 / OPT / Mistral / Qwen / OLMo 3128
LLaMA / LLaMA 2102
Gemma 387
Gemma 461
T5 (11B)33
Kaplan et al. (2020): Loss vs. Aspect Ratio Wide range achieves similar loss (50M, 274M, 1.5B params) Test Loss Aspect Ratio dmodel / nlayer (log) 10¹ 10² 10³
  • Sweet spot: most large models cluster around ~100–200 (while some newer models run deeper, e.g., GLM-5.3 at 78 layers, hidden size 6,144)

Why Aspect Ratio Is a Systems Choice

Layer 0Device 0 Layer 1Device 1 Layer 2Device 2 Layer 3Device 3 forward backward Sequential data dependency across layers limits parallelism and increases step latency

Hyperparameter 4: Vocabulary Size

Monolingual models (~30k–50k)

ModelVocab Size
LLaMA32,000
T5 / T5 v1.132,128
Original Transformer37,000
GPT-140,478
GPT-2 / GPT-350,257

Multilingual / production (~100k–262k)

ModelVocab Size
Yi64,000
GPT-4 (cl100k)≈100,277
DeepSeek LLM102,400
Qwen 1.5 / 2 / 3151,936–152,064
mT5 / PaLM / Gemma 4250k / 256k / 262,144

Regularization: Dropout vs. Weight Decay

ModelDropout*Weight Decay
Original Transformer0.10
GPT-20.10.1
T50.10
GPT-30.10.1
OPT0.10.1
T5 v1.100
PaLM0(variable)
LLaMA / Llama 300.1
Qwen 14B0.10.1

*Papers rarely discuss dropout; open models usually omit it.

  • Why question regularization at all?
    • Pretraining runs on trillions of tokens (e.g., Llama 3: 15T; Qwen3: 36T; DeepSeek-V4.1-Flash: 45T)
    • Mostly single-pass SGD $\Rightarrow$ hard to overfit / memorize
  • Practice: older models used dropout 0.1; modern models set dropout = 0 but keep weight decay (~0.1)
  • Puzzle: if we aren't overfitting, why does weight decay still help?

Why Weight Decay Helps LLMs (Not Overfitting!)

Val vs. Train Loss (Andriushchenko+ 2023) Validation Loss Training Loss λWD = 0.0 λWD = 0.1 λWD = 0.3
  • Not generalization: across $\lambda_{\text{WD}} \in \{0.0, 0.1, 0.3\}$, validation loss tracks training loss along the exact same line
  • Optimization dynamics: weight decay interacts with the cosine learning-rate decay schedule
    • Under constant LR, higher $\lambda_{\text{WD}}$ actually has higher training loss
    • Once LR decays (cosine schedule), higher $\lambda_{\text{WD}}$ catches up and reaches lower final training loss
We still "regularize" LLMs with weight decay, but primarily to improve optimization dynamics, not to prevent overfitting.

Training Stability: Beware the Softmaxes

Training Loss & Gradient Norm (OLMo 0424 vs. OLMo 2) Loss — OLMo 0424 7B (spiky) — OLMo 2 1124 7B (stable) Grad L2 Norm Training Steps
  • At large scale, loss spikes and gradient norm explosions derail training
  • Primary culprits — the two softmaxes:
    • Output softmax over $|V|$ logits
    • Attention softmax over $Q K^T / \sqrt{d_k}$
  • Exponentials $e^z$ amplify large logits and cause overflow or near-zero denominators
  • Goal: bound logits and activations smoothly without hurting capacity

Output Softmax Stability: The Auxiliary z-loss

Recall log-softmax with partition function $Z(x) = \sum_{r'=1}^{|V|} e^{U_{r'}(x)}$:

$$\log P(x) = U_r(x) - \log Z(x)$$

Simple, near-zero compute overhead, and directly prevents output logit drift.

Attention Softmax Stability: QK-Norm & Soft-Capping

Ablation (Perplexity ± 0.1 at 95% CI)bf16 baselinesoft_capQKV_normQK_norm_capQK_normQK_FC_norm
Perplexity (lower is better)11.1911.2410.8511.0010.8410.87

Soft-capping prevents blow-ups but can slightly hurt perplexity (and complicates fused kernels); QK-Norm improved both stability and perplexity.

2025–2026 Stability: QK-Clip, Gated Attention & Muon

Learning Rate Stress TestBaselineStabilized Setup
4× optimal LRAdamW: 183 spikes / 10k stepsMuon + gated residual: 0 spikes
3× optimal LRStandard norm: 32.0 spikes / 10k stepsGatedNorm: 3.2 spikes / 10k steps

Late-2026 frontier models (DeepSeek-V4, Kimi K3 with Per-Head Muon, Qwen3.8-Flash-Next) pair architectural gating with Muon-family optimizers for spike-free scale.

Attention Cost: Prefill vs. Incremental Decode

Training / Prefill (all $n$ tokens in parallel)
Ops: $O(b n d^2)$ · Mem: $O(b n d + b h n^2 + d^2)$
$$\text{AI} = O\!\left(\left(\frac{1}{k} + \frac{1}{bn}\right)^{-1}\right)$$
  • High arithmetic intensity ($k = d/h$, $n < d$) $\Rightarrow$ keeps compute units busy
Incremental Decode ($n$ sequential steps, KV cache)
Ops: $O(b n d^2)$ · Mem: $O(\underbrace{b n^2 d}_{K,V} + \underbrace{n d^2}_{\text{proj}})$
$$\text{AI} = O\!\left(\left(\frac{n}{d} + \frac{1}{b}\right)^{-1}\right)$$
  • Generation is sequential: each step reloads the entire KV cache
  • $n/d$ term destroys arithmetic intensity as context $n$ grows
New Query qt K Cache: K1:t (read every step!) V Cache: V1:t (read every step!) Attention Output Memory-bound! Must shrink KV

$b$ = batch size, $n$ = sequence length, $d$ = hidden dim, $h$ = heads, $k = d/h$ = head dim.

MQA and GQA: Sharing KV Heads

Multi-Head (MHA) VKQ Grouped-Query (GQA) Multi-Query (MQA)
  • MQA (Shazeer, 2019): 1 shared $K, V$ head $\Rightarrow$ mem $O(bnd + bn^2 k + nd^2)$, $\text{AI} = O\!\left(\left(\frac{1}{d} + \frac{n}{dh} + \frac{1}{b}\right)^{-1}\right)$
  • GQA (Ainslie et al., 2023): $g$ KV groups; matches MHA-XXL quality near MQA latency
Shazeer (2019)$h$$d_k,d_v$$d_{\text{ff}}$dev-PPL
Multi-head8128819229.9
Multi-query8128908830.2
Smaller MHA1–8128–16998430.9–31.2

Beyond GQA: MLA and Compressed KV Caches

Multi-Head Latent Attention (MLA) Hidden state xt KV Latent ctKVcached (low-rank) RoPE Keycached (drope) Up-proj KC Up-proj VC Multi-Head Attention
  • MLA (introduced in DeepSeek-V2; used in DeepSeek-V3 & Kimi K2): compress $K, V$ into a single low-rank latent vector $c_t^{\text{KV}}$ before caching, plus a small decoupled RoPE key
  • Late-2026 frontier KV designs:
    • GLM-5.3 (2026): MLA with kv_lora_rank = 512 and rope_dim = 64 across 64 heads
    • Kimi K3 (July 2026): gated MLA layers interleaved with Kimi Delta Attention
    • DeepSeek-V4.1-Flash (Sept 2026): 1 KV head shared by 64 Q heads (head_dim = 512), cross-layer KV reuse + FP4 KV cache $\Rightarrow$ 890 bytes/token global KV at 1M context

Sparse, Interleaved, and Hybrid Attention

3 : 1 Interleaved Block Pattern Layer 4: Full / Sparse Global Attn Layer 3: Local SWA or Linear / DeltaNet Layer 2: Local SWA or Linear / DeltaNet Layer 1: Local SWA or Linear / DeltaNet Dense O(n²) Sparse / Top-k Early fixed patterns: Child et al. (2019), GPT-3
  • 2025–early-2026 wave (interleaved):
    • Command A: 3:1 SWA (RoPE) to Full (NoPE); OLMo 3: 3/4 SWA (4,096) + Full (YaRN); also Llama 4, Gemma 3/4
    • Qwen 3.5: 3:1 Gated DeltaNet to Gated Attention
  • Late-2026 frontier (1M context):
    • MiniMax-M3 (June 2026): blockwise top-$k$ sparse on GQA — matches GQA quality on 109B with 28.4× less attention compute at 1M context
    • DeepSeek-V4 / V4.1-Flash: CSA / CSA2 + HCA; GLM-5.3: DSA sparse (top-$k=2048$)
    • Qwen3.8-Flash-Next: 3:1 Gated DeltaNet + QSA; Kimi K3: 3:1 Kimi Delta Attn + gated MLA; Nemotron 3.5: Mamba-Transformer MoE

Recap: Architecture & Hyperparameters in Late 2026

  • Block consensus
    • Non-residual norm (pre-norm RMSNorm), no bias terms
    • Gated FFNs (SwiGLU / GeGLU), serial blocks
    • RoPE / partial RoPE (or RoPE + NoPE hybrids)
  • Hyperparameter lessons
    • $d_{\text{ff}} \approx 4 d$ (or $\frac{8}{3}d$ for GLU) and $d_{\text{model}}/n_{\text{layer}} \sim 100\text{–}200$ sit in wide basins; parallelism drives depth vs. width
    • Multilingual vocabs: 100k–262k; weight decay aids LR-schedule dynamics, not overfitting
  • Stability at scale
    • Output z-loss, QK-Norm, and QK-Clip (for MLA)
    • Gated Attention, GatedNorm, and Muon suppress spikes even at $3\text{–}4\times$ LR
  • Late-2026 frontier shifts
    • Ultra-sparse MoE (256–896 experts, shared experts, LatentMoE) + MTP layers
    • Multi-stream residuals (DeepSeek-V4 mHC, Kimi K3 Attention Residuals)
    • Compressed KV (MLA, FP4 KV) + sparse/linear hybrids for 1M context