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.
Inspect Architecture: Attention mechanism1. 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.
2. The math
3. How it works
4. The code (python)
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
In the catalog
Finished this chapter?
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.