Hallucination & Factuality

A user asks a language model to cite the paper that proves a famous theorem. The model produces a fluent, precisely formatted reference. It includes author names, journal, year, and page numbers. But this reference does not exist. Nothing in the output signals uncertainty. The fabricated citation reads exactly like a real one. This phenomenon is called hallucination. It is one of the central obstacles to deploying large language models in medicine, law, and other high-stakes domains. The very fluency that makes these systems useful also makes their errors dangerous. Hallucination is not a bug that a patch will remove. It is a structural consequence of how Language model pretraining shapes a model's objective. The goal is to predict the next token that is plausible given the training distribution. It is not to predict the next token that is true. A model trained this way has no built-in mechanism for a key distinction. It cannot tell "this continuation is fluent and probable" apart from "this continuation is factually grounded." Understanding hallucination therefore requires understanding two things. First, the statistical mechanics of autoregressive generation. Second, the gap between likelihood and truth. This article develops a precise vocabulary for types of hallucination. It walks through the mechanisms that produce them: parametric knowledge gaps, exposure bias, decoding stochasticity, and reward hacking during alignment. It also surveys the principal countermeasures. These include retrieval grounding, citation-verification pipelines, calibration and abstention, and factuality-targeted fine-tuning. Each technique is evaluated not just on "does it help." It is also evaluated on why it helps and where it breaks down. Factuality tooling that sounds good in a demo often fails under distribution shift or adversarial prompting. By the end, you should be able to do several things. Explain what hallucination is at the level of the training objective. Categorize failure modes. Trace a worked example through a retrieval-augmented factuality check. Reason about the precision/recall tradeoffs inherent in every mitigation strategy. This sets up later material on Evaluation of LLMs, where hallucination rates become a benchmark axis. It also sets up Safety & Red-Teaming, where adversaries deliberately elicit confident falsehoods.

Key takeaways
  • Hallucination = fluent, confident output that is factually false or unsupported by evidence, arising from a probability-maximizing objective with no built-in truth predicate.
  • Two broad types: intrinsic (contradicts the given source/context) and extrinsic (unverifiable against, or absent from, any source).
  • Root causes include knowledge gaps in pretraining data, exposure bias during autoregressive decoding, sampling stochasticity, and reward models that reward confident-sounding answers over calibrated ones.
  • Mitigations span the pipeline: retrieval grounding (Retrieval-Augmented Generation), decoding-time constraints, self-consistency/verification, calibration and abstention, and factuality-aware fine-tuning (e.g., DPO on verified vs. fabricated pairs).
  • No single fix eliminates hallucination; each mitigation trades off recall (coverage of true answers) against precision (avoiding false claims), and most add latency or cost.
  • Measuring factuality itself is hard — automatic metrics (FActScore-style atomic-fact checking, NLI-based entailment) are imperfect proxies for human judgment.
The core insight

Hallucination happens because next-token likelihood and factual truth are correlated but not identical objectives, and every mitigation is really an attempt to inject an external truth signal that pretraining never provided.

The idea

A hallucination is a generated statement that is fluent and often stated with high confidence, but that is false, fabricated, or unsupported by any available evidence. The term is borrowed from vision/perception but is somewhat misleading: the model is not "seeing things" — it is doing exactly what it was trained to do, sampling from a learned distribution over token sequences that maximizes likelihood given context, not one that maximizes correspondence to external reality. It is useful to distinguish two families. An intrinsic hallucination contradicts information explicitly present in the model's own input (e.g., a summarization model asserts a fact that contradicts the source document it was asked to summarize). An extrinsic hallucination adds information that is neither supported nor contradicted by the input — it may be true by coincidence, false, or simply unverifiable (e.g., a model asked to summarize a short news snippet adds a statistic that appears nowhere in any accessible source). A further useful split is between closed-domain hallucination, where a ground-truth context is given (as in RAG or summarization, and correctness is checked against that context), and open-domain hallucination, where the model draws on its parametric memory of world facts with no supplied context, and correctness must be checked against the world. Formally, an autoregressive language model defines a distribution over the next token xtx_t given a prefix x<tx_{<t}:

