How does self-attention in a transformer work?

Learning path, stage 1 of 5: How LLMs work · question 3 of 10

Self-attention lets every token look at every other token in the sequence and decide how much each one matters for its own meaning. Each token is projected into a query (Q), a key (K) and a value (V). Attention weights come from softmax(QKᵀ/√d), and each token's output is the weighted sum of the values.

Step by step

  1. Embed each token (plus position information) into a vector.
  2. Multiply by three learned matrices to get Q ("what am I looking for"), K ("what do I contain") and V ("what I pass on").
  3. Score every pair: Q·K, scaled by √d so the softmax doesn't saturate.
  4. Softmax each row into weights that sum to 1.
  5. Output = weights × V.

Details that come up in interviews

  • Multi-head attention: several attention heads run in parallel, each learning a different kind of relationship (syntax, coreference, and so on).
  • Causal mask: decoder-only LLMs block attention to future tokens, so each token only sees the past. That is what makes next-token prediction work.
  • Cost: attention is O(n²) in sequence length. This is why long contexts are expensive and why FlashAttention, sparse attention and KV caches exist.
  • Why it replaced RNNs: every position is processed in parallel during training, and long-range dependencies are one step away rather than many.

Sources

Code example

tsx
1// Scaled dot-product attention for one head, in plain TypeScript.
2type Matrix = number[][];
3
4const matmul = (a: Matrix, b: Matrix): Matrix =>
5 a.map((row) => b[0].map((_, j) => row.reduce((s, v, k) => s + v * b[k][j], 0)));
6const transpose = (m: Matrix): Matrix => m[0].map((_, i) => m.map((r) => r[i]));
7const softmax = (row: number[]) => {
8 const max = Math.max(...row);
9 const exps = row.map((x) => Math.exp(x - max)); // subtract max for stability
10 const sum = exps.reduce((a, b) => a + b, 0);
11 return exps.map((e) => e / sum);
12};
13
14export function attention(Q: Matrix, K: Matrix, V: Matrix, causal = true): Matrix {
15 const d = Q[0].length;
16 const scores = matmul(Q, transpose(K)).map((row, i) =>
17 row.map((s, j) => (causal && j > i ? -Infinity : s / Math.sqrt(d))),
18 );
19 const weights = scores.map(softmax); // each row sums to 1
20 return matmul(weights, V); // weighted mix of values
21}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app