# Hallucination and Calibration: Why Models Sound Sure and Are Wrong

> Hallucination is fluent output that contradicts the facts or the sources a model was given. This page covers two taxonomies, the floor set by facts seen only once, why binary grading rewards guessing, and three runnable simulations of calibration, temperature scaling and abstaining.

- URL: https://dmxsf.com/en/wiki/safety/hallucination-and-calibration/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-21
- Tags: Safety & security, Alignment, Evaluation

## After this page you will be able to

- Distinguish factuality from faithfulness hallucination (and intrinsic from extrinsic), and list the main sources of hallucination with the mitigation that fits each.
- Explain why the singleton rate (the Good–Turing missing mass) is a floor on the error rate for facts seen only once, and verify in a simulation that it matches the share of unseen prompts.
- Show why binary grading rewards guessing, and derive that when a wrong answer costs t/(1−t) points, answering pays only if confidence exceeds t.
- Read a reliability diagram, compute ECE, and say what temperature scaling can change (the confidence values) and what it cannot (the predicted class, hence accuracy).
- List the layered defenses (retrieval and citations, abstention training, factuality preference optimization, consistency checks) and the limits of each.

Hallucination is output that reads fluently but contradicts the facts or the sources the model was given. It is not one bug but the sum of several mechanisms: some facts appear only once in the training data, so the model has nothing to check them against; the training objective is to continue text, not to verify facts; and the most common benchmarks give a wrong answer and “I don’t know” the same zero, so guessing never costs anything. **Calibration** is the yardstick for whether the model’s tone can be trusted: of the answers it gives with 90% confidence, are about 90% actually right?