pθ(xt∣x<t)=softmax(Wht+b)p_\theta(x_t \mid x_{<t}) = \text{softmax}(W h_t + b)

where hth_t is the model's hidden state after processing x<tx_{<t}. Training minimizes cross-entropy against a corpus:

L(θ)=−∑tlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\sum_t \log p_\theta(x_t \mid x_{<t})

Nothing in this loss distinguishes "the corpus said something true" from "the corpus said something false" — the model is fit to the distribution of tokens seen, weighted by frequency, not to an oracle of truth. Facts that are rare, contested, post-training-cutoff, or simply absent from the corpus get no gradient signal pulling the model toward a correct answer; instead, the model's best strategy at inference time is to produce the most probable-looking continuation, which for named entities, dates, and citations tends to have the surface form of a fact even when its content is invented.

How it works

Understanding hallucination requires tracing where in the pipeline unfaithfulness gets introduced, and then tracing where a countermeasure can intercept it. Four distinct mechanisms compound:

1. Knowledge gaps at training time. If a fact appears rarely, inconsistently, or not at all in pretraining data, the model has no strong parametric representation of it. When queried, it interpolates from related patterns (similar names, similar formats) and produces a plausible-looking but wrong answer, because the softmax always outputs some high-probability token — it has no "abstain" option baked in by default.

2. Exposure bias in autoregressive decoding. During training the model conditions on ground-truth prefixes (teacher forcing). At inference it conditions on its own previously generated (possibly already wrong) tokens. One hallucinated token early in a citation can commit the model to continuing the fabrication, because subsequent tokens are chosen to be probable given the corrupted prefix, not corrected against it.

3. Sampling stochasticity. Decoding strategies like temperature sampling or nucleus sampling intentionally inject randomness for diversity. This raises the probability of selecting a lower-probability continuation that happens to be false, especially in the "long tail" of rare entities, exact numbers, or precise dates — precisely where factual precision matters most and where the model's distribution is flattest (least peaked, most uncertain).

4. Reward misspecification during alignment. In RLHF or DPO fine-tuning, human raters (or a reward model standing in for them) tend to rate confident, complete-sounding answers higher than hedged or abstaining ones, even when the confident answer is wrong. This creates a training signal that actively rewards fluent fabrication over honest uncertainty — a well-documented failure mode sometimes called sycophancy-adjacent reward hacking. The countermeasures intercept these mechanisms at different pipeline stages. The pseudocode below sketches a realistic factuality-checking pipeline used to detect hallucinations post-hoc (as in FActScore-style evaluation and in production RAG systems with citation verification): ``` function CHECK_FACTUALITY(response, retrieved_docs):

# Step 1: decompose the response into atomic, checkable claims claims = DECOMPOSE_INTO_ATOMIC_FACTS(response)

# e.g. "Marie Curie won two Nobel Prizes, in Physics (1903)

# and Chemistry (1911)" ->

# ["Marie Curie won a Nobel Prize in Physics in 1903",

# "Marie Curie won a Nobel Prize in Chemistry in 1911"] results = [] for claim in claims:

# Step 2: retrieve evidence for this specific claim evidence = RETRIEVE(claim, corpus_or_docs=retrieved_docs, k=5) if evidence is EMPTY: verdict = "UNVERIFIABLE" else:

# Step 3: use an entailment / NLI model to check support score = ENTAILMENT_SCORE(premise=evidence, hypothesis=claim) if score > SUPPORT_THRESHOLD: verdict = "SUPPORTED" elif score < CONTRADICT_THRESHOLD: verdict = "CONTRADICTED" else: verdict = "UNVERIFIABLE" results.append((claim, verdict, evidence))

# Step 4: aggregate into a factuality score supported = count(v == "SUPPORTED" for (_, v, _) in results) factuality_score = supported / max(len(claims), 1) return factuality_score, results

function RETRIEVAL_AUGMENTED_GENERATION_WITH_ABSTENTION(query, corpus): docs = RETRIEVE(query, corpus, k=8) if RELEVANCE_SCORE(docs, query) < MIN_RELEVANCE: return "I don't have reliable information to answer this." draft = GENERATE(prompt=CONSTRUCT_PROMPT(query, docs)) score, per_claim = CHECK_FACTUALITY(draft, docs) if score < ACCEPTANCE_THRESHOLD:

# attempt one grounded rewrite, forcing citation of doc spans draft = REGENERATE_WITH_FORCED_CITATIONS(query, docs, per_claim) score, per_claim = CHECK_FACTUALITY(draft, docs) if score < ACCEPTANCE_THRESHOLD: return ABSTAIN_OR_HEDGE(draft, per_claim) return ANNOTATE_WITH_CITATIONS(draft, per_claim) ``` Each stage targets a specific mechanism: `RETRIEVE` supplies grounding text so the model is not relying solely on possibly-absent parametric knowledge (attacking mechanism 1); `CHECK_FACTUALITY` catches drift introduced by exposure bias and sampling (mechanisms 2–3) after generation, rather than trying to prevent it during decoding; `RELEVANCE_SCORE` gating and `ABSTAIN_OR_HEDGE` directly counteract the reward-hacking incentive to always produce a confident-sounding answer (mechanism 4), by making abstention a legitimate, scoreable output rather than a failure.

