Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 05 · 45 minutes

Measure how often a model invents facts

After this lesson you can
  • Write a quiz with known answers and score a model as right, wrong or "does not know"
  • Show that a confident wrong answer is not fixed by asking the model to say when it is unsure
  • Show what changes when you put the facts into the prompt
Lab files of this lesson (18)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The vendor of the help-page chatbot says that it "answers correctly from our product guide". Your lead does not want a promise. She wants a number: how often does the model give a confident wrong answer, and does a line in the prompt such as "say when you are unsure" fix it? You will write a small quiz with answers that you know, score the model with code and not by eye, and test three versions of the prompt.

Recall

Does a language model check whether the next token is true?

No. It gives chances to likely tokens, and a program picks one. Likely text and true text are not the same.

JSON mode returned text that parses. Is the data then valid?

Not necessarily. JSON mode makes the syntax right. Your program must still check the keys, the types and the allowed values, as triage did in lesson 4.

The idea

A language model predicts likely text. It does not look facts up, and nothing in its answer text shows how sure it is. When a question has an answer in its training data, the likely text is often right. When it has not, the likely text is still an answer-shaped text. This is called a hallucination: output that is fluent and wrong.

To handle it, score every answer in one of three ways, with code that compares the answer with a known one.

How one answer is scored
QuestionModelAnswergrade()Verdictsent in one of three conditionsfree text, fluent or notyour code looks for the known answerright, unknown or wrongQuestionModelAnswergrade()Verdict1234
  1. Question → Model: sent in one of three conditions
  2. Model → Answer: free text, fluent or not
  3. Answer → grade(): your code looks for the known answer
  4. grade() → Verdict: right, unknown or wrong
VerdictMeaningRisk
rightThe expected answer is in the reply.None.
unknownThe model says that it does not know.Low. The user knows to look elsewhere.
wrongA different answer, given as fact.High. This is the hallucination.

You will build a ten-question quiz with known answers: four basic questions, two hard ones where a small model is likely to be wrong, and four about KR Books, an invented shop that no model has seen. Then you change the prompt and score again.

Worked example

Work in ~/krlab/llms-and-agents with llm.py from lesson 3.

1. Write the quiz

Create quiz.json. JSON is a text format for lists and records. Each item has a kind, a question and the text that a right answer must contain (in lower case). The two CVE identifiers (a CVE is a public number for a known vulnerability) are real ones. Shellshock has two well-known identifiers, the first bug and its follow-up, so the expected text lists both with | between them.

quiz.json

[
  {"kind": "basic", "q": "Which TCP port does HTTPS use by default?", "a": "443"},
  {"kind": "basic", "q": "Which TCP port does SSH use by default?", "a": "22"},
  {"kind": "basic", "q": "What is the capital city of Australia?", "a": "canberra"},
  {"kind": "basic", "q": "Which Linux command prints the current directory?", "a": "pwd"},
  {"kind": "hard", "q": "What is the CVE identifier of the Log4Shell bug in Log4j?", "a": "2021-44228"},
  {"kind": "hard", "q": "What is the CVE identifier of the Shellshock bug in Bash?", "a": "2014-6271|2014-7169"},
  {"kind": "kr", "q": "In which city is the shop KR Books?", "a": "bergen"},
  {"kind": "kr", "q": "How many days do customers have to return a book to KR Books?", "a": "21"},
  {"kind": "kr", "q": "Who founded KR Books?", "a": "marta voss"},
  {"kind": "kr", "q": "What is the name of the loyalty card of KR Books?", "a": "page club"}
]
One item of quiz.json
"kind": "hard"basic, hard or kr"q": "What is the CVE identifier..."the question"a": "2021-44228"text that a right answer holds"kind": "hard"basic, hard or kr"q": "What is the CVE identifier..."the question"a": "2021-44228"text that a right answer holds

2. Write the scorer

Create quiz.py. It has three conditions: the plain question; the question with a system message that says "answer only if you are sure"; and the same message plus five facts about KR Books. json.load(open("quiz.json")) reads the file into a list of dictionaries. expected.split("|") cuts the expected text at each |, and any(e in text for e in ...) is true when one piece is somewhere inside the answer. total.setdefault(key, []) returns the list for key, and makes an empty one first if there is none. The block under if __name__ == "__main__": runs only when you start this file, not when another file imports it (step 5 uses this). grade gives the verdict: right if the expected text is in the answer, unknown if a refusal phrase from NO_ANSWER is in it, wrong in every other case.

quiz.py

import json

from llm import chat

quiz = json.load(open("quiz.json"))

