How AI Language Models Work · Training a Language Model

Fine-Tuning and RLHF: Learning to Be Helpful

A pre-trained model only continues text. To make an assistant, people compare answers and a reward model learns what they prefer. That reward then steers the chat model.

rlhf.py

import math

# A pre-trained model just continues text. To make it helpful, people compare two answers,
# and a reward model learns to score answers the way they would.
answers = ["Paris is the capital of France.", "idk lol"]
features = [[1.0, 1.0], [0.0, 0.0]]   # [polite, answers the question]
weights = [0.0, 0.0]                  # the reward model starts knowing nothing
lr = 0.5                              # a person preferred the first answer

for epoch in range(3):
    rewards = [round(weights[0] * f[0] + weights[1] * f[1], 2) for f in features]
    agree = round(math.exp(rewards[0]) / (math.exp(rewards[0]) + math.exp(rewards[1])), 2)
    weights = [round(w + lr * (1 - agree) * (features[0][i] - features[1][i]), 2) for i, w in enumerate(weights)]
    print("epoch", epoch, "rewards", rewards, "agrees with the person:", agree)

best = answers[rewards.index(max(rewards))]
print("the chat model is then trained towards answers like:", best)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. Two answers to "What is the capital of France?".
  3. Two simple features per answer: is it polite, and does it answer? Real reward models are whole language models reading the text.
  4. The reward model's weights start at 0: it has no opinion yet.
  5. A person preferred the first answer. The reward model will learn to agree.
  6. epoch is created with the value 0.
  7. Score each answer: both get 0.
  8. The chance the reward model agrees with the person is a softmax over the two rewards: 0.5, a coin toss.
  9. Nudge the weights towards the features of the preferred answer, by how much it still disagreed (1 − 0.5): both weights become 0.25.
  10. It prints epoch 0 rewards [0.0, 0.0] agrees with the person: 0.5.
  11. epoch changes from 0 to 1.
  12. Now the good answer scores 0.5 and the bad one 0.
  13. Agreement 0.62.
  14. weights now points to a different list: [0.44, 0.44].
  15. It prints epoch 1 rewards [0.5, 0.0] agrees with the person: 0.62.
  16. epoch changes from 1 to 2.
  17. Rewards 0.88 and 0.
  18. Agreement 0.71, and rising.
  19. weights now points to a different list: [0.58, 0.58].
  20. It prints epoch 2 rewards [0.88, 0.0] agrees with the person: 0.71.
  21. Python moves to the next item of the loop: for epoch in range(3).
  22. The answer with the highest reward.
  23. The polite, correct answer wins. In RLHF, the chat model then writes many answers, the reward model scores them, and reinforcement learning pushes it towards the high scorers. That is how a text predictor becomes a helpful assistant.