Figure
Where hallucination enters the pipeline, and where mitigations intercept it
Pretraining corpus → weights θ Prompting query + context Autoregressive decoding (sampling) Output final response Knowledge gap: rare/absent fact → interpolated guess Exposure bias + stochastic sampling → error compounds Retrieval grounding (inject evidence into context before generation) Relevance gating / forced citation prompting Constrained / low-temp decoding, self- consistency voting Post-hoc claim verification + abstention Red = where errors enter · Green = where each mitigation intercepts them No single stage is sufficient: knowledge gaps need retrieval; decoding errors need verification.

Complexity & correctness

Detection cost. Let a response contain mm atomic claims, and let retrieval over a corpus of size NN cost O(log⁡N)O(\log N) per query using an approximate nearest-neighbor index (e.g., HNSW), or O(N)O(N) for brute-force dense retrieval. Claim decomposition costs one additional LLM call of length proportional to the response, O(L)O(L) tokens where LL is response length. Then the full `CHECK_FACTUALITY` pipeline costs:

O(L  +  m⋅(log⁡N+CNLI))O\big(L \;+\; m \cdot (\log N + C_{\text{NLI}})\big)

where CNLIC_{\text{NLI}} is the cost of one entailment-scoring call (typically a smaller cross-encoder, O(ℓ2)O(\ell^2) in sequence length ℓ\ell for a Transformer, or O(ℓ)O(\ell) for a distilled scorer). Since mm (atomic facts per response) is typically small (5–30) and each NLI call is cheap relative to generation, factuality checking is usually a small constant-factor overhead on top of generation cost, not an asymptotic blow-up — but it does multiply latency and API cost linearly in mm, which matters at production scale.

Why retrieval reduces hallucination (the mechanism, formally). Without retrieval, the model must answer using only its parametric estimate pθ(answer∣query)p_\theta(\text{answer} \mid \text{query}), which is a marginal over everything seen in training — for rare facts this distribution is close to uniform over plausible-looking completions, i.e., high entropy, i.e., unreliable. With retrieval, the model instead computes pθ(answer∣query,evidence)p_\theta(\text{answer} \mid \text{query}, \text{evidence}), conditioning on evidence text that (if retrieval succeeds) sharply concentrates the token distribution around the supported answer — the conditioning reduces the conditional entropy of the next-token distribution when the evidence is relevant and correct. This is the same principle as Retrieval-Augmented Generation: retrieval does not change the model's parameters, it changes what conditional distribution is being sampled from at inference time. The correctness of this reduction is contingent, not guaranteed: it holds only if (a) retrieval returns relevant, correct evidence, and (b) the model is faithful to that evidence rather than overriding it with parametric priors (a known failure called context-parametric conflict, where a confidently wrong prior in the weights outvotes correct retrieved context).