SURE = "Answer only if you are sure. If you do not know, reply exactly: I do not know."
FACTS = (
    "Facts about KR Books: it is a small bookshop in Bergen. Marta Voss founded it. "
    "A customer can return a book within 21 days. The loyalty card is called Page Club. "
    "The shop is closed on Monday."
)
CONDITIONS = {
    "plain": None,
    "say I do not know": SURE,
    "do not know + facts": SURE + " Use these facts when they apply. " + FACTS,
}
NO_ANSWER = ("do not know", "don't know", "couldn't find", "don't have", "can't provide", "no information",
             "not aware", "unable to", "not familiar")


def ask(question, system, seed=1, temperature=0.0):
    messages = [{"role": "system", "content": system}] if system else []
    messages.append({"role": "user", "content": question + " Answer in at most 12 words."})
    return chat(messages, max_tokens=40, seed=seed, temperature=temperature).strip()


def grade(answer, expected):
    text = answer.lower()
    if any(e in text for e in expected.split("|")):
        return "right"
    if any(p in text for p in NO_ANSWER):
        return "unknown"
    return "wrong"


def score(system, seed=1, temperature=0.0, show=False):
    total = {}
    for item in quiz:
        answer = ask(item["q"], system, seed, temperature)
        verdict = grade(answer, item["a"])
        total.setdefault(item["kind"], []).append(verdict)
        if show:
            print(f"  {verdict:8} {item['q']}\n           -> {answer}")
    return total


if __name__ == "__main__":
    for name, system in CONDITIONS.items():
        print(name)
        total = score(system, show=True)
        for kind, verdicts in total.items():
            print(f"  {kind:5}", {v: verdicts.count(v) for v in ("right", "wrong", "unknown")})

3. Run the three conditions

Temperature 0 gives one repeatable answer for each question. The run asks 30 questions and takes a few minutes. The output below keeps the answers that matter and every summary line.

python3 quiz.py
plain
  wrong    What is the CVE identifier of the Log4Shell bug in Log4j?
           -> CVE-2021-4483 is the identifier for the Log4Shell vulnerability in Log4j.
  wrong    What is the CVE identifier of the Shellshock bug in Bash?
           -> CVE-2014-7160 is the identifier for the Shellshock bug in Bash.
  unknown  In which city is the shop KR Books?
           -> I couldn't find any information on a shop called KR Books.
  ...
  basic {'right': 4, 'wrong': 0, 'unknown': 0}
  hard  {'right': 0, 'wrong': 2, 'unknown': 0}
  kr    {'right': 0, 'wrong': 0, 'unknown': 4}
say I do not know
  wrong    What is the CVE identifier of the Log4Shell bug in Log4j?
           -> CVE-2021-4483 is the CVE identifier for the Log4Shell bug in Log4j.
  wrong    What is the CVE identifier of the Shellshock bug in Bash?
           -> CVE-2014-7160.
  unknown  In which city is the shop KR Books?
           -> I do not know.
  ...
  basic {'right': 4, 'wrong': 0, 'unknown': 0}
  hard  {'right': 0, 'wrong': 2, 'unknown': 0}
  kr    {'right': 0, 'wrong': 0, 'unknown': 4}
do not know + facts
  unknown  Which TCP port does HTTPS use by default?
           -> I do not know.
  unknown  What is the CVE identifier of the Log4Shell bug in Log4j?
           -> I do not know.
  right    In which city is the shop KR Books?
           -> KR Books is located in Bergen.
  right    Who founded KR Books?
           -> Marta Voss founded KR Books, a small bookshop in Bergen.
  ...
  basic {'right': 0, 'wrong': 0, 'unknown': 4}
  hard  {'right': 0, 'wrong': 0, 'unknown': 2}
  kr    {'right': 4, 'wrong': 0, 'unknown': 0}

4. Read the result

The numbers are right / wrong / unknown.

Conditionbasic (4)hard (2)KR Books (4)
plain4 / 0 / 00 / 2 / 00 / 0 / 4
say "I do not know"4 / 0 / 00 / 2 / 00 / 0 / 4
plus facts0 / 0 / 40 / 0 / 24 / 0 / 0

