How AI Language Models Work · Inside a Language Model
A transformer is the same block stacked many times: attention adds context, a normalising step keeps numbers steady, and a small network works on each word. Follow "bank" through one block.
import math
# One transformer block: attention mixes in context, then a small network works on the result.
dims = ["nature", "money"]
x = [0.5, 0.5] # "bank" coming in: it could mean either
context = [0.8, 0.2] # what attention mixed in from "river" (see the attention lesson)
# 1. Add the attention result to the input. Adding (a "residual") keeps the original meaning too.
x = [x[0] + context[0], x[1] + context[1]]
# 2. Normalise, so the numbers stay a steady size however many blocks are stacked.
size = math.sqrt(x[0] ** 2 + x[1] ** 2)
x = [round(v / size, 2) for v in x]
# 3. Feed-forward: a tiny neural network (with ReLU), added on as well.
hidden = [max(0, 1.0 * x[0] - 0.5 * x[1]), max(0, -0.5 * x[0] + 1.0 * x[1])]
x = [round(x[0] + hidden[0], 2), round(x[1] + hidden[1], 2)]
print("bank leaving the block:", x)math module, for functions like math.exp and math.sqrt.