Why detection (NLI-based checking) is a sound but incomplete filter. An entailment classifier trained to predict whether a premise supports a hypothesis provides a calibrated proxy for factual support, assuming its own training data is representative of the claim/evidence pairs encountered at test time. It is sound in the sense that high-confidence contradictions reliably flag real hallucinations (few false negatives for blatant fabrications). It is incomplete because: (1) it cannot verify claims for which no evidence was retrieved (labeled "unverifiable," which is not the same as "false" — a precision/recall gap the pipeline must live with); (2) it inherits any bias or blind spot of the NLI model itself; (3) atomic-fact decomposition is itself an LLM call and can silently drop or distort claims.

Honest tradeoffs. Every mitigation trades some quantity for factuality:

  • Retrieval grounding trades latency and infrastructure complexity (index maintenance, retrieval quality) for accuracy, and still fails when retrieval is wrong or the corpus lacks the needed document.
  • Abstention trades helpfulness (coverage — the fraction of queries answered at all) for precision (fraction of answered queries that are correct). A model that abstains on everything has zero hallucination and zero utility.
  • Lower decoding temperature reduces variance-driven hallucination but also reduces diversity and can increase repetition or degenerate output.
  • Self-consistency (sampling kk times and taking a majority-vote answer) improves precision on questions with a single stable answer but multiplies inference cost by kk and does not help when the model is systematically wrong (all kk samples share the same misconception), since majority voting over correlated errors converges to the wrong answer, not the right one.

Worked example

Consider a RAG system asked: "When did Alan Turing publish 'Computing Machinery and Intelligence,' and what test did it introduce?" Suppose the retrieval corpus contains one relevant document (a Wikipedia-style summary) but the retriever, under time pressure, returns three passages, one of which is only tangentially related.

StepStateDetail
1. Query—"When did Turing publish CMI, and what test did it introduce?"
2. Retrieve (k=3)Doc A (relevant), Doc B (relevant), Doc C (irrelevant, about the Enigma machine)Relevance scores: A=0.91, B=0.85, C=0.22
3. Relevance gatePasses (max score 0.91 > MIN_RELEVANCE=0.5)Proceeds to generation
4. Draft generation"Alan Turing published 'Computing Machinery and Intelligence' in 1950, introducing what is now called the Turing Test. In it, he predicted that by 2014, machines would pass the test 70% of the time."Model adds a fabricated statistic not present in any retrieved doc
5. Decompose into atomic claims(a) "Turing published CMI in 1950." (b) "CMI introduced the Turing Test." (c) "Turing predicted 70% pass rate by 2014."Three separate checkable units
6. Retrieve evidence per claim(a),(b): Doc A directly states both. (c): no matching passage in A, B, or CClaim (c) evidence = EMPTY
7. Entailment scoring(a) SUPPORTED (score 0.97). (b) SUPPORTED (score 0.95). (c) UNVERIFIABLE (no evidence retrieved)Two supported, one flagged
8. Factuality score2/3≈0.672/3 \approx 0.67Below example threshold of 0.8
9. Regenerate with forced citationModel asked to cite a span for every claim; claim (c) cannot be cited, model drops itNew draft omits the fabricated statistic
10. Re-check(a) SUPPORTED, (b) SUPPORTED — 2/2 = 1.0Passes threshold, returned with citations

This trace illustrates the key dynamic: retrieval alone did not prevent hallucination (Doc A/B contained no "70% by 2014" claim, yet the model produced one anyway — a classic case of the parametric prior injecting plausible-sounding but unsupported detail into an otherwise grounded answer). Only the post-hoc verification-and-regeneration loop caught and removed it. Note also that claim (c) is not necessarily false — Turing's actual 1950 paper does contain a similar prediction — but the pipeline correctly labels it "unverifiable" given the retrieved evidence, which is the honest and reproducible verdict a system without a perfect oracle can give. This distinction (unverifiable ≠ false) is one of the most commonly mishandled subtleties in factuality tooling.

