◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

Hallucinations

Why language models sometimes state false things fluently and confidently, how to measure whether a model knows what it doesn't know, and the practical ways to reduce the damage, from retrieval and citations to abstaining.

Level
●●●●● Easy
Reading
11 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

GPT and Decoder-Only Models

This leads to

—
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. GPT and Decoder-Only Models
  33. Hallucinations

Read them roughly in this order. See it on the concept map →

Why it matters

In 2023 two New York lawyers filed a brief citing six court decisions that did not exist. They had asked ChatGPT for supporting cases, and it produced realistic-looking citations, complete with case names, docket numbers and quotations. The judge sanctioned the lawyers. In 2024 a Canadian tribunal ordered Air Canada to honour a refund policy that its customer-service chatbot had invented. Google's first public demo of its Bard chatbot, in February 2023, included a wrong claim about the James Webb Space Telescope.

These are hallucinations: outputs that are fluent and confident but false or unsupported. (Some researchers prefer confabulation, the clinical term for producing false memories without intent to deceive, because "hallucination" suggests perception.) They are the single biggest obstacle to trusting language models with facts. They are not a bug in one product; they follow from how these models are trained, and every model released so far still produces them, though far less often than early ones.

This chapter explains why hallucinations happen, how to measure whether a model "knows what it knows" (calibration), and what actually reduces the damage in real systems: retrieval and grounding, citations, verification, and letting the model say "I don't know".

The intuition

A language model is trained to continue text plausibly. Ask it for the birthday of a famous scientist and the most plausible continuation is the correct date, because that fact appears many times in its training data. Ask it for the birthday of an obscure person mentioned once, and the most plausible continuation is still a date: the format is certain even when the content is not. The model writes a date in the same confident tone either way.

Think of a student in an exam where wrong answers cost nothing and blank answers score zero. The rational strategy is to always write something. Language models have been trained, and largely evaluated, under exactly those rules.

Two distinctions help:

  • Factuality: is the output true about the world? Inventing a court case is a factuality failure.
  • Faithfulness: is the output consistent with the source it was given? A summary that adds a claim not in the document is unfaithful, even if the claim happens to be true.

Researchers also distinguish intrinsic hallucinations (contradicting the provided source) from extrinsic ones (adding unsupported information).

Key idea Models hallucinate because they are trained to produce plausible text and rewarded for answering rather than abstaining. Rare facts are the riskiest. The reliable fixes are external: give the model the facts (retrieval), make it show its sources, check its claims, and reward "I don't know".

How it works

Why plausible is not the same as true

Pretraining minimises next-token loss (Language Modeling and Next-Token Prediction). That objective rewards matching the distribution of text, not truth. For common facts, distribution and truth coincide. For rare facts, they diverge.

