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 2

Scaled Dot-Product & Multi-Head Attention

Query-Key-Value routing, scaling factor sqrt(d_k), causal autoregressive masks, and RoPE.

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

Want the training mechanics first? Start with Chapter 1: Modern Optimizers & Normalization Mechanics.

6 min Prerequisites: Matrix operations, Softmax, Embedding vectors
Inspect Architecture: Attention mechanism

1. The idea

Self-attention computes dynamic, data-dependent routing coefficients across all sequence positions. Each token projects into Query, Key, and Value vectors, computing similarity dot products scaled by 1/√d_k to prevent gradient saturation.

Diagram of the attention formula as a pipeline: tokens X, then the Q, K and V projections, then the scores Q K-transpose divided by the square root of d_k, then the causal mask M is added, then softmax gives the weights, which mix the values V, and finally the heads are concatenated and projected by W_O. The steps from the scores to mixing the values run in each of h heads in parallel. Below, M is shown for 5 tokens as a 5 by 5 grid: each query position keeps itself and earlier key positions, and every later position is minus infinity, which softmax turns into a weight of 0.Diagram of the attention formula as a pipeline: tokens X, then the Q, K and V projections, then the scores Q K-transpose divided by the square root of d_k, then the causal mask M is added, then softmax gives the weights, which mix the values V, and finally the heads are concatenated and projected by W_O. The steps from the scores to mixing the values run in each of h heads in parallel. Below, M is shown for 5 tokens as a 5 by 5 grid: each query position keeps itself and earlier key positions, and every later position is minus infinity, which softmax turns into a weight of 0.
The attention formula step by step, and the causal mask M that stops each token attending to later ones. No weights are shown: the actual values depend on the input.

2. The math

Scaled Dot-Product Attention Formula
Attention(Q,K,V)=softmax(QKTdk+M)V\text{Attention}(Q, K, V) = \text{softmax}\left( \frac{Q K^T}{\sqrt{d_k}} + M \right) V
Q: queries, K: keys, V: values, M: causal triangular mask (-inf above diagonal).
Rotary Position Embedding (RoPE)
RΘ,mdxm=(cos⁡(mθ1)−sin⁡(mθ1)sin⁡(mθ1)cos⁡(mθ1))(xm(1)xm(2))R_{\Theta, m}^d x_m = \begin{pmatrix} \cos(m\theta_1) & -\sin(m\theta_1) \\ \sin(m\theta_1) & \cos(m\theta_1) \end{pmatrix} \begin{pmatrix} x_m^{(1)} \\ x_m^{(2)} \end{pmatrix}
Encodes relative token distances via 2D rotation of Query/Key orthogonal coordinate pairs.

3. How it works

1
Q, K, V Linear Projections
Project input sequence X in R^(B x T x D) into Q, K, V and reshape into h parallel attention heads.
2
Apply RoPE Rotations
Rotate query and key head vectors with frequency angles θ_i = 10000^(-2(i-1)/d) to inject relative position.
3
Causal Scaled Dot-Product
Compute scores (Q K^T)/sqrt(d_k), apply upper-triangular -inf mask, and take Softmax.
4
Aggregate Values & Output Projection
Multiply attention weights by V and project concatenated heads back to hidden dimension D.

4. The code (python)

mha.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math

class MultiHeadAttentionScratch(nn.Module):
    """Multi-Head Self-Attention with Causal Masking in pure PyTorch."""
    def __init__(self, d_model: int, n_heads: int):
        super().__init__()
        assert d_model % n_heads == 0
        self.d_model = d_model
        self.n_heads = n_heads
        self.d_k = d_model // n_heads

        self.q_proj = nn.Linear(d_model, d_model, bias=False)
        self.k_proj = nn.Linear(d_model, d_model, bias=False)
        self.v_proj = nn.Linear(d_model, d_model, bias=False)
        self.out_proj = nn.Linear(d_model, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, C = x.shape

        q = self.q_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
        k = self.k_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
        v = self.v_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)

        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
        mask = torch.triu(torch.full((T, T), float("-inf"), device=x.device), diagonal=1)
        scores = scores + mask

        attn_weights = F.softmax(scores, dim=-1)
        out = torch.matmul(attn_weights, v)

        out = out.transpose(1, 2).contiguous().view(B, T, C)
        return self.out_proj(out)

5. Check yourself

Answer all 1 questions correctly to complete the chapter · 0 / 1 done
Q1/1 What is the computational complexity of standard self-attention with respect to sequence length T?

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.