Looking for the lab runner…

Hands-on lab 01 of 10 · Attention

Scaled dot-product attention, from matmul + softmax

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.

Time: 45-60 minCheck: python labs/check.py 1

The maths, step by step

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]
  1. 1
    Scores
    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.
  2. 2
    Mask
    S[i, j] = -inf wherever query i must NOT see key j.

    Causal: query i sees keys j <= i (no peeking ahead).

  3. 3
    Softmax
    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.
  4. 4
    Output
    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).

Read alongside

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 1: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab01_attention.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

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:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 the causal mask

causal_mask(n_q, n_k=None, device=None)

to write

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 ]]
Hint 1
build a column of query positions and a row of key positions and compare them; broadcasting turns [n_q, 1] vs [1, n_k] into [n_q, n_k].
Hint 2
offset = n_k - n_q; allowed[i, j] = j <= i + offset.
Hint 3
torch.arange(n_q, device=device)[:, None] + offset >= torch.arange(n_k, device=device)[None, :]

2 a numerically stable softmax

softmax(x, dim=-1)

to write

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.

Hint 1
exp(1000) overflows float32 to inf, and inf / inf = nan. Subtracting the row max first makes the largest exponent exp(0) = 1.
Hint 2
m = x.amax(dim=dim, keepdim=True); keepdim=True keeps the shape broadcastable against x. exp(-inf - m) is exactly 0.
Hint 3
e = torch.exp(x - m); return e / e.sum(dim=dim, keepdim=True)

3 scaled dot-product attention

scaled_dot_product_attention(q, k, v, mask=None)

to write

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)
Hint 1
four lines: scores, mask, softmax, weighted sum. Use your softmax().
Hint 2
scores = q @ k.transpose(-2, -1) / q.shape[-1] ** 0.5 transpose(-2, -1) swaps the last two dims, whatever the leading dims are.
Hint 3
scores = scores.masked_fill(~mask, float("-inf")) when mask is not None; weights = softmax(scores, dim=-1); out = weights @ v

4 split and merge heads

split_heads(x, n_heads)

to write

[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].

Hint 1
first split the LAST dim into (h, d_k), then move h in front of N.
Hint 2
x.view(B, N, h, d_k) gives [B, N, h, d_k]; which two dims must swap?
Hint 3
x.view(B, N, n_heads, d // n_heads).transpose(1, 2)

merge_heads(x)

to write

[B, h, N, d_k] → [B, N, h * d_k], the exact inverse of split_heads.

Hint 1
undo split_heads in reverse order: swap h and N back, then flatten.
Hint 2
after transpose the tensor is not contiguous, so .view() fails; use .reshape() (or .contiguous().view()).
Hint 3
x.transpose(1, 2).reshape(B, N, h * d_k)

5 multi-head attention module

class MultiHeadAttention(nn.Module)

to write

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.

Write 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
Hint 1
project -> split_heads -> scaled_dot_product_attention -> merge_heads -> out_proj.
Hint 2
the mask is [N, N]; it broadcasts over [B, h, N, N] automatically. Create it on x.device so the code also runs on a GPU.
Hint 3
q = split_heads(self.q_proj(x), self.n_heads) (same for k, v) mask = causal_mask(N, device=x.device) if causal else None o, w = scaled_dot_product_attention(q, k, v, mask) return self.out_proj(merge_heads(o)), w

✎ Scratch cell

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).