How AI Language Models Work · Inside a Language Model

The Transformer Block

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.

transformer_block.py

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)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. Two meaning dimensions, to keep things small. Real models use thousands.
  3. "bank" arrives at the block with an even mix: it could mean a river bank or a money bank.
  4. What attention found in the sentence: mostly "nature", from "river".
  5. Step 1: add the attention result to the input. bank is now [1.3, 0.7], leaning towards nature.
  6. Step 2: measure the vector's length…
  7. …and divide by it, so the vector has length 1: [0.88, 0.47]. Without this, numbers could grow huge after many blocks.
  8. Step 3: a tiny neural network with ReLU (negative results become 0). It boosts nature by 0.645, money by 0.03.
  9. Added on: [1.52, 0.5]. "bank" now clearly means the river kind.
  10. One block: attention (look at other words), normalise, feed-forward (think about this word), each added on. A large language model is this block repeated 30 to 100 times, then a final layer that scores every possible next token.