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

Free lesson

Instruction tuning with a loss mask

After this lesson: I can turn question and answer pairs into training examples with a loss mask.

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

Ask a question, get more questions

Type "When does the library open?" into a model straight after pretraining. It may carry on with "When does the library close? Where is the library?", as if it were writing a page of questions.

It is doing its job: continuing text. Instruction tuning teaches it to answer instead.

By the end of this lesson

Note

I can turn question and answer pairs into training examples with a loss mask.

Key words

WordWhat it meansExample
Base modela model straight after pretraining, which continues text
Instruction tuningmore training on instructions paired with good answers
Chat templatethe fixed layout a conversation is written in
Special tokena marker token that is not ordinary text<assistant>
Loss maska 0 or 1 per token saying whether its loss counts

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

Instruction tuning uses the same loss

Instruction tuning, also called supervised fine-tuning, starts from the base model. It trains on examples of an instruction followed by a good answer, with the same next-token loss as pretraining.

The set is far smaller than the corpus, and every example is written or checked with care. The model learns the shape of a helpful reply.

Worked example: the same prompt, two models

ModelReply to "When does the library open?"
Base modelWhen does the library close? Where is the library?
After instruction tuningAt nine on weekdays.

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 chat template marks who is speaking

Every example is written in one chat template. Special tokens mark where the user speaks, where the assistant speaks and where a reply ends.

The end token matters: the model learns to produce it, and that is how it knows to stop. The same template is used later when the model is run, or its replies go wrong.

Write the tuning script into the lab

Command
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'pairs = [' '    [\"when does the library open\", \"at nine\"],' '    [\"when does the canteen open\", \"at noon\"],' '    [\"when does the gym open\", \"at seven\"],' '    [\"where is the library\", \"next to the gym\"],' ']' 'rows = []' 'for q, a in pairs:' '    rows.append([\"<user>\"] + q.split() + [\"<assistant>\"] + a.split() + [\"<end>\"])' 'words = sorted(set(w for r in rows for w in r))' 'V = len(words)' 'print(\"vocabulary\", V)' 'print(\" \".join(rows[0]))' 'print(\"mask\", [0] * (len(pairs[0][0].split()) + 2) + [1] * (len(pairs[0][1].split()) + 1))' 'def train(masked):' '    W = np.zeros((V, V))' '    x, y = [], []' '    for r in rows:' '        on = False' '        for k in range(len(r) - 1):' > steps/sft.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' '            if r[k] == \"<assistant>\":' '                on = True' '            if on or not masked:' '                x.append(words.index(r[k]))' '                y.append(words.index(r[k + 1]))' '    x, y = np.array(x), np.array(y)' '    for step in range(200):' '        p = np.exp(W[x]) / np.exp(W[x]).sum(axis=1, keepdims=True)' '        p[np.arange(len(y)), y] -= 1' '        np.add.at(W, x, -5.0 * p / len(y))' '    print(\"masked\" if masked else \"every token\", \"positions trained\", len(y))' '    for w, n in [[\"<user>\", \"when\"], [\"<assistant>\", \"at\"]]:' '        p = np.exp(W[words.index(w)]) / np.exp(W[words.index(w)]).sum()' '        print(\"  chance of\", n, \"after\", w, round(float(p[words.index(n)]), 2))' 'train(False)' 'train(True)' >> steps/sft.py"

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

Tune on every token, then on answers only

Command
docker exec jupyter python3 steps/sft.py

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

What sft.py printed for the first example

Token<user>whendoesthelibraryopen<assistant>atnine<end>
Mask0000000111

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

Try it: build a template and its mask

Code: python
question = "when does the gym open"
answer = "at seven"

tokens = ["<user>"] + question.split() + ["<assistant>"] + answer.split() + ["<end>"]
mask = []
on = 0
for t in tokens:
    mask.append(on)
    if t == "<assistant>":
        on = 1    # every token after this one is the answer

for t, m in zip(tokens, mask):
    print(m, t)

# Made-up losses, one per token. Only the answer tokens count.
losses = [0.1, 2.0, 1.5, 1.0, 1.8, 0.9, 0.2, 0.6, 1.2, 0.3]
total = 0
for loss, m in zip(losses, mask):
    total = total + loss * m
print("masked mean loss", round(total / sum(mask), 2))
# Change the answer to "at seven on weekdays". How many tokens count now?

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

Only the answer is trained

The loss mask keeps the loss of answer tokens and drops the rest. The model still reads the question, because it needs it to answer. It is just not trained to write questions.

In the lab, the model trained on every token learnt to write user questions: "when" after <user> at 0.74. With the mask, that chance stayed at 0.06, one in 18. The answers were learnt equally well, at about 0.75.

A common mistake

Warning

Many people think instruction tuning is where a model learns its facts. Most of what it knows comes from pretraining. Instruction tuning mostly teaches the shape of a reply, so a small, careful set goes a long way.

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

Match each word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: build chat examples

Prepare training examples for instruction tuning.

format_chat(question, answer) writes one example in the template <user> ... <assistant> ... <end>. answer_mask(tokens) gives 1 for each answer token and its <end>, and 0 for everything else; a list may hold several turns. masked_mean(losses, mask) averages only the losses that count.

Code: python
def format_chat(question, answer):
    # Return "<user> " + question + " <assistant> " + answer + " <end>".
    return question


def answer_mask(tokens):
    # 1 for every token after an "<assistant>" token, up to and including
    # the next "<end>"; 0 for everything else, the markers included.
    return []


def masked_mean(losses, mask):
    # The mean of the losses where the mask is 1. Return 0 if none count.
    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.