Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 01 of 10 · Attention
Build the operation at the heart of every model in this repo: scaled dot-product attention with a causal mask, and then multi-head attention (split the width into heads, attend per head, merge back). You use only matmul, exp and reshapes; no torch attention function.
Notation: B batch, h heads, N_q queries, N_k keys, d_k key/query width, d_v value width, d = h * d_k model width.
Inputs Q [B, h, N_q, d_k] K [B, h, N_k, d_k] V [B, h, N_k, d_v]
S = Q @ K^T / sqrt(d_k) [B, h, N_q, N_k]S[i, j] = how well query i matches key j. Dividing by sqrt(d_k) keeps the variance of S near 1, so softmax does not saturate.
S[i, j] = -inf wherever query i must NOT see key j.
Causal: query i sees keys j <= i (no peeking ahead).
P = softmax(S, dim=-1) [B, h, N_q, N_k]P[i, j] = exp(S[i, j] - m_i) / sum_j' exp(S[i, j'] - m_i), m_i = max_j S[i, j] (subtracting m_i avoids overflow and does not change the result). Each row sums to 1; masked entries get exactly 0.
O = P @ V [B, h, N_q, d_v]Each output row is a weighted average of the value rows.
Multi-head attention on x [B, N, d] with n_heads = h, d_k = d / h
q = x W_q^T + b_q, k = x W_k^T + b_k, v = x W_v^T + b_v [B, N, d] split: [B, N, d] → view [B, N, h, d_k] → transpose → [B, h, N, d_k] attend: O = attention(q, k, v) [B, h, N, d_k] merge: [B, h, N, d_k] → transpose → [B, N, h, d_k] → [B, N, d] out = O W_o^T + b_o [B, N, d]
Head i owns columns i*d_k ... (i+1)*d_k - 1 of q, k and v. That is why the split is "view as [B, N, h, d_k], then transpose", and not "view as [B, h, N, d_k]" (which would mix tokens and heads).
[B, N, d] → [B, h, N, d_k][B, h, N, N]Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.
Cells on this page:
The lab file's imports. Run this cell first (or press Run all).
causal_mask(n_q, n_k=None, device=None)Boolean mask of shape [n_q, n_k]; True means "query i may attend to key j".
With n_k == n_q (the usual case) query i sees keys 0..i, so the mask is lower-triangular, diagonal included.
When there are more keys than queries (n_k > n_q) the queries are the LAST n_q positions of the sequence; this happens during generation with a KV cache (lab 03). Query i then sits at absolute position i + (n_k - n_q) and may attend to keys j <= i + (n_k - n_q).
Example, n_q = 2, n_k = 4 (2 cached keys + 2 new tokens):
[[True, True, True, False], [True, True, True, True ]]
softmax(x, dim=-1)softmax(x)_i = exp(x_i - max(x)) / sum_j exp(x_j - max(x)) along dim.
Must not overflow for large inputs (try x = [1000., 1001., 1002.]) and must give exactly 0 for entries equal to -inf (masked positions). Do not call torch.softmax / F.softmax here; build it from torch.exp.
scaled_dot_product_attention(q, k, v, mask=None)Attention from matmul + softmax.
Args:
q: [..., N_q, d_k] (leading dims, e.g. [B, h], are batch dims) k: [..., N_k, d_k] v: [..., N_k, d_v] mask: optional bool tensor broadcastable to [..., N_q, N_k]; True = may attend (same convention as causal_mask()).
Returns:
out: [..., N_q, d_v] weights: [..., N_q, N_k] the softmax probabilities (rows sum to 1)
split_heads(x, n_heads)[B, N, d] → [B, h, N, d_k] with h = n_heads and d_k = d // h.
Head i must hold the columns x[:, :, i*d_k:(i+1)*d_k].
merge_heads(x)[B, h, N, d_k] → [B, N, h * d_k], the exact inverse of split_heads.
class MultiHeadAttention(nn.Module)Multi-head self-attention with separate q/k/v/out projections.
The layers are created for you. The check copies these weights into torch.nn.MultiheadAttention and compares the outputs.
forward(x, causal=False)Args:
x: [B, N, d_model]
causal: if True, apply causal_mask(N)
Returns:
out: [B, N, d_model] weights: [B, h, N, N] per-head attention probabilities
Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).