Common pitfalls & traps

PitfallWhy it happensConsequence
Treating "unverifiable" as "false"Evaluation pipelines often binarize scoresPenalizes true-but-obscure facts, incentivizes only stating well-documented trivia
Trusting retrieval blindlyAssuming retrieved text is always relevant/correctCorpus errors or off-topic passages get faithfully summarized as fact
Context-parametric conflict ignoredModel's strong prior overrides correct retrieved evidenceModel contradicts the very document it was given
Self-consistency on systematically biased modelsMajority voting assumes errors are independentkk correlated hallucinated samples "confirm" each other
Confusing calibration with factualityA model can be well-calibrated on average confidence yet wrong on specific claimsHigh expressed confidence still misleads users on a per-claim basis
Over-rewarding confident answers in RLHFHuman raters prefer complete, fluent answers over hedged onesReward model teaches the policy to bluff rather than abstain
Evaluating factuality only on short-form QALong-form generation has compounding, harder-to-decompose errorsBenchmarks look good while real deployments still hallucinate

Pioneers & history

The study of factuality in generated text predates modern LLMs, growing out of work on abstractive summarization, natural language inference, and calibration in machine learning, before being reframed for autoregressive foundation models.

Origins · 1 minChristopher D. Manning and how this was discovered
CD
Christopher D. Manning
1966– · Stanford NLP; foundational work connecting language models, NLI, and grounded semantics

Manning's group produced much of the theoretical scaffolding — NLI datasets, entailment models, and grounded representation learning — that later became the standard toolkit for detecting hallucination via entailment-based fact-checking pipelines.

History
2018
— Large-scale NLI benchmarks (e.g., MultiNLI) mature entailment models later reused as hallucination detectors.
2020
— Retrieval-Augmented Generation is introduced, directly targeting knowledge-gap-driven hallucination.
2021
— Faithfulness metrics for abstractive summarization (intrinsic vs. extrinsic hallucination taxonomy) are formalized.
2022
— Instruction tuning and RLHF become widespread, exposing reward-hacking-driven confident fabrication at scale.
2023
— Atomic-fact factuality metrics (FActScore-style pipelines) enable fine-grained, per-claim hallucination measurement for long-form generation.

Where this matters

Production RAG systems in search engines, enterprise document assistants, and customer-support bots all depend on citation verification pipelines like the one above to avoid presenting fabricated content as sourced fact. Medical and legal LLM applications require explicit abstention thresholds, because an incorrect but confident answer in these domains carries real-world harm — several deployed systems refuse to answer, or route to a human, when factuality scores fall below a strict threshold. Search engines that summarize web results ("AI overviews") rely on the retrieval-relevance gate to avoid summarizing irrelevant or low-quality pages as if they were authoritative. Coding assistants face a specialized version of the problem — "API hallucination," where a model invents plausible-looking but nonexistent library functions — addressed by static-analysis-based post-hoc verification rather than NLI. Academic and scientific writing tools use citation-verification pipelines nearly identical to the pseudocode above to catch fabricated references before they reach a manuscript. All of these systems foreshadow the broader theme of Evaluation of LLMs (how do we benchmark factuality at scale) and Safety & Red-Teaming (how adversaries deliberately construct prompts that maximize hallucination rates, such as asking for citations on intentionally obscure or fictitious topics).

Ask the tutor: How would you design an evaluation benchmark that separately measures a model's hallucination rate on well-represented facts versus rare, long-tail facts?

Is hallucination the same as a model simply "lying"?