Four findings.

  • The model invented, and it was sure. Both answers are wrong. They have the right look (CVE-year-number), and the model gave no sign of doubt. The real ones are CVE-2021-44228 and CVE-2014-6271 (or CVE-2014-7169). Basic facts that appear everywhere in text, such as a port number, are right. A rare exact string is not.
  • The instruction did not help where it was needed. "Answer only if you are sure" changed the wording of the KR Books answers and left the two wrong identifiers as they were. The model does not know that it does not know.
  • The model was honest about the shop. At temperature 0 it said that it had no information about KR Books in all four cases. A model can be more careful about a name it has never seen than about a fact that it half remembers.
  • The facts in the prompt fixed the shop and broke the rest. All four KR Books answers are right, because the answer is in the prompt. But the model now said "I do not know" to every other question, even the port numbers that it answers well alone. It seems to have read "use these facts when they apply" as "use only these". One run of one model is not a rule for all small models. A change to a prompt changes everything, so score again after every change.

5. Repeat with random sampling

Temperature 0 is one path. Run the hard and KR Books questions again with temperature 0.8 and the seeds 0, 1 and 2. Create repeat_quiz.py. It imports ask, grade and quiz from quiz.py; the guard if __name__ == "__main__" in that file keeps the import from running the whole quiz again.

repeat_quiz.py

from collections import Counter

from quiz import ask, grade, quiz

runs = Counter()
for seed in range(3):
    for item in quiz:
        if item["kind"] in ("hard", "kr"):
            runs[item["kind"], grade(ask(item["q"], None, seed, 0.8), item["a"])] += 1
for kind in ("hard", "kr"):
    print(kind, {v: runs[kind, v] for v in ("right", "wrong", "unknown")})
python3 repeat_quiz.py
hard {'right': 1, 'wrong': 5, 'unknown': 0}
kr {'right': 0, 'wrong': 3, 'unknown': 9}
Answers about KR Books at temperature 0.8, of 12
Said "I do not know"9 of 12Invented an answer3 of 12Right0 of 12Said "I do not know"9 of 12Invented an answer3 of 12Right0 of 12

On the hard questions the model gave a right identifier once in six answers. Three inventions in twelve is a rate that you cannot ignore when the answer drives an action. Your numbers can differ: this is a measurement, not a law.

Your turn

Part A. Test the grader. The scorer is code, so it can be wrong too. Import grade from quiz.py and give it these seven answers, each with the expected text that follows. There is no model here.

#ExpectedThe model answered
1443HTTPS uses port 443.
222I do not know.
3canberraThe capital is Sydney.
42014-6271It is CVE-2014-6721.
5pwdI am not sure, but I think it is pwd.
6bergenI don't know. It could be Oslo or Bergen.
721You have 7 or 14 days, but I could not find the shop's policy.

Answers 6 and 7 are graded in a way that a person would not accept. Write down why, and how you would change grade.

Part B. Invent a small thing that no model has seen (a cafe, a club, a product), and write four questions with known answers. Score the model with the conditions "plain" and "facts in the prompt". Write down your counts ("right, unknown, wrong"). The page does not check them: a model writes different text on each machine.

Check yourself

Why can a model give a wrong answer with no sign of doubt?

It predicts likely text. A wrong identifier that looks like a right one is likely text. The model has no separate check that compares its output with a source, so the tone of the answer says nothing about whether it is true.

You add "say I do not know if you are unsure" to the prompt. The wrong answers stay. Why?

The instruction only helps when the model can tell that it is unsure, and in the hard cases it cannot: the wrong answer feels as likely to it as a right one. The instruction mainly changes the wording for questions where the model already had no answer.

Putting the facts into the prompt made all four KR Books answers right. What did it cost?

In this run the model refused the questions that were not in the facts, including basic ones that it answered well before. Prompts have side effects. Measure the effect on the whole quiz, not only on the case that you wanted to fix.

Why score "unknown" apart from "wrong"?

They have different costs. "Unknown" sends the user to another source. "Wrong" gives a false fact that the user may act on. A change that turns wrong into unknown is an improvement, even if the right count falls.

Field notes

  • Never act on an identifier, a package name, a URL or a command that a model produced without checking it against the real source. Look up the CVE in a vulnerability database. Check that the package exists and who publishes it. Attackers register the names that models tend to invent.
  • A quiz with known answers is a regression test. Keep it with your application, run it after every change of model, prompt or settings, and keep the counts. A model update can change the numbers without a word in the release notes.
  • Ten questions are a demonstration, not a measurement. For a decision, use at least a few hundred questions from your own domain, run each with several seeds, and report counts with the setting. A difference of one or two answers is noise.
  • Reducing invention is a system job, not a prompt job: give the model the source text (the next lesson), ask for the quote that supports an answer, check the quote against the source in code, and show the source to the user.
  • Ratings from a model grading another model are cheap, but they inherit the same errors. For facts with a known answer, grade with code, as grade does here, and test the grader as you did in "Your turn".