The previous page of this chapter covered how an attacker gets a model into trouble ([prompt injection and jailbreaks](https://dmxsf.com/en/wiki/safety/prompt-injection-and-jailbreaks/)). This page covers how a model gets into trouble on its own. It classifies hallucinations, traces where they come from, and then turns three claims into numbers you can change, using three simulations in one script: the error floor that facts seen only once impose (Experiment 1), how grading rules reward guessing (Experiment 2), and overconfidence with temperature scaling (Experiment 3). The experiments are toys built to illustrate results from the papers, not evaluations of real models; every statement about real models comes from a paper cited on the page.

## What hallucination is

The word is used differently in different papers, so start with two common taxonomies.

| Type | Source | Definition | Example |
| --- | --- | --- | --- |
| Factuality hallucination | Huang et al., 2023 | The content conflicts with verifiable real-world facts | Stating a scholar’s birthday wrongly |
| Faithfulness hallucination | Huang et al., 2023 | The content departs from the user’s input (instruction, context) or contradicts itself | A summary contains a number the source does not |
| Intrinsic hallucination | Ji et al., 2022 | The output contradicts the source | The source says a vaccine was approved in 2019, the summary says 2021 |
| Extrinsic hallucination | Ji et al., 2022 | The output cannot be verified from the source: it is neither supported nor contradicted | The summary adds “clinical trials have started”, which the source never says |

The two taxonomies cut the same phenomenon from different angles, and whether there is a source decides which one to use. Closed-book question answering has no source, so it only has factuality problems; summarization, document QA and retrieval-augmented generation have a source and meet both kinds. An extrinsic hallucination is not necessarily wrong: Ji et al. point out that it can be factually correct outside knowledge and can even add useful background, but because it cannot be verified, most of the literature still treats it with caution.

## Where hallucinations come from

There is no single cause. The table lists the main sources and the matching mitigation; the next three sections take the three least intuitive rows (the statistical floor, grading, calibration) and run experiments on them.

| Source | Mechanism | Typical symptom | Main mitigation |
| --- | --- | --- | --- |
| A fact seen only once | Nothing in the data separates true from false, so the model can only guess from the distribution | Birthdays of obscure people, titles and authors of papers | Retrieval, abstention (Experiment 1) |
| Errors and misconceptions in the data | The model faithfully imitates mistakes and popular misconceptions in its training text | “Misconception” questions such as those in TruthfulQA | Data cleaning, preference optimization |
| New facts forced in by fine-tuning | Supervised fine-tuning on facts the model did not know teaches it to give an answer even when it is unsure | The more new facts it absorbs, the higher its tendency to hallucinate | Match fine-tuning data to what the model already knows; abstention data |
| Grading that rewards guessing | A wrong answer and an abstention both score zero, so abstaining never pays | Models near the top of a leaderboard guess boldly | Explicit confidence targets (Experiment 2) |
| Problems in the context | Retrieved passages are wrong or irrelevant, or information in the middle of a long context goes unused, see [Lost in the Middle](https://dmxsf.com/en/blog/lost-in-the-middle/) | A summary adds material, ignores the source | Citations and faithfulness evaluation, see [RAG](https://dmxsf.com/en/wiki/applications/rag/) |
| Reasoning and arithmetic errors | What is missing is not a fact but the ability to get every step right | Miscounted letters, multi-step arithmetic errors | Tool calls, reasoning models, test-time compute |

Sampling temperature is often blamed, but it only amplifies: temperature changes what we draw from the model’s distribution, not the distribution itself. Greedy decoding (temperature 0) takes the most likely continuation, and if that is wrong the model is wrong every time; raising the temperature makes low-probability mistakes easier to draw, and still cannot make the model know a fact it never learned (see [decoding and sampling](https://dmxsf.com/en/wiki/inference/decoding-and-sampling/)).

## A statistical floor: facts seen only once

Start with the least controversial kind: **arbitrary facts** that cannot be derived from the training data, such as a person’s birthday. An obscure person’s birthday may appear exactly once in the corpus (say, in an obituary). Asked later about another equally obscure person who never appeared, the model has no clue that separates the 365 possible dates.

Kalai and Vempala (2024) and Kalai et al. (2025) turned this into a theorem. The statistic comes from Alan Turing’s missing-mass estimate (Good–Turing): to estimate the probability that the next sample is something never seen, use the fraction of samples whose item appeared **exactly once**. Call that fraction the **singleton rate**:

$$
\mathrm{sr}=\frac{n_1}{N}
$$

$N$ is the number of training samples and $n_1$ is the number of prompts (for example “when was so-and-so born?”) that appear exactly once. In the “arbitrary facts” setting the paper proves that any algorithm’s model satisfies, with probability at least 99%,

$$
\mathrm{err}\;\ge\;\mathrm{sr}-\frac{2}{\min_c|\mathcal E_c|}-\frac{35+6\ln N}{\sqrt N}-\delta
$$

where $\mathrm{err}$ is the model’s error rate on fresh prompts, $|\mathcal E_c|$ is the number of wrong answers for prompt $c$ (364 for birthdays), and $\delta$ measures the model’s miscalibration (a calibrated model has $\delta=0$). The two subtracted terms are small and vanish as $N$ and $|\mathcal E_c|$ grow. The other direction holds too: there is a calibrated algorithm whose error rate is at most $\mathrm{sr}-\mathrm{sr}/(\max_c|\mathcal E_c|+1)+13/\sqrt N$. Put together: **a calibrated pretrained model hallucinates on this kind of fact at about the singleton rate.**

The result has a clear scope.

- **Arbitrary facts only.** Each prompt has exactly one correct answer and one way to write it, facts have no exploitable regularity, and the training data contain no errors. The paper itself notes that there is no statistical reason for pretraining to err on facts that appear many times (such as references to books and papers) or on systematic facts (such as arithmetic), and that different architectures and learning algorithms may mitigate the latter two.
- **Not “hallucination is inevitable”.** A system that answers only what is in a database and says “I don’t know” to everything else need not make errors; the price is that it gives up answering. **Errors can be turned into abstentions, but they do not vanish.**
- **Calibration is the premise.** The paper treats pretraining errors as a natural consequence of cross-entropy training and cites evidence that pretrained models are often calibrated while post-trained models can deviate. That is why the next section covers grading and the one after covers calibration.

### Experiment 1: the singleton rate in a simulation

The simulation shrinks the theorem to its smallest form. The corpus can mention 50,000 people, each with one fixed birthday. The probability of mentioning each person follows a Zipf distribution $\mu(c)\propto c^{-s}$ (smaller $s$ means a heavier tail). The training set is $N$ (person, birthday) pairs, all correct. The “model” is a pure memorizer: for a person it has seen it copies the answer, and for a person it has not seen it guesses among 365 days. The script computes three numbers: the singleton rate `sr` of the training set; the probability mass of people never seen, `missing` (only a simulation can compute it, on a real corpus it is unknowable); and the model’s error rate on fresh questions, `guess_err`. Each configuration averages 10 seeds, and sampling the corpus, sampling the test questions and guessing birthdays each use their own independent seed.

```python
import numpy as np

M, DAYS = 50_000, 365  # people the corpus may mention; possible birthdays
rank = np.arange(1, M + 1)

def one_run(s, n, seed):
    """Train a memorizer on n (person, birthday) pairs, test on fresh ones."""
    mu = rank ** -s
    mu /= mu.sum()  # how often each person is mentioned
    ids = np.random.default_rng([seed, 0]).choice(M, size=n, p=mu)
    counts = np.bincount(ids, minlength=M)
    sr = (counts == 1).sum() / n  # singleton rate
    missing = mu[counts == 0].sum()  # probability mass of unseen people
    test = np.random.default_rng([seed, 1]).choice(M, size=20_000, p=mu)
    unseen = counts[test] == 0
    hit = np.random.default_rng([seed, 2]).integers(DAYS, size=20_000) == 0
    err = (unseen & ~hit).mean()  # seen: copy the answer; unseen: guess
    return sr, missing, err

gaps, mean_gaps = [], []
print("   s        N     sr  missing  guess_err")
for s in (0.8, 1.0, 1.2):
    for n in (1_000, 10_000, 100_000):
        r = np.array([one_run(s, n, k) for k in range(10)])
        gaps.append(np.abs(r[:, 0] - r[:, 1]).max())
        sr, missing, err = r.mean(0)
        mean_gaps.append(abs(sr - missing))
        print(f"{s:4.1f} {n:8d} {sr:6.3f} {missing:8.3f} {err:10.3f}")
```

Output:

```text
   s        N     sr  missing  guess_err
 0.8     1000  0.761    0.764      0.763
 0.8    10000  0.506    0.502      0.502
 0.8   100000  0.150    0.149      0.149
 1.0     1000  0.509    0.505      0.505
 1.0    10000  0.307    0.305      0.305
 1.0   100000  0.116    0.117      0.117
 1.2     1000  0.267    0.269      0.268
 1.2    10000  0.147    0.146      0.146
 1.2   100000  0.064    0.064      0.064
```

How far apart are `sr` and `missing`?

```python
print(f"largest |sr - missing|: {max(mean_gaps):.3f} in the 10-run means,"
      f" {max(gaps):.3f} in a single run")
```

```text
largest |sr - missing|: 0.004 in the 10-run means, 0.037 in a single run
```

- **`sr` estimates exactly the part never seen.** In every configuration `sr` and `missing` are nearly equal, and the first can be computed without knowing the true distribution. Averaged over ten runs they differ by at most 0.004; a single run can differ by as much as 0.037, so the fewer the samples, the noisier one run is.
- **For a memorizer, the error rate is `missing`.** `guess_err` is slightly below `missing` only because a blind guess has a 1/365 chance of being right (0.763 against 0.764). Replace the guess with “I don’t know” and the error rate becomes 0 while the abstention rate is exactly `missing`: errors turn into abstentions and the total is unchanged.
- **More data lowers the floor slowly.** At $s=1.0$, growing $N$ tenfold from 10,000 to 100,000 only takes `sr` from 0.307 to 0.116; with a heavier tail ($s=0.8$) and $N=100{,}000$ it is still 0.150.
- **This is a toy.** Real prompt distributions are far messier than a Zipf law, and real models are not memorizers: they infer from context and from related facts. These numbers are not hallucination rates of real models. The simulation shows one thing: for facts with no pattern, the part never seen can only be guessed, and its share can be estimated before training from the singleton rate.

Miao and Kearns (2025) ran an empirical study on n-gram models and fine-tuned encoder-decoder Transformers. They generated training data from Pareto distributions of different shapes to control the monofact rate (their name for the singleton rate) and confirmed that it correlates positively with hallucination. They also found that repeating just 5% of the training examples (selective upweighting) cut hallucination by up to 40% with accuracy unchanged, at the price of deliberately injected miscalibration, which corresponds to the $\delta$ in the bound above, so it does not contradict it; it also suggests that a one-size-fits-all deduplication policy may not always be optimal.

## How grading rewards guessing

Pretraining leaves errors behind, and post-training is supposed to clean them up by teaching the model to say “I don’t know” when unsure. But Kalai et al. (2025) point out that the mainstream benchmarks punish exactly that behavior. Suppose that on some question the model’s confidence in its answer (its probability of being right) is $c$.

- Under **binary grading** (1 point for a right answer, 0 for a wrong answer or an abstention), the expected score of answering is $c\ge 0$ and abstaining scores 0, so **abstaining is never optimal** (Observation 1 in the paper; the proof is one line). However unsure the model is, it should guess.
- Under **grading with a penalty**: $+1$ for right, $-\lambda$ for wrong, 0 for abstaining. The expected score of answering is $c-(1-c)\lambda$, which is positive if and only if

$$
c>\frac{\lambda}{1+\lambda}=t,\qquad \lambda=\frac{t}{1-t}
$$

So if the question states “answer only if you are more than $t$ confident; a wrong answer costs $t/(1-t)$ points”, the optimal policy is to answer when confidence exceeds $t$ and abstain otherwise.

| Target $t$ | Penalty $t/(1-t)$ | Meaning |
| --- | --- | --- |
| 0 | 0 | Plain binary grading: guess freely |
| 0.5 | 1 | A wrong answer cancels a right one; answer if more than half sure |
| 0.75 | 3 | Do not answer unless 75% sure |
| 0.9 | 9 | Do not answer unless 90% sure |

Section 4.2 of the paper (the HTML rendering of arXiv v1) writes the penalty for $t=0.75$ as 2, but by its own formula it is 3; the table follows the formula, and so do the experiment and exercises below. The design is not new: the paper lists the Indian JEE, NEET and GATE exams, the AMC contests of the Mathematical Association of America, and earlier versions of the SAT, AP and GRE as exams that penalize wrong answers. The paper also calls the behavior “answer only above the target confidence $t$” **behavioral calibration**: the model is not asked to report a probability, only to behave optimally for every $t$, which can be audited by comparing accuracy and error rates across thresholds.

### Experiment 2: one model, two behaviors, two grading rules

Give a model a confidence $c$ on each of 200,000 questions, drawn from Beta(0.6, 0.9) (mean 0.4; illustrative values, not data from any real model), and **calibrated by construction**: when it says $c$, it really is right with probability $c$. Let it take four behaviors: answer only if $c>\theta$ (with $\theta$ equal to 0, 0.5, 0.75, 0.9), and score each under four grading rules ($t$ equal to 0, 0.5, 0.75, 0.9). Expected scores are computed directly, so there is no sampling noise.

```python
conf = np.random.default_rng(7).beta(0.6, 0.9, size=200_000)
# conf = P(correct | the model answers); calibrated by construction
THETAS = (0.0, 0.5, 0.75, 0.9)  # answer only if conf > theta

def score(theta, t):
    """Expected score of 'answer iff conf > theta' when a wrong answer
    costs t / (1 - t) points (t = 0 is plain 0-1 grading)."""
    answer = conf > theta
    penalty = t / (1 - t)
    return ((conf - penalty * (1 - conf)) * answer).mean()

print("grading t  penalty |  theta=0.00    0.50    0.75    0.90 | best")
for t in THETAS:
    row = [score(th, t) for th in THETAS]
    print(f"{t:9.2f} {t / (1 - t):8.1f} | "
          + "".join(f"{v:8.3f}" for v in row)
          + f" | {THETAS[int(np.argmax(row))]}")
```

Output:

```text
grading t  penalty |  theta=0.00    0.50    0.75    0.90 | best
     0.00      0.0 |    0.400   0.281   0.164   0.075 | 0.0
     0.50      1.0 |   -0.200   0.187   0.142   0.072 | 0.5
     0.75      3.0 |   -1.401   0.001   0.096   0.064 | 0.75
     0.90      9.0 |   -5.002  -0.558  -0.039   0.041 | 0.9
```

Now the accuracy, error rate and abstention rate of each behavior:

```python
print("theta  accuracy  error  abstain  acc_if_answered")
for th in THETAS:
    ans = conf > th
    acc, err = (conf * ans).mean(), ((1 - conf) * ans).mean()
    print(f"{th:5.2f} {acc:9.3f} {err:6.3f} {1 - ans.mean():8.3f}"
          f" {acc / ans.mean():16.3f}")
```

```text
theta  accuracy  error  abstain  acc_if_answered
 0.00     0.400  0.600    0.000            0.400
 0.50     0.281  0.093    0.626            0.751
 0.75     0.164  0.023    0.813            0.879
 0.90     0.075  0.004    0.921            0.952
```

- **In every row the best column is exactly $\theta=t$** (the last column, `best`). This confirms the derivation: the $t$ of the grading rule sets the threshold to use.
- **Under binary grading (the first row) the boldest behavior ranks first:** $\theta=0$ scores 0.400 and $\theta=0.9$ only 0.075. Yet in the second table the first has an error rate of 0.600 and the second only 0.004, and on the questions it does answer the second is right 0.952 of the time. The same model, behaving more honestly, drops from first to last on a binary leaderboard.
- **Grading with a penalty turns the ranking upside down:** in the $t=0.9$ row, $\theta=0$ scores -5.002 and $\theta=0.9$ scores 0.041.
- **Implication:** if training or model selection looks at binary grading, the behavior being rewarded is the first column. That is the core argument of Kalai et al.: hallucination survives post-training not only because of what models can do but because of what grading rewards.

In the experiment $c$ is the model’s true probability of being right; a real model does not know its $c$ and can only give an estimate. Whether that estimate is any good is the question of the next section.

## Calibration: can you trust the tone?

Suppose a model gives an answer together with a confidence $\hat p$. If

$$
P(\text{correct}\mid \hat p=p)=p\quad\text{for every }p
$$

the model is **calibrated**. In practice, samples are grouped by $\hat p$ into $M$ bins and shown in a **reliability diagram**: the horizontal axis is the mean confidence in the bin and the vertical axis the actual accuracy in the bin; a calibrated model hugs the diagonal, below the diagonal means overconfident, above means underconfident. The **expected calibration error** (ECE) summarizes it:

$$
\mathrm{ECE}=\sum_{m=1}^{M}\frac{|B_m|}{n}\,\bigl|\mathrm{acc}(B_m)-\mathrm{conf}(B_m)\bigr|
$$

$B_m$ holds the samples in bin $m$, $\mathrm{acc}$ is the accuracy in the bin and $\mathrm{conf}$ is the mean confidence in the bin. Guo et al. (2017) used 15 equal-width bins and so does the experiment below; ECE depends on the binning and the sample size, so numbers from different papers are not directly comparable. The preference probability $\sigma(\Delta r)$ that a reward model outputs is also a probability that needs calibrating and can be measured with ECE too; the [Reward Models](https://dmxsf.com/en/wiki/post-training/reward-models/) page has the experiment.

### Where a language model’s confidence comes from

| Source | How | What is known |
| --- | --- | --- |
| Token probabilities | Read the probability of the answer tokens (or of the four options A, B, C, D in a multiple-choice question) | Pretrained models are often well calibrated; the GPT-4 technical report shows on an MMLU subset that post-training clearly weakens calibration (its Figure 8) |
| Verbalized confidence | Ask the model to write how sure it is (“90%” or “very sure”) | Lin et al. (2022) fine-tuned GPT-3 to produce calibrated verbalized probabilities; Tian et al. (2023) found that for RLHF models such as ChatGPT, GPT-4 and Claude, verbalized confidence is usually better calibrated than token probabilities on TriviaQA, SciQ and TruthfulQA, often cutting ECE by about half in relative terms |
| Self-evaluation | Have the model answer first and then estimate the probability that its answer is true, P(True); or predict before answering whether it knows, P(IK) | Kadavath et al. (2022): larger models are well calibrated on multiple-choice and true/false questions in a suitable format, and P(True) performs and calibrates well; P(IK) is less well calibrated on new tasks |
| Consistency | Sample the same question several times and see whether the answers agree (SelfCheckGPT; semantic entropy first groups answers with the same meaning and then computes entropy) | Needs no external knowledge and no internal probabilities, so it works on black boxes; it cannot catch a model that gives the same wrong answer every time |

### Experiment 3: an overconfident classifier and temperature scaling

With no real large model at hand, the experiment uses a simulated 5-way classifier. For each question the true logits $z$ are drawn from $\mathcal N(0,1.6^2)$ and the label is drawn from $\mathrm{softmax}(z)$, so $\mathrm{softmax}(z)$ is the calibrated “truth”. Multiplying the logits by 2.5 gives an overconfident “deployed model”: the predicted classes and the accuracy do not change, but the confidences are pushed toward 1. This is the simplest toy version of “post-training weakens calibration”, with a single scalar of miscalibration; real miscalibration is messier and varies with question type and topic.

**Temperature scaling** is the post-processing recommended by Guo et al. (2017): divide the logits by a scalar $T$ before the softmax,

$$
\hat p=\mathrm{softmax}(z/T)
$$

with $T$ chosen on a held-out set to minimize the negative log-likelihood (NLL). Below, $T$ is fitted on the first half of the data (30,000 questions) and every metric is evaluated on the second half; AUROC measures how well the maximum probability separates right answers from wrong ones.

```python
K, N = 5, 60_000

def softmax(z):
    e = np.exp(z - z.max(1, keepdims=True))
    return e / e.sum(1, keepdims=True)

def ece(p, y, bins=15):
    conf, ok = p.max(1), p.argmax(1) == y
    idx = np.minimum((conf * bins).astype(int), bins - 1)
    return sum((idx == b).mean() * abs(ok[idx == b].mean()
                                       - conf[idx == b].mean())
               for b in range(bins) if (idx == b).any())

def nll(z, y):
    return -np.log(softmax(z)[np.arange(len(y)), y]).mean()

def auroc(score, ok):
    rk = score.argsort().argsort() + 1.0
    n1, n0 = ok.sum(), (~ok).sum()
    return (rk[ok].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)

def fit_temperature(z, y):
    lo, hi = np.log(0.05), np.log(20.0)  # golden-section on log T
    g = (np.sqrt(5) - 1) / 2
    for _ in range(60):
        a, b = hi - g * (hi - lo), lo + g * (hi - lo)
        if nll(z / np.exp(a), y) < nll(z / np.exp(b), y):
            hi = b
        else:
            lo = a
    return float(np.exp((lo + hi) / 2))

z_true = np.random.default_rng(11).normal(0, 1.6, size=(N, K))
u = np.random.default_rng(12).random((N, 1))
y = (softmax(z_true).cumsum(1) > u).argmax(1)  # labels drawn from p_true
cal, test = slice(0, N // 2), slice(N // 2, N)  # fit T on one half only
T = fit_temperature(2.5 * z_true[cal], y[cal])
print(f"fitted T on the calibration half: {T:.3f} (true factor: 2.5)")
print("model                    ECE    NLL    acc  AUROC")
for name, logits in (("calibrated (x1)", z_true),
                     ("overconfident (x2.5)", 2.5 * z_true),
                     ("overconfident + T", 2.5 * z_true / T)):
    p, yt = softmax(logits[test]), y[test]
    ok = p.argmax(1) == yt
    print(f"{name:21s} {ece(p, yt):6.3f} {nll(logits[test], yt):6.3f}"
          f" {ok.mean():6.3f} {auroc(p.max(1), ok):6.3f}")
```

Output:

```text
fitted T on the calibration half: 2.461 (true factor: 2.5)
model                    ECE    NLL    acc  AUROC
calibrated (x1)        0.004  1.041  0.588  0.705
overconfident (x2.5)   0.216  1.396  0.588  0.701
overconfident + T      0.003  1.040  0.588  0.705
```

- **The miscalibration is real:** the overconfident model has ECE 0.216 and NLL 1.396; the calibrated model has 0.004 and 1.041.
- **Temperature scaling fixes the numbers:** the fitted $T=2.461$ is close to the true factor 2.5; after scaling, ECE drops to 0.003 and NLL is 1.040, the same as the calibrated model.
- **The predicted classes do not change, so accuracy does not either** (0.588). The ranking is nearly but not exactly unchanged: AUROC moves from 0.701 to 0.705. For two classes the maximum probability is monotone in $T$ and the ranking is exactly preserved; with more classes it changes at different speeds for different questions, so the ranking can shift slightly.

Now where exactly the overconfident model goes wrong:

```python
yt = y[test]
p_over, p_cal = softmax(2.5 * z_true[test]), softmax(z_true[test])
conf_o, ok_o = p_over.max(1), p_over.argmax(1) == yt
conf_c, ok_c = p_cal.max(1), p_cal.argmax(1) == yt
bin_o = np.minimum((conf_o * 10).astype(int), 9)
bin_c = np.minimum((conf_c * 10).astype(int), 9)
print("               overconfident (x2.5)    |    calibrated (x1)")
print("confidence bin  share  conf    acc    |  share  conf    acc")
for b in range(2, 10):
    m, n = bin_o == b, bin_c == b
    print(f"[{b / 10:.1f}, {(b + 1) / 10:.1f})   {m.mean():6.3f}"
          f" {conf_o[m].mean():6.3f} {ok_o[m].mean():6.3f}    |"
          f" {n.mean():6.3f} {conf_c[n].mean():6.3f} {ok_c[n].mean():6.3f}")
```

Output:

```text
               overconfident (x2.5)    |    calibrated (x1)
confidence bin  share  conf    acc    |  share  conf    acc
[0.2, 0.3)    0.001  0.285  0.286    |  0.016  0.280  0.286
[0.3, 0.4)    0.017  0.368  0.295    |  0.134  0.359  0.357
[0.4, 0.5)    0.058  0.459  0.348    |  0.223  0.451  0.454
[0.5, 0.6)    0.110  0.550  0.388    |  0.198  0.548  0.547
[0.6, 0.7)    0.108  0.651  0.449    |  0.160  0.648  0.657
[0.7, 0.8)    0.121  0.751  0.486    |  0.128  0.749  0.756
[0.8, 0.9)    0.153  0.853  0.566    |  0.094  0.847  0.850
[0.9, 1.0)    0.432  0.969  0.753    |  0.046  0.937  0.938
```

*Figure: Simulated 5-way classifier, 30,000 test questions (data from the reliab output above). Left: points below the diagonal mean the stated confidence exceeds the actual accuracy. Right: the overconfident model puts 43.2% of its answers in the top bin; the rule "answer only if confidence is at least 0.9" lets all of them through, and only 75.3% are correct.*

In the top bin [0.9, 1.0) the overconfident model claims a mean confidence of 0.969 but is right only 0.753 of the time, and a share of 0.432 of all its answers is crowded into this bin; the calibrated model has only 0.046 of its answers there, claiming 0.937 and getting 0.938.

Finally, what this means for abstaining:

```python
print("keep the most confident  overconfident  calibrated")
for cov in (1.0, 0.8, 0.6, 0.4, 0.2):
    k = int(cov * len(yt))
    a = ok_o[np.argsort(-conf_o)[:k]].mean()
    c = ok_c[np.argsort(-conf_c)[:k]].mean()
    print(f"{cov:23.0%} {a:14.3f} {c:11.3f}")
print("answer iff stated confidence >= 0.9: coverage, accuracy")
for name, cf, ok in (("overconfident", conf_o, ok_o),
                     ("calibrated   ", conf_c, ok_c)):
    m = cf >= 0.9
    print(f"{name} {m.mean():6.3f} {ok[m].mean():8.3f}")
```

Output:

```text
keep the most confident  overconfident  calibrated
                   100%          0.588       0.588
                    80%          0.642       0.642
                    60%          0.700       0.700
                    40%          0.766       0.769
                    20%          0.849       0.850
answer iff stated confidence >= 0.9: coverage, accuracy
overconfident  0.432    0.753
calibrated     0.046    0.938
```

- **The ranking is fine, the threshold is wrong.** “Keep the most confident 40%” gives accuracy 0.766 for the overconfident model and 0.769 for the calibrated one, almost the same: who answers first depends only on the ranking, and temperature scaling barely changes the ranking.
- **But “answer only if confidence is at least 0.9” differs enormously.** The overconfident model lets through 0.432 of the questions (`coverage`) with accuracy only 0.753; the calibrated model lets through 0.046 with accuracy 0.938. **A threshold only means something on calibrated numbers.** That is the premise that makes the explicit confidence targets of Experiment 2 usable: if the stated “I am 90% sure” is not calibrated, writing $t=0.9$ in the question stops nothing.

**Calibrated does not mean useful.** A model that says “I am 40% sure” on every question has ECE 0 if its overall accuracy happens to be 40%, and is useless: it cannot tell which questions to answer. Calibration measures whether the tone can be trusted; discrimination (AUROC, or an accuracy–coverage curve) measures whether confidence separates right from wrong. Look at both.

The widget below turns experiment 3 into a version with your own parameters: drag the miscalibration scale and watch the reliability diagram leave the diagonal while ECE grows; pull the confidences back with temperature scaling — the accuracy does not move; then try “answer only at confidence ≥ 0.9” on the overconfident and the calibrated model and see how far apart they are.

## What to do in practice

No single measure solves it; in practice the defenses are layered.

| Measure | How | What it addresses | Limits |
| --- | --- | --- | --- |
| Retrieval and citations | Put relevant material in the context and require each claim to cite its source | Missing or outdated facts; lets readers check | The model still guesses when retrieval fails; it can still be unfaithful to what it retrieved; with binary grading, guessing still pays (Kalai et al., 2025) |
| Abstention training | R-Tuning: compare the model’s parametric knowledge with the fine-tuning data, find the questions the model gets wrong, and build “refusal-aware” data from them for fine-tuning | Questions beyond what the model knows; the paper finds that refusing is a meta-skill that transfers to other tasks | Needs an estimate of what the model knows; over-refusal makes a product useless |
| Factuality preference optimization | FactTune: score the claims in long answers for factuality using a retrieval system or the model’s own confidence, build preference pairs, and train with DPO | Factual errors in open-ended long text; at 7B scale, relative to Llama-2-chat, the factual error rate falls by 58% on biographies and 40% on medical questions | Depends on the scorer; the paper tested held-out topics |
| Matching fine-tuning data to the model’s knowledge | Gekhman et al. measured the cost in a controlled study: new facts are learned more slowly, and once learned they raise the tendency to hallucinate linearly | Reduces “fine-tuning teaches the model to answer even when unsure” | Requires judging, for each example, whether the model already knows it |
| Consistency checks | Sample several times; answers that disagree are more likely hallucinations (SelfCheckGPT, semantic entropy) | No external knowledge needed; works on black boxes | The cost of repeated sampling; stable errors go undetected |
| Grading and product design | State a confidence target in the benchmark and report accuracy–coverage curves; show sources in the product and flag low-confidence answers for checking | Abstaining stops being punished; users know what to check | Needs calibrated confidence as a premise (Experiment 3) |

## Practical checklist

1. Decide first whether you face factuality or faithfulness: tasks with a source (summarization, document QA, RAG) test faithfulness, closed-book QA tests factuality.
2. Report accuracy, error rate and abstention rate together, or an accuracy–coverage curve, not just binary accuracy.
3. Measure calibration on your own task: a reliability diagram plus ECE, with the number of bins and the sample size; fit the temperature on a held-out set, never on the test set.
4. When you need abstention, let the cost of a wrong answer set the threshold: with 1 point for right, 0 for abstaining and $\lambda$ points off for wrong, $t=\lambda/(1+\lambda)$; state it in the prompt or the evaluation instructions.
5. Where facts matter, combine retrieval and citations, and keep a human check on high-risk answers.

### Common misconceptions

| Misconception | What is actually true |
| --- | --- |
| “Set the temperature to 0 and it will not hallucinate” | Temperature 0 only makes the output deterministic. If the most likely continuation is wrong, the model is wrong every time. |
| “With RAG there is no hallucination” | RAG eases missing and outdated facts, but the model still guesses when retrieval fails and can still be unfaithful to what it retrieved. |
| “Bigger models hallucinate less” | More data and scale reduce the share never seen (in Experiment 1 `sr` falls as $N$ grows), but as long as many facts appear only once the floor does not vanish. In the 2021 models tested by the TruthfulQA authors the largest were the least truthful; their explanation was that false answers are learned from the training distribution. |
| “If the model states its confidence, we know when it is right” | Verbalized confidence is often better calibrated than token probabilities (Tian et al., 2023), but it still has to be validated on your own task; uncalibrated confidence is just another tone of voice. |
| “Low ECE means the model is reliable” | A constant predictor can have ECE 0. Read ECE together with discrimination, and remember it depends on binning and sample size. |

## Summary and exercises

1. Hallucination has two taxonomies, factuality versus faithfulness (or intrinsic versus extrinsic), and whether there is a source decides which one to look at.
2. For facts with no pattern, the error rate of a calibrated pretrained model is about the singleton rate (the share of prompts seen only once); errors can be turned into abstentions but do not vanish.
3. Under binary grading abstaining is never optimal; with a penalty of $t/(1-t)$ for a wrong answer, answering pays only above confidence $t$.
4. Calibration is what gives a threshold meaning; temperature scaling fixes the confidence values without changing the predicted class; calibration and discrimination are two different things.
5. Mitigation is layered: retrieval and citations, abstention training, factuality preference optimization, consistency checks, plus better grading and product design.

### Quick self-test

**1. Which of these is a faithfulness hallucination?**

- [ ] In closed-book QA, the model gives a scholar’s birthday wrongly
- [x] Asked to summarize a news article, the model writes a summary containing a number that is not in the article
- [ ] The model gets the population of an obscure city wrong
- [ ] The sampling temperature is so high that the output turns into gibberish

> Faithfulness asks whether the output stays true to the input or context the user supplied. The first and third are factuality hallucinations checked against the real world, and the last is decoding randomness, not the kind of hallucination discussed here.

**2. A training set has 1,000 (person, birthday) samples, and 200 of the people appear only once. Which statement fits best?**

- [ ] The singleton rate is 0.02, which can be ignored
- [x] The singleton rate is 0.20: the next question names a person never seen with probability about 0.20, and a calibrated pretrained model errs on this kind of fact at about that rate, not much less
- [ ] The singleton rate is 0.80, because most people appear only once
- [ ] As long as the training data contain no errors, the error rate is 0

> $\mathrm{sr}=n_1/N=200/1000=0.20$ (see the output in the exercise answers). The paper’s bound differs only by small terms that vanish as $N$ grows, and it holds even when the training data contain no errors.

**3. The grading is +1 for right, a penalty of $t/(1-t)$ points for wrong, 0 for abstaining, with $t=0.75$. On some question the model’s confidence is 0.6. Which statement is right?**

- [ ] A wrong answer costs 3 points, the expected score of answering is +0.60, so answer
- [x] A wrong answer costs 3 points, the expected score of answering is -0.60, so abstain
- [ ] A wrong answer costs 1 point, the expected score of answering is +0.20, so answer
- [ ] Always answer, because abstaining scores 0

> The expected score is $0.6-0.4\times 3=-0.60$ (see the output in the exercise answers). Answering only pays when confidence exceeds $t=0.75$.

**4. You apply temperature scaling ($T$ fitted on a held-out set) to a multi-class classifier. Which statements are true?**

- [x] The predicted class does not change, so accuracy does not change
- [x] In this page’s experiment, ECE falls from 0.216 to 0.003
- [ ] The ranking of confidences is exactly preserved, so AUROC is identical to the last digit
- [ ] The model has learned new knowledge

> Scaling changes only the confidence values. With several classes the ranking can shift slightly: in the experiment AUROC moves from 0.701 to 0.705. It adds no knowledge: facts never seen can still only be guessed.

**5. Which statements about grading and guessing are true?**

- [x] Under binary grading the expected score of answering is never below that of abstaining, so abstaining is never optimal
- [x] In Experiment 2 the answer-everything policy $\theta=0$ scores highest under binary grading (0.400) although its error rate is 0.600
- [ ] Under grading with a penalty, the best threshold does not depend on the penalty
- [ ] Once RAG is used, the grading rule no longer affects whether the model guesses

> With a penalty the best threshold is exactly $t=\lambda/(1+\lambda)$ (in Experiment 2 the best column of every row is $\theta=t$). When retrieval fails, binary grading still rewards guessing.

### Exercises

1. **Change the parameters (Experiment 1).** (a) Set the Zipf exponent to $s=1.5$ (a more concentrated head) with $N=10{,}000$; (b) go back to $s=1.0$ and set $N$ to 1,000,000. What are `sr` and `missing`? What does this say about “more data is always better”?
2. **Read the table (Experiment 2).** In the $t=0.75$ row, why is the score of $\theta=0.5$ close to 0 (0.001)?
3. **Compute.** (a) With $t=0.9$ and confidence 0.8, what is the expected score of answering? Should the model answer? (b) If a wrong answer costs 10 points, a right one earns 1 and an abstention 0, what should the threshold $t$ be?
4. **Underconfidence.** Change the logit multiplier from 2.5 to 0.5 (underconfident). Which $T$ does temperature scaling fit? What is the ECE before scaling? What does $T$ below 1 mean?
5. **Design.** You must choose an abstention threshold for a medical Q&A product where a wrong answer is far worse than an abstention. Write your evaluation plan: which grading rule, which metrics to report, and how to check that the confidence the model gives can be trusted.

<details>
<summary>Reference answers</summary>

Run this after the script above (it uses `one_run`, `fit_temperature` and other functions defined there):

```python
for t in (0.5, 0.75, 0.9):
    print(f"t={t}: penalty t/(1-t) = {t / (1 - t):.1f}")

def gain(c, t):
    return c - (1 - c) * t / (1 - t)

print(f"conf=0.6, t=0.75: E[answer] = {gain(0.6, 0.75):.2f}")
print(f"conf=0.8, t=0.9:  E[answer] = {gain(0.8, 0.9):.2f}")
print(f"a wrong answer costs 10 points: t = {10 / (1 + 10):.3f}")
n1, n = 200, 1_000
print(f"{n1} singletons in {n} facts: sr = {n1 / n:.2f}")
for s, n in ((1.5, 10_000), (1.0, 1_000_000)):
    sr, missing, _ = one_run(s, n, 0)
    print(f"s={s}, N={n}: sr={sr:.3f} missing={missing:.3f}")
under = 0.5 * z_true  # underconfident: logits shrunk by half
T_u = fit_temperature(under[cal], y[cal])
print(f"x0.5: ECE {ece(softmax(under[test]), y[test]):.3f}, T = {T_u:.3f}")
```

```text
t=0.5: penalty t/(1-t) = 1.0
t=0.75: penalty t/(1-t) = 3.0
t=0.9: penalty t/(1-t) = 9.0
conf=0.6, t=0.75: E[answer] = -0.60
conf=0.8, t=0.9:  E[answer] = -1.00
a wrong answer costs 10 points: t = 0.909
200 singletons in 1000 facts: sr = 0.20
s=1.5, N=10000: sr=0.038 missing=0.042
s=1.0, N=1000000: sr=0.006 missing=0.006
x0.5: ECE 0.177, T = 0.492
```

**1.** (a) At $s=1.5$ and $N=10{,}000$, `sr` is 0.038 and `missing` is 0.042; this is a single run, and the gap is within single-run noise. With a concentrated head little is left unseen. (b) At $s=1.0$ and $N=1{,}000{,}000$ both are 0.006. More data does lower the floor, but as long as the prompt distribution has a tail, some facts appear only once, so “more data is better” only pushes the floor down without reaching 0; how much data it takes to get low enough depends on how heavy the tail is.

**2.** At $t=0.75$ a wrong answer costs 3 points. Questions with confidence between 0.5 and 0.75 have a negative expected score when answered, and questions above 0.75 a positive one; the two parts nearly cancel, so $\theta=0.5$ scores close to 0. $\theta=0.75$ abstains on exactly the negative part and scores highest (0.096).

**3.** (a) $0.8-0.2\times 9=-1.00$, so do not answer, since 0.8 is below $t=0.9$. (b) $\lambda=10$, so $t=\lambda/(1+\lambda)\approx 0.909$.

**4.** The last line of the output: the ECE before scaling is 0.177 and the fitted $T=0.492$, close to 0.5: the logits were halved, and dividing by 0.5 restores them. $T<1$ means the model is underconfident and the confidences must be pushed toward the extremes; $T>1$ (like 2.461 in Experiment 3) means overconfident, and the confidences must be pulled back.

**5.** A reference plan: grade with a penalty set by the real cost of a wrong answer (for example 20 points off with 1 point for right gives $t=20/21\approx 0.952$) and put the threshold in the prompt; report accuracy, error rate, abstention rate and an accuracy–coverage curve rather than a single binary accuracy; on a held-out set draw a reliability diagram and report ECE (with the number of bins and the sample size), looking above all at the actual accuracy in the high-confidence bins; give confidence intervals for the error rate on the high-risk categories (see [evaluation statistics](https://dmxsf.com/en/wiki/evaluation/eval-statistics/)); and after launch, sample high-confidence answers for review and keep monitoring whether calibration drifts.

</details>

## Further reading

The paper links below were checked in November 2026.

- Kalai, Nachum, Vempala, Zhang, [Why Language Models Hallucinate](https://arxiv.org/abs/2509.04664), 2025
- Kalai, Vempala, [Calibrated Language Models Must Hallucinate](https://arxiv.org/abs/2311.14648), STOC 2024
- Miao, Kearns, [Hallucination, Monofacts, and Miscalibration: An Empirical Investigation](https://arxiv.org/abs/2502.08666), 2025
- Ji et al., [Survey of Hallucination in Natural Language Generation](https://arxiv.org/abs/2202.03629), 2022
- Huang et al., [A Survey on Hallucination in Large Language Models](https://arxiv.org/abs/2311.05232), 2023
- Lin, Hilton, Evans, [TruthfulQA: Measuring How Models Mimic Human Falsehoods](https://arxiv.org/abs/2109.07958), 2021
- Guo et al., [On Calibration of Modern Neural Networks](https://arxiv.org/abs/1706.04599), ICML 2017
- OpenAI, [GPT-4 Technical Report](https://arxiv.org/abs/2303.08774), 2023 (Figure 8: calibration curves before and after post-training)
- Kadavath et al., [Language Models (Mostly) Know What They Know](https://arxiv.org/abs/2207.05221), 2022
- Lin, Hilton, Evans, [Teaching Models to Express Their Uncertainty in Words](https://arxiv.org/abs/2205.14334), 2022
- Tian et al., [Just Ask for Calibration](https://arxiv.org/abs/2305.14975), EMNLP 2023
- Gekhman et al., [Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?](https://arxiv.org/abs/2405.05904), 2024
- Zhang et al., [R-Tuning: Instructing Large Language Models to Say ‘I Don’t Know’](https://arxiv.org/abs/2311.09677), NAACL 2024
- Tian et al., [Fine-tuning Language Models for Factuality](https://arxiv.org/abs/2311.08401), 2023
- Manakul et al., [SelfCheckGPT](https://arxiv.org/abs/2303.08896), 2023
- Kuhn, Gal, Farquhar, [Semantic Uncertainty](https://arxiv.org/abs/2302.09664), ICLR 2023

## Companion code

[Calibration: withheld answers, confidence and accuracy](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/hallucination-and-calibration): Fit temperature on held-out calibration examples and plot the trade-off between coverage and error using synthetic scores.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run safety/hallucination-and-calibration`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/hallucination-and-calibration/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/hallucination-and-calibration/README.en.md)
- [`calibration.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/evaluation/calibration.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#hallucination-and-calibration)

## FAQ

### What is hallucination in large language models, and what kinds are there?

Hallucination is fluent output that contradicts the facts or the sources the model was given. Two taxonomies are common. Huang et al. (2023) split it by what the output is checked against: factuality hallucination (it conflicts with real-world facts) and faithfulness hallucination (it departs from the user’s input or context, or contradicts itself). Ji et al. (2022) split it by the relation to a source: intrinsic (it contradicts the source) and extrinsic (it cannot be verified from the source, though it is not necessarily wrong). Closed-book question answering only meets factuality errors; summarization, document QA and RAG meet both kinds.

### Why do language models hallucinate, and can it be eliminated?

There is more than one cause. Many facts appear only once in the training data, so the model has no signal to tell true from false: Kalai et al. show that, in an idealized setting of arbitrary facts, a calibrated pretrained model errs on at least about the singleton rate, the share of prompts seen exactly once. The training objective is to continue text, not to check facts. And most benchmarks grade 0 or 1, so a wrong answer and “I don’t know” both score zero and guessing never hurts. The floor does not make hallucination inevitable, because a model can say “I don’t know”, but that trades coverage for accuracy: the errors turn into abstentions and do not disappear.

### What is calibration, and can I trust a model that says it is 90% sure?

A model is calibrated when its stated confidence matches how often it is right: among the answers it gives with 90% confidence, about 90% should be correct. It is measured with reliability diagrams and the expected calibration error (ECE). Pretrained models often have well-calibrated token probabilities and post-training weakens that: the GPT-4 technical report shows it on an MMLU subset, and Tian et al. (2023) found that for RLHF models, asking the model to state its confidence is often better calibrated than reading token probabilities, often cutting ECE by about half in relative terms. Measure ECE on your own task instead of assuming.

### Why is it so hard to get a model to say “I don’t know”?

Partly because the model does not know what it knows (poor calibration), and partly because grading rewards guessing: Kalai et al. (2025) point out that under binary grading, abstaining is never the best policy, and most popular benchmarks grade that way. They propose stating a confidence target in the question: 1 point for a right answer, a penalty of t/(1−t) points for a wrong one, 0 for “I don’t know”, so that answering pays only above confidence t. Experiment 2 on this page simulates it.

### Does retrieval-augmented generation (RAG) eliminate hallucination?

No. Retrieval puts missing or outdated facts into the context, which reduces factuality errors, but when retrieval fails the model still guesses, and it can still be unfaithful to what it retrieved. Kalai et al. (2025) note that as long as grading stays binary, guessing remains the best policy whenever search finds nothing. Pair RAG with citations, abstention and faithfulness evaluation; see the RAG page.
