How AI Language Models Work ยท Inside a Language Model
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.
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)math module, for functions like math.exp and math.sqrt.head 0 [0.09, 0.67, 0.09, 0.15].powered now points to a different list: [1, 1.64872, 1, 7.38906].head 1 [0.09, 0.15, 0.09, 0.67].