How AI Language Models Work · Inside a Language Model
"Bank" means something different next to "river" than next to "money". Attention lets each word look at the others and borrow meaning from the ones that matter.
import math
# "I sat by the river bank." Which earlier words should "bank" pay attention to?
words = ["I", "sat", "river"]
keys = [[0.1, 0.0], [0.3, 0.1], [2.0, 0.4]] # what each word offers (made-up numbers)
values = [[0.0, 1.0], [0.2, 0.8], [1.0, 0.0]] # what each word passes on: [nature, money]
query = [1.0, 0.5] # what "bank" is looking for
# 1. Score each word: how well does its key match the query? (a dot product)
scores = []
for key in keys:
scores.append(round(query[0] * key[0] + query[1] * key[1], 2))
# 2. Softmax turns the scores into attention weights that add up to 1.
powered = [math.exp(s) for s in scores]
weights = [round(p / sum(powered), 2) for p in powered]
# 3. Mix the values, each weighted by its attention.
nature = round(sum([w * v[0] for w, v in zip(weights, values)]), 2)
money = round(sum([w * v[1] for w, v in zip(weights, values)]), 2)
print("bank now means: nature", nature, "money", money)math module, for functions like math.exp and math.sqrt.key now points to a different list: [0.3, 0.1].key now points to a different list: [2, 0.4].for key in keys.