How AI Language Models Work · Training a Language Model
Show the model the real next word, measure how surprised it was (the loss), and nudge its scores. Repeat this billions of times and you have a language model.
import math
# Training: show the model the real next word, measure how surprised it was, and nudge its scores.
options = ["like", "want", "tea"]
scores = [0.0, 0.0, 0.0] # after "i", the untrained model has no preference
target = 0 # in the training text, "i" was followed by "like"
lr = 1.0
for step in range(3):
powered = [math.exp(s) for s in scores]
chances = [round(p / sum(powered), 3) for p in powered]
loss = round(-math.log(chances[target]), 3)
# The gradient of this loss: (chance - 1) for the right word, (chance - 0) for the others.
scores = [round(s - lr * (c - (1 if i == target else 0)), 3) for i, (s, c) in enumerate(zip(scores, chances))]
print("step", step, "chance of like:", chances[target], "loss:", loss)math module, for functions like math.exp and math.sqrt.step is created with the value 0.step 0 chance of like: 0.333 loss: 1.1.step changes from 0 to 1.powered now points to a different list: [1.94838, 0.71677, 0.71677].scores now points to a different list: [1.091, -0.545, -0.545].step 1 chance of like: 0.576 loss: 0.552.step changes from 1 to 2.powered now points to a different list: [2.97725, 0.579842, 0.579842].scores now points to a different list: [1.371, -0.685, -0.685].step 2 chance of like: 0.72 loss: 0.329.