Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

How reasoning models are trained

After this lesson: I can use a checked reward to explain how a model learns to work before it answers.

60 min lesson3 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Why does it think before it answers?

Some models pause and write out their working before they reply, sometimes for a minute. You pay for every one of those extra tokens.

For a sum or a bug, the working often makes the answer right. This lesson shows how a model can be trained to do that, with a reward a program checks.

By the end of this lesson

Note

I can use a checked reward to explain how a model learns to work before it answers.

Key words

WordWhat it meansExample
Chain of thoughtworking written out before the final answer
Reasoning modela model trained to write its working first
Verifiera program that checks an answerunit tests
Verifiable rewarda reward of 1 or 0 decided by a verifier
Test-time computeextra work done while answering, not while training
Majority votethe answer most samples agree on

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Working out loud costs tokens

A model spends the same work on every token it writes. A chain of thought gives it more tokens, and so more work, before the answer.

A reasoning model is trained to write that working first. Some products hide it and show only the reply, but it is still generated and still counted.

Worked example: two answers to 23 plus 45

WayWhat the model writesTokens, about
At onceAnswer: 683
Step by stepFirst 23 plus 45. 20 plus 40 is 60, 3 plus 5 is 8. Answer: 6825

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A program can hand out the reward

For a sum, a puzzle with one answer or code with tests, a verifier can check the result. That gives a verifiable reward: 1 if right, 0 if not. No person and no reward model is needed.

Reinforcement learning then raises the chance of whatever led to rewarded answers. Published reports on some open models describe training of this kind.

Try it: a verifier for sums

Code: python
# A verifier is a small program that checks the final answer.
def verify(text, expected):
    parts = text.split("Answer: ")
    if len(parts) < 2:
        return 0                  # no answer given: no reward
    if parts[-1].strip() == str(expected):
        return 1
    return 0

tries = [
    "First 23 plus 45. 20 plus 40 is 60, 3 plus 5 is 8. Answer: 68",
    "Answer: 67",
    "It is about seventy",
    "Answer: 68",
]
for t in tries:
    print(verify(t, 68), t)
# Add a try with the right answer and wrong working. What reward does it get?

Make a free account to save your work and track your progress.

Write the reasoning script into the lab

Command
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'rng = np.random.default_rng(3)' 'def attempt(a, b, steps):' '    right = rng.random() < (0.8 if steps else 0.3)' '    worked = \"First \" + str(a) + \" plus \" + str(b) + \". \" if steps else \"\"' '    return worked + \"Answer: \" + str(a + b if right else a + b + int(rng.integers(1, 9)))' 'def verify(text, expected):' '    return 1 if text.split(\"Answer: \")[-1] == str(expected) else 0' 'z = np.zeros(2)' 'for rnd in range(61):' '    chance = np.exp(z) / np.exp(z).sum()' '    rewards, picks = [], []' '    for k in range(20):' '        a, b = int(rng.integers(10, 99)), int(rng.integers(10, 99))' '        steps = int(rng.random() < chance[1])' '        rewards.append(verify(attempt(a, b, steps), a + b))' > steps/reasoning.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Finish writing the script

Command
docker exec jupyter sh -c "printf '%s\n' '        picks.append(steps)' '    if rnd % 20 == 0:' '        print(\"round\", rnd, \"chance of working step by step\", round(float(chance[1]), 2), \"right\", sum(rewards), \"of 20\")' '    base = np.mean(rewards)' '    for r, s in zip(rewards, picks):' '        z += 0.02 * (r - base) * (np.eye(2)[s] - chance)' 'print(attempt(23, 45, True))' 'one, vote = 0, 0' 'for k in range(200):' '    a, b = int(rng.integers(10, 99)), int(rng.integers(10, 99))' '    answers = [attempt(a, b, False).split(\"Answer: \")[-1] for i in range(5)]' '    one += answers[0] == str(a + b)' '    vote += max(answers, key=answers.count) == str(a + b)' 'print(\"one try right\", one, \"of 200, majority of 5 right\", vote, \"of 200\")' >> steps/reasoning.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Reward right sums and watch the choice change

Command
docker exec jupyter python3 steps/reasoning.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What reasoning.py printed

RoundChance of working step by stepRight of 20
00.513
200.8114
400.915
600.9316

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a reward on the answer also checks the working. The verifier reads only the final answer. A model can reach a right answer by a wrong route, and its written steps are not always how it really got there.

Spending more at answer time

More work while answering is called test-time compute. A longer chain of thought is one way. Another is to sample several answers and take a majority vote.

In the lab, 200 sums answered at once were right 60 times with one try and 89 times with a vote of five. The vote cost five times as many tokens.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Assignment: verify and vote

Write the verifier and the vote from the lesson.

extract_answer(text) returns the whole number after the last Answer: , or None. reward(text, expected) is 1 or 0. majority_vote(answers) returns the commonest answer, ignoring None, the first seen on a tie. vote_accuracy(samples, expected) is the share of problems whose vote is right.

Code: python
def extract_answer(text):
    # The whole number after the last "Answer: ", or None if there is no
    # "Answer: " or what follows is not digits (use .strip() and .isdigit()).
    return None


def reward(text, expected):
    # 1 if the extracted answer equals expected, else 0.
    return 0


def majority_vote(answers):
    # The most common answer, ignoring None. On a tie, the one seen first.
    # None if every answer is None.
    return None


def vote_accuracy(samples, expected):
    # samples is a list of lists of texts, one list per problem.
    # The share of problems whose majority vote is the expected answer.
    return 0

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.