AlgoViz

Attention Is All You Need

medium 40 min

The 2017 paper that introduced the Transformer.

See it run

Five words, one question: which word does "it" mean? Watch queries meet keys and values flow.

Operations

Tokens plus position

Each word becomes numbers, and a wave pattern says where it stands (§3.4, §3.5).

Step 1 of 4

Five tokens

Tokens

  1. parcel0
  2. fit1
  3. slot2
  4. it3
  5. big4

Our sentence, cut to the five words that matter: parcel, fit, slot, it, big. Positions 0 to 4.

Step 1: Five tokens

x = embedding[token] * math.sqrt(d_model)     # learned, 512 numberspe = [sin(pos / 10000 ** (2 * i / d_model)),   # even dimensions      cos(pos / 10000 ** (2 * i / d_model))]   # odd dimensionsx = x + pe                                     # same size, so they add
Work
O(n · d)
Memory
n × d numbers
Base model
512 numbers a token

Without the wave pattern, "parcel fits slot" and "slot fits parcel" give exactly the same attention scores.

In the real world

The same attention is all you need doing real jobs. Pick one and step through it.

Max reads two endings of the same sentence. The answer to the puzzle at the top of the page.

Step 1 of 3

"too big"

Keys

  1. parcel
  2. fit
  3. slot
  4. it
  5. big

Weight

  1. 0.62
  2. 0.04
  3. 0.04
  4. 0.15
  5. 0.15
it = the parcel

The query of "it" is [2, 0]. Parcel gets 0.62, slot 0.04.

Step 1: "too big"

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Masking with 0 instead of minus infinity

    critical

    e to the 0 is 1, so a zero score still gets weight and the decoder can see the future.

    Wrong
    scores[~mask] = 0
    Right
    scores[~mask] = float("-inf")
  • Forgetting to scale

    major

    With d_k = 64 the scores spread 8 times wider, softmax becomes nearly one-hot, and training slows or stalls.

    Wrong
    w = softmax(Q @ K.T)
    Right
    w = softmax(Q @ K.T / math.sqrt(d_k))
  • Softmax over the wrong axis

    major

    Each query's weights must add to 1 across the keys. Normalising down the columns mixes up queries.

    Wrong
    w = softmax(scores, axis=0)
    Right
    w = softmax(scores, axis=-1)
  • Leaving out position

    major

    Attention gives the same scores for any order of the tokens, so word order is lost.

    Wrong
    x = embed(tokens)
    Right
    x = embed(tokens) + positions(len(tokens))
  • Recomputing every step when generating

    minor

    Old keys and values never change. Recomputing them makes generation of n tokens cost about n² projections.

    Wrong
    for t in range(n):    out = model(tokens[:t + 1])
    Right
    for t in range(n):    out = model.step(tokens[t], cache)

Interview tips

  • How to explain it

    • Queries ask, keys answer, values come back.
    • Score all pairs, scale, softmax, mix.
    • Several heads, positions added, future masked.
    • All in parallel, at the price of n².
  • Memory trick

    • Badge, question, bag.
    • Square root for the spread.
    • Minus infinity for the mask.
    • Prefill multiplies, decode reads.
  • Always say

    • Table 1: O(n²·d), O(1), O(1).
    • KV cache = 2 × L × kv heads × head dim × bytes.
    • The equation has not changed since 2017.
    • Encoder for embeddings, decoder for generation.
  • Numbers to know

    • Base: 6 + 6 layers, 512, 8 heads of 64, 2048.
    • 65M base, 213M big.
    • 28.4 BLEU En-De, 41.8 En-Fr.
    • 12 hours and 3.5 days on 8 P100s.