How AI Language Models Work ยท Inside a Language Model

Multi-Head Attention: Asking Several Questions

One attention head can only look for one thing. Give "chased" two heads, and one finds who did the chasing while the other finds who was chased.

multi_head.py

import math

# "The cat chased the mouse." The word "chased" asks two questions at once, one per attention head.
words = ["the", "cat", "the", "mouse"]
keys = [[0.0, 0.0], [2.0, 0.5], [0.0, 0.0], [0.5, 2.0]]   # [is a doer, is a receiver]
queries = [[1.0, 0.0], [0.0, 1.0]]                         # head 0: who chased? head 1: chased whom?

for head, query in enumerate(queries):
    scores = [query[0] * k[0] + query[1] * k[1] for k in keys]
    powered = [math.exp(s) for s in scores]
    weights = [round(p / sum(powered), 2) for p in powered]
    print("head", head, weights)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. The other words in "The cat chased the mouse", seen from the word "chased".
  3. Each word's key, with two numbers: [is a doer, is a receiver]. "cat" is a doer, "mouse" a receiver, "the" neither.
  4. Two queries, one per head. Head 0 asks "who chased?", head 1 asks "chased whom?".
  5. Head 0 first.
  6. Score each word: the query [1, 0] picks out the "doer" number. cat scores 2.
  7. Softmax, step 1.
  8. Head 0's weights: cat 0.67. This head has found who did the chasing.
  9. It prints head 0 [0.09, 0.67, 0.09, 0.15].
  10. Head 1: same words, same keys, a different query.
  11. Now mouse scores 2 and cat 0.5.
  12. powered now points to a different list: [1, 1.64872, 1, 7.38906].
  13. Head 1's weights: mouse 0.67. Same sentence, a completely different focus.
  14. It prints head 1 [0.09, 0.15, 0.09, 0.67].
  15. Two heads, two answers: "chased" now knows both who chased (cat) and whom (mouse). A real model joins every head's mixed values side by side and passes them on. Large models have dozens of heads in every layer.