No. Lying implies intent to deceive, which requires a model to represent both the true fact and a decision to state otherwise — there is no strong evidence current LLMs do this by default. Hallucination is better understood as a byproduct of the training objective: the model is optimized to produce fluent, high-likelihood continuations, and truth is only a byproduct of that objective when the training data reliably supports the correct answer. When data is sparse, contradictory, or the query pushes into rare or adversarial territory, the model's most probable continuation can be false without any internal "intent." That said, some research on sycophancy shows models can shift toward what they infer a user wants to hear, which is a related but distinct phenomenon from pure knowledge-gap hallucination.

Can hallucination be reduced to zero?

Not with current architectures and training paradigms. Any system that must answer open-ended queries drawn from an unbounded world will occasionally lack grounding for some question, and forcing an answer anyway (rather than abstaining) will sometimes produce a false one. Reducing hallucination to zero would require either restricting the system to only answer questions with guaranteed-correct retrieved evidence (which sacrifices coverage substantially) or achieving perfect calibration and abstention (which is an open research problem). In practice, teams aim to minimize hallucination rate for a target coverage level, accepting a nonzero residual as reported clearly to users via citations, confidence indicators, or explicit caveats.

How does temperature affect hallucination rate?

Higher sampling temperature flattens the next-token probability distribution, increasing the chance of selecting lower-probability (and often less-supported) tokens, which raises hallucination risk especially for precise facts like dates, numbers, and proper nouns. Lower temperature (or greedy decoding) concentrates probability mass on the model's single most likely continuation, generally reducing hallucination on factual spans but at the cost of more repetitive, less creative text and, paradoxically, sometimes more confident-sounding wrong answers if the top token itself happens to be wrong. Temperature is a knob on variance, not a fix for a poorly grounded parametric prior — it cannot correct a systematically wrong high-probability answer.

What is FActScore and how does it differ from simple accuracy?

FActScore-style metrics decompose long-form generated text into atomic factual claims (short, independently checkable statements) and then score the fraction of those claims supported by a reference corpus or knowledge source, rather than scoring the response as a single true/false unit. This is important because long-form answers routinely mix correct and incorrect claims — a single accuracy number would mask partial hallucination. The decomposition step itself uses an LLM and is imperfect: it can merge, split, or drop claims incorrectly, which is why FActScore-style pipelines report both the atomic-fact score and qualitative error analysis, rather than treating the number as ground truth.

Does making a model bigger reduce hallucination?

Scale helps with knowledge-gap hallucination for well-represented facts, since larger models with more capacity and more training tokens tend to memorize more of the training distribution accurately, but scale does not fix structural issues like exposure bias, sampling-induced errors, or reward-hacking-driven overconfidence from alignment. Larger models can also become more fluent at producing convincing-sounding fabrications, which can make hallucinations harder for humans to detect even if the underlying rate is lower — a phenomenon sometimes noted in evaluations where larger, more fluent models receive higher human preference scores despite comparable or even higher rates of subtle factual error.

How does hallucination relate to calibration?

Calibration measures whether a model's expressed confidence (e.g., a probability or a verbal hedge) matches its actual accuracy — a well-calibrated model that says "I'm 70% sure" should be right about 70% of the time on such claims. Hallucination is a claim-level correctness failure, while calibration is a distributional property over many claims. A model can be well-calibrated in aggregate (its stated confidences track its overall accuracy) while still confidently hallucinating on specific individual claims, because calibration is measured in expectation, not per-instance. Improving calibration (e.g., via temperature scaling or verbalized-confidence fine-tuning) is a complementary but not sufficient strategy for reducing hallucination.

Why doesn't RAG fully solve hallucination if the model has the right document?

Because generation is still an autoregressive sampling process conditioned on, not dictated by, the retrieved text — the model can still choose a high-probability token that deviates from the evidence, especially when its pretrained prior strongly favors a different (more "typical") answer, a failure called context-parametric conflict. Retrieval quality itself is also imperfect: irrelevant or outdated documents can be retrieved with high similarity scores yet be factually inapplicable to the specific query. Effective RAG systems therefore pair retrieval with post-hoc entailment verification between the specific cited span and the specific claim, rather than trusting that "a relevant document was retrieved" implies "the generated claim is faithful to it."

Before this

Where this leads