Advanced about 6 h
The picture
01
RMSNorm + SwiGLU
cheaper, better
02
RoPE
relative position
03
GQA
smaller KV cache
04
FlashAttention
IO-aware kernel
05
MoE
sparse capacity
What a 2024+ open model changes versus GPT-2
- RMSNorm instead of LayerNorm: drops the mean subtraction, slightly cheaper.
- SwiGLU MLP instead of GELU: a gated activation that improves quality per parameter.
- RoPE instead of learned positions: encodes relative position by rotating queries and keys.
- Grouped-query attention (GQA): many query heads share fewer key/value heads.
- FlashAttention: same maths, far less memory traffic.
- Mixture of experts (MoE) in some models: only a few expert MLPs run per token.
RMSNorm and SwiGLU
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-6):
super().__init__()
self.w, self.eps = nn.Parameter(torch.ones(d)), eps
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.w
class SwiGLU(nn.Module):
def __init__(self, d, hidden):
super().__init__()
self.gate, self.up, self.down = nn.Linear(d, hidden, bias=False), nn.Linear(d, hidden, bias=False), nn.Linear(hidden, d, bias=False)
def forward(self, x):
return self.down(F.silu(self.gate(x)) * self.up(x))
Rotary position embeddings
RoPE rotates each pair of dimensions in and by an angle proportional to the position, so the dot product depends on the difference in positions. It extrapolates better than learned absolute positions, and scaling tricks extend it to longer contexts.
def rope(x, base=10000.0): # x: (B, h, T, dk), dk even
B, h, T, dk = x.shape
inv = 1.0 / (base ** (torch.arange(0, dk, 2, device=x.device) / dk))
ang = torch.outer(torch.arange(T, device=x.device), inv) # (T, dk/2)
cos, sin = ang.cos()[None, None], ang.sin()[None, None]
x1, x2 = x[..., 0::2], x[..., 1::2]
out = torch.empty_like(x)
out[..., 0::2], out[..., 1::2] = x1 * cos - x2 * sin, x1 * sin + x2 * cos
return out
The KV cache and GQA
During generation each new token attends to all previous keys and values, so we store them rather than recompute. Its size is:
def kv_cache_gb(layers, kv_heads, head_dim, seq_len, batch, bytes_per=2):
return 2 * layers * kv_heads * head_dim * seq_len * batch * bytes_per / 1e9
# 32 layers, head_dim 128, 8k context, batch 16, fp16
print(kv_cache_gb(32, 32, 128, 8192, 16)) # multi-head attention: 32 KV heads
print(kv_cache_gb(32, 8, 128, 8192, 16)) # grouped-query attention: 8 KV heads (4x smaller)
The cache, not the weights, often limits batch size and context length at serving time. GQA cuts it by sharing key/value heads.
FlashAttention
Standard attention writes the score matrix to slow GPU memory. FlashAttention computes it in tiles that stay in fast on-chip memory, with an online softmax, giving the same result with far less memory traffic and linear memory in . In PyTorch you get it through F.scaled_dot_product_attention.
Mixture of experts
An MoE layer replaces one MLP with many "expert" MLPs and a router that sends each token to the top few. You get a large parameter count but only run a fraction per token. The costs: all experts must sit in memory, routing needs load balancing, and fine-tuning is fiddlier.
Common mistakes
- Quoting an MoE model's total parameters as if every token used all of them.
- Forgetting the KV cache when sizing GPUs.
- Applying RoPE to values (it is applied to queries and keys only).
Exercises
- Read the
config.jsonof an open model and annotate each field with the concept above. - Extend your GPT with RMSNorm, SwiGLU and RoPE and compare validation loss at equal steps.
You are done when you can…
- Compute the KV-cache size for a model, batch size and context length
- Explain how RoPE, GQA and MoE each trade quality, memory or compute
- Read a modern model's config and recognise each choice