A 2025 OpenAI paper, "Why Language Models Hallucinate" (Kalai, Nachum, Vempala and Zhang), made this precise. It argues that generating valid statements is at least as hard as classifying statements as valid or not, so any error rate in that classification shows up as hallucination. For arbitrary facts with no pattern to learn (such as individuals' birthdays), it relates the expected hallucination rate to the fraction of such facts that appear exactly once in the training data: if 20% of birthday facts are seen only once, expect the model to get at least roughly 20% of such questions wrong.

Other causes add to this:

  • Training and evaluation reward guessing. The same paper argues that most benchmarks give a point for a right answer and zero for both a wrong answer and "I don't know", so guessing always scores at least as well as abstaining (Evaluating LLMs and Benchmarks).
  • Preference training can reward confident, complete-sounding answers and agreement with the user (RLHF and Preference Optimization), which encourages sycophancy and overconfidence.
  • Snowballing: once a model has committed to a wrong claim early in an answer, it tends to continue consistently with it.
  • Knowledge cutoff: the model knows nothing after its training data ends. The knowledge cutoff is that date; events after it can only be guessed.
  • Decoding randomness: sampling at high temperature can pick unlikely, wrong tokens (Decoding: Temperature, Top-k and Top-p). Lowering temperature reduces some errors but does not fix confident ones.

The scoring rule decides whether guessing pays

Suppose the model is pp confident in its best answer. Under the usual grading (right =+1= +1, wrong =0= 0, abstain =0= 0), the expected score of answering is pp, which is never worse than abstaining. So a score-maximising model should always answer.

Now penalise wrong answers by kk points. Answering is worth p⋅1−(1−p)⋅kp \cdot 1 - (1-p) \cdot k, and abstaining is worth 0. Answering only pays when

p>k1+kp > \frac{k}{1 + k}

Worked example. A model is 20% confident. Under ordinary grading, answering is worth +0.2+0.2 in expectation, so it should guess. With a penalty k=1k = 1, answering is worth 0.2−0.8=−0.60.2 - 0.8 = -0.6: it should say "I don't know". With k=1k = 1 the break-even confidence is 50%; with k=3k = 3 it is 75%. Changing the scoring changes the behaviour that training and evaluation reward. Kalai and colleagues proposed exactly this for benchmarks: state a confidence target in the instructions and penalise wrong answers accordingly.

Calibration: does the model know what it knows?

A model is well calibrated if, among all the answers it gives with 70% confidence, about 70% are correct. Calibration makes abstention possible: if confidence is meaningful, you can refuse to answer below a threshold.

The usual summary is the expected calibration error (ECE): group predictions into confidence bins, and take the average gap between each bin's confidence and its actual accuracy, weighted by how many predictions fall in the bin:

ECE=∑bnbN ∣ confidenceb−accuracyb ∣\text{ECE} = \sum_{b} \frac{n_b}{N}\, \big|\, \text{confidence}_b - \text{accuracy}_b \,\big|
0.0 0.0 0.2 0.2 0.4 0.4 0.6 0.6 0.8 0.8 1.0 1.0 stated confidence actual accuracy perfect calibration overconfident model blue: share of answers that were actually right in each confidence bin red: the gap to the diagonal, confidence the model did not earn mean confidence 0.66 accuracy 0.58 expected calibration error 0.091
Fig. 1 A reliability diagram for a simulated overconfident model. Each bar is the actual accuracy of answers given within a confidence range; the diagonal is perfect calibration. Bars below the diagonal mean the model is more confident than it should be. Computed with the code in this chapter.

What do we know about real models? Anthropic's "Language Models (Mostly) Know What They Know" (Kadavath et al., 2022) found large pretrained models fairly well calibrated on multiple-choice questions, and that they could be trained to predict whether their own answers were correct. The GPT-4 technical report (2023) showed the pretrained model was well calibrated on MMLU and that post-training made it noticeably less calibrated. Calibration of the token probabilities on multiple-choice questions does not automatically carry over to the confidence a chat model states in words in a long answer, which is often poorly calibrated.

Reducing the damage

No single technique eliminates hallucinations. In practice systems stack several layers:

question user asks retrieve search your documents generate answer only from sources; cite them; may say “not found” verify check each claim and quote against the sources deliver answer + sources, human review if stakes are high unsupported claim → revise, or answer “I don’t know” Each layer catches some errors the others miss no single layer is enough: retrieval can miss, models can ignore sources, verifiers can err
Fig. 2 Layers of defence against hallucination in an application. Retrieval grounds the answer in real documents; the model is instructed to cite and to abstain when the sources don't cover the question; a verification step checks claims against the sources; and a human reviews high-stakes outputs.
  1. Grounding with retrieval. Grounding means tying the answer to provided sources. Retrieve relevant documents and put them in the prompt (Retrieval-Augmented Generation), and instruct the model to answer only from them. This converts many factuality problems into faithfulness problems, which are easier to check.
  2. Citations. Ask for a citation for each claim, ideally quoting the supporting passage. Then verify that each quote really exists in the source; models can hallucinate citations too.
  3. Permission to abstain. Say explicitly that "I don't know" or "the documents don't say" is an acceptable answer. Abstention is underused, and models trained or prompted to use it hallucinate less.
  4. Tools. Let the model look things up (search, databases, a calculator, code execution) instead of recalling them (Tool Use and Function Calling).
  5. Self-consistency checks. Sample several answers; if they disagree on a fact, that fact is suspect. SelfCheckGPT (2023) turned this into a hallucination detector that needs no external knowledge.
  6. Verification passes. A second step (or second model) extracts the claims in an answer and checks each against the sources or the web.
  7. Human review where errors are costly, with the sources shown alongside the answer.

Training-side improvements help too: rewarding abstention, penalising confident errors in preference data, and training on verified facts. Measured hallucination rates on factual benchmarks have fallen substantially across model generations, and reasoning models that check their work tend to do better on some factual tasks, though not uniformly.

Measuring it

Common evaluations include TruthfulQA (2021: questions where the popular answer is a misconception), SimpleQA (OpenAI, 2024: short fact-seeking questions with single verifiable answers, scored as correct, incorrect or not attempted), FActScore (2023: breaks long biographies into atomic facts and checks each) and faithfulness benchmarks for summarisation and RAG. For your own application, the most useful measure is a test set of real questions with known answers and known unanswerable questions, where the right response is to abstain (Evaluating LLM Applications).

In code

A simulated model answers 1,000 questions with a stated confidence, but it is overconfident: its true chance of being right is only 85% of what it claims. We measure calibration, then see how abstaining below a threshold changes the score under different penalties for wrong answers.

import numpy as np
rng = np.random.default_rng(0)

conf = rng.uniform(0.3, 1.0, 1000)                      # stated confidence
p_true = 0.85 * conf                                    # actual chance of being right
correct = rng.random(1000) < p_true

def ece(conf, correct, bins=10):
    """Expected calibration error: average |confidence - accuracy| across bins."""
    edges = np.linspace(0, 1, bins + 1)
    total = 0.0
    for lo, hi in zip(edges[:-1], edges[1:]):
        m = (conf > lo) & (conf <= hi)
        if m.any():
            total += m.mean() * abs(conf[m].mean() - correct[m].mean())
    return total

print(f"accuracy {correct.mean():.2f}, mean confidence {conf.mean():.2f}, ECE {ece(conf, correct):.3f}")

# Abstain below a threshold. Score: +1 right, -penalty wrong, 0 for "I don't know".
print("threshold  answered  accuracy  score(pen=0)  score(pen=1)  score(pen=3)")
for t in [0.0, 0.5, 0.7, 0.9]:
    ans = conf >= t
    right, wrong = (correct & ans).sum(), (~correct & ans).sum()
    scores = [(right - pen * wrong) / 1000 for pen in (0, 1, 3)]
    print(f"   {t:.1f}       {ans.mean():.2f}      {correct[ans].mean():.2f}"
          f"        {scores[0]:+.3f}        {scores[1]:+.3f}        {scores[2]:+.3f}")

# accuracy 0.58, mean confidence 0.66, ECE 0.091
# threshold  answered  accuracy  score(pen=0)  score(pen=1)  score(pen=3)
#    0.0       1.00      0.58        +0.577        +0.154        -0.692
#    0.5       0.74      0.64        +0.478        +0.214        -0.314
#    0.7       0.46      0.72        +0.328        +0.201        -0.053
#    0.9       0.14      0.84        +0.119        +0.096        +0.050

Read the table column by column. With no penalty for wrong answers, answering everything wins (+0.577): this is the "always guess" incentive. With a penalty of 1, abstaining below 50% confidence is best. With a penalty of 3, the model should answer only when very sure, and answering everything gives a large negative score. The accuracy column shows the trade-off you control in an application: fewer answers, but more of them right.

Common pitfalls

  • Trusting fluency. Confident, well-written, specific text (names, numbers, citations) is not evidence of truth. Specific details are where hallucinations hide.
  • Assuming RAG solves it. With retrieval, models can still ignore the documents, misread them, or fill gaps from memory. Measure faithfulness, not just retrieval quality.
  • Not allowing "I don't know". If your prompt or evaluation punishes abstaining, you are training or selecting for guessing.
  • Asking the model to grade itself without evidence. "Are you sure?" can flip correct answers to wrong ones as easily as the reverse. Verify against sources.
  • Ignoring the knowledge cutoff. Questions about recent events, prices, versions and laws need retrieval or tools.

Watch out Never publish or act on model-generated citations, quotations, legal references, medical doses or statistics without checking the original source. The cost of a fabricated citation lands on you, not on the model.

Where it leads

A bit of history

The term "hallucination" was used in neural machine translation and image captioning by the late 2010s, for systems that produced fluent output unrelated to their input. Studies of abstractive summarisation around 2020 (for example Maynez et al., "On Faithfulness and Factuality in Abstractive Summarization") found that a large share of model summaries contained information not supported by the source document. Ji and colleagues' 2022 survey organised the field's definitions and methods.

With ChatGPT's launch in November 2022, hallucination became a public concern, and incidents such as the fabricated legal citations in Mata v. Avianca (2023) made the risk concrete. Research since has focused on calibration (Kadavath et al., 2022), detection (SelfCheckGPT, 2023), grounding through retrieval, and incentives: OpenAI's 2025 paper argued that hallucinations persist largely because training and benchmarks reward guessing, and that changing the scoring is part of the cure.

Try it

  1. Using p>k/(1+k)p > k/(1+k), what penalty kk makes a model answer only when it is at least 90% confident?
  2. In the code, make the model well calibrated (p_true = conf). How does the ECE change, and how does the best threshold for penalty 1 change?
  3. Ask a chat model for the publication year and journal of three papers you know well, and of one paper you invent. Does it admit the invented one doesn't exist? Try again with "If you are not sure, say so."

Hint for 1: solve k/(1+k)=0.9k/(1+k) = 0.9.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why does a model confidently give a wrong birthday for an obscure person?

  2. A summary adds a true claim that isn't in the source document. What kind of failure is this?

  3. Wrong answers cost 1 point, right answers earn 1 and "I don't know" scores 0. Above what confidence should a model answer?

  4. Your company's support bot invents refund policies. Which approach does the chapter recommend first?

  5. Among answers a model gives with 70% confidence, only 50% are correct. What does this tell you?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Why Language Models Hallucinate

Kalai, Nachum, Vempala & Zhang (OpenAI) · 2025 · Intermediate · Free

Argues hallucinations arise naturally from pretraining statistics and persist because benchmarks reward guessing over saying 'I don't know'.

Paper

Language Models (Mostly) Know What They Know

Kadavath et al. (Anthropic) · 2022 · Advanced · Free

Large models are fairly well calibrated on multiple-choice questions and can be trained to estimate the probability that their own answer is correct.

Book

AI Engineering

Chip Huyen · 2025 · Intermediate · Paid

Building applications on foundation models: evaluation, prompting, RAG, agents, fine-tuning, inference optimisation.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/hallucination.md