Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
Modern ArchitecturesLEVEL 3 · ADVANCEDChapter 3

Modern Decoder-Only LLM Block (Llama / Mistral Style)

Grouped-Query Attention (GQA), SwiGLU FFN, Pre-RMSNorm, and KV Caching.

Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.

6 min Prerequisites: Multi-Head Attention & RMSNorm
Inspect Architecture: Decoder-only language models (GPT series)

1. The idea

Modern frontier Large Language Models (Llama 3, Mistral, Gemma) share an optimized autoregressive decoder block combining Pre-RMSNorm, Grouped-Query Attention (GQA) for 4x KV-cache memory compression, SwiGLU gated activations, and residual streams.

Diagram of one decoder block. The residual stream x runs left to right. A first branch takes x through RMSNorm and then grouped-query attention (GQA), and adds the result back: x becomes x + GQA(x_norm). A second branch takes the new x through RMSNorm and then the SwiGLU gated feed-forward network, SiLU(x W_gate) times (x W_up), then W_down, and adds it back: x becomes x + SwiGLU(x_ffn). Below, inside GQA, 32 query heads are drawn in 8 groups of 4, each group sharing one key/value head, so the KV cache holds only 8 heads: 32 / 8 = 4 times smaller.Diagram of one decoder block. The residual stream x runs left to right. A first branch takes x through RMSNorm and then grouped-query attention (GQA), and adds the result back: x becomes x + GQA(x_norm). A second branch takes the new x through RMSNorm and then the SwiGLU gated feed-forward network, SiLU(x W_gate) times (x W_up), then W_down, and adds it back: x becomes x + SwiGLU(x_ffn). Below, inside GQA, 32 query heads are drawn in 8 groups of 4, each group sharing one key/value head, so the KV cache holds only 8 heads: 32 / 8 = 4 times smaller.
One decoder block: each branch is normalised first, then added back into the residual stream. Below, the lesson's GQA example of 32 query heads sharing 8 key/value heads.

2. The math

SwiGLU Gated Feed-Forward Network
SwiGLU(x)=(SiLU(xWgate)⊙(xWup))WdownSiLU(z)=z⋅σ(z)\text{SwiGLU}(x) = \left( \text{SiLU}(x W_{\text{gate}}) \odot (x W_{\text{up}}) \right) W_{\text{down}} \qquad \text{SiLU}(z) = z \cdot \sigma(z)
Gated linear unit with continuous SiLU non-linearity for enhanced representation capacity.
Grouped-Query Attention (GQA) Memory Scaling
KV Memory Reduction=HQHKV(e.g. 32 query heads share 8 KV heads  ⟹  4× smaller KV cache)\text{KV Memory Reduction} = \frac{H_Q}{H_{KV}} \qquad (\text{e.g. } 32 \text{ query heads share } 8 \text{ KV heads} \implies 4\times \text{ smaller KV cache})
Multiple query heads share single key/value head pairs during inference.

3. How it works

1
Pre-RMSNorm Normalization
Apply scale normalization x_norm = RMSNorm(x) prior to attention.
2
Grouped-Query Attention
Compute GQA self-attention and add residual: x <- x + GQA(x_norm).
3
Pre-RMSNorm FFN
Normalize residual stream: x_ffn = RMSNorm(x).
4
SwiGLU Projection & Residual
Execute gated FFN and add residual: x <- x + SwiGLU(x_ffn).

4. The code (python)

llm_block.py
import torch
import torch.nn as nn
import torch.nn.functional as F

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:
        rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
        return x * rms * self.weight

class SwiGLU(nn.Module):
    def __init__(self, dim: int, hidden_dim: int):
        super().__init__()
        self.w_gate = nn.Linear(dim, hidden_dim, bias=False)
        self.w_up = nn.Linear(dim, hidden_dim, bias=False)
        self.w_down = nn.Linear(hidden_dim, dim, bias=False)

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

class ModernLLMBlock(nn.Module):
    """Complete Llama 3 / Mistral style Transformer Decoder Block."""
    def __init__(self, dim: int, n_heads: int, hidden_dim: int):
        super().__init__()
        self.attn_norm = RMSNorm(dim)
        self.attn = nn.MultiheadAttention(dim, n_heads, batch_first=True)
        self.ffn_norm = RMSNorm(dim)
        self.ffn = SwiGLU(dim, hidden_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        normed = self.attn_norm(x)
        attn_out, _ = self.attn(normed, normed, normed, need_weights=False)
        x = x + attn_out
        x = x + self.ffn(self.ffn_norm(x))
        return x

5. Check yourself

Answer all 1 questions correctly to complete the chapter · 0 / 1 done
Q1/1 What is the primary operational benefit of Grouped-Query Attention (GQA) over Multi-Head Attention (MHA)?

Finished this chapter?

Weekly newsletter

The Epoch Zero newsletter

What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.