Causes of hallucination and mitigations
Section focus: Explain every item aloud without notes
Description
Level 1 — The Simple Intuition (ELI5)
An LLM does not "look up facts" in a database—it is a probabilistic next-word predictor trained to sound fluent and confident. Imagine an improv actor on stage: if you ask them about a fictional 2024 Supreme Court case, their training says "Never break character; always give a smooth, authoritative answer!" That fluent fabrication is a hallucination.
To stop the improv actor from making things up, we give them an open reference book on stage (RAG), train them that saying "I don't know" wins more points than guessing (Abstention Alignment), and have a fact-checker verify every claim against the book before the audience hears it (Grounded Verification).
Level 2 — Taxonomy & Root Causes of Hallucinations
We classify hallucinations into two fundamental categories:
- Closed-Domain (Intrinsic / Context) Hallucination: The model contradicts or fabricates details relative to the source text provided right inside the prompt (e.g., summarizing a medical note and inventing a dosage not mentioned in the note).
- Open-Domain (Extrinsic) Hallucination: The model states false world knowledge when no reference document is provided (e.g., inventing fake Python libraries, fake legal citations, or wrong historical dates).
Why Do LLMs Hallucinate? (5 Core Technical Causes)
- Next-Token Likelihood Truthfulness (Pretraining Objective): Cross-entropy loss rewards predicting statistically plausible token sequences from noisy web text, not epistemic truth.
- SFT Exposure Bias & "Forced Guessing" (Sycophancy): If SFT datasets always contain confident answers—even for obscure facts the base model doesn't actually know in its weights—SFT teaches the model to bluff confidently whenever it is uncertain!
- The Snowballing Effect (Autoregressive Error Propagation): Because decoding is causal, once an LLM samples one slightly inaccurate token at step , that token enters the context for step , forcing the model to invent justifications to stay self-consistent with its earlier mistake.
- Parametric Knowledge Cutoff & Long-Tail Compression: A model's weights are a lossy compression of the internet up to its cutoff date; rare entities (the "long tail") suffer interference in weight space.
- Attention Dilution ("Lost in the Middle"): In long prompts ( tokens), U-shaped attention bias causes the model to attend strongly to the beginning and end of the prompt while missing facts buried in the middle.
Level 3 — Engineering Mitigations Across the Stack
- Context & Architecture Layer (RAG + Citation Grounding):
- Retrieve verified chunks via hybrid search (BM25 + dense embeddings + cross-encoder reranker) and enforce inline span citations (
[Source ID]) with an explicit abstention instruction: "If the answer is not explicitly stated in the provided context, respond ONLY withINSUFFICIENT_CONTEXT."
- Decoding Layer:
- Lower temperature () for factual tasks.
- Context-Aware Decoding (CAD) / DoLa (Decoding by Contrasting Layers): Contrasts logits with vs. without context (or late vs. early Transformer layers) to amplify factual knowledge and suppress surface-level priors:
- Post-Training Layer (Factuality-Aware RLHF/DPO):
- Calibrate SFT/RLHF so abstaining on unknown facts receives higher reward than guessing wrong ().
- Verification & Guardrail Layer (NLI & Claim Decomposition):
- Break the generated response into atomic claims and run a fast Natural Language Inference (NLI) model or LLM-as-a-Judge (RAGAS Faithfulness) to check whether each claim is Entailed, Contradicted, or Unsupported by the retrieved context.
Learning notes
Defense-in-Depth Anti-Hallucination Pipeline
Loading diagram…
Root Cause Symptom Mitigation Matrix
Failure Layer | Root Cause | Classic Symptom | Production Fix |
Pretraining Data | Lossy compression of rare facts; temporal cutoff | Confuses two minor historical figures or cites 2023 API syntax | RAG • real-time tool/search grounding |
SFT / Alignment | Behavioral cloning on answers the base model doesn't know | Confidently invents fake DOIs, URLs, or court cases | Knowledge-boundary SFT • RL penalties for ungrounded claims |
Long Context Attention | "Lost in the Middle" U-shaped attention sink | Ignores a constraint on page 18 of a 40-page PDF | Chunking + Cross-Encoder Reranking (place top chunks at edges) |
Autoregressive Decoding | Snowballing commitment to an early bad token | Answers "Yes" on token 1, then fabricates a false proof | Chain-of-Thought (CoT) (reason before committing to an answer!) |
Tokenization (BPE) | Subword blindness to character/digit structure | Miscounts letters or hallucinates arithmetic | Delegate math/string ops to a Code Interpreter / Python Tool |
Example or implementation
Context-Aware Decoding (CAD) + Claim Faithfulness Scorer in Python
import torch import torch.nn.functional as F def context_aware_decoding_step( logits_with_context: torch.Tensor, # Logits from P(y_t | context, query) logits_without_context: torch.Tensor, # Logits from P(y_t | query) alone alpha: float = 0.5, ) -> torch.Tensor: """ Implements Context-Aware Decoding (Shi et al., 2023): Amplifies tokens whose probability increases when the retrieved context is present, suppressing the model's stubborn prior hallucinations! """ log_p_ctx = F.log_softmax(logits_with_context, dim=-1) log_p_prior = F.log_softmax(logits_without_context, dim=-1) adjusted_logits = (1.0 + alpha) * log_p_ctx - alpha * log_p_prior return F.softmax(adjusted_logits, dim=-1) def compute_ragas_faithfulness(claims: list[str], entailed_flags: list[bool]) -> float: """ RAGAS Faithfulness Metric: Faithfulness = (# of atomic claims supported by retrieved context) / (Total atomic claims in answer) """ if not claims: return 1.0 supported = sum(1 for flag in entailed_flags if flag) return supported / len(claims) # Example: Model prior wants to say "Paris" (index 0), but context says "Lyon" (index 1) logits_prior = torch.tensor([[5.0, 1.0, 0.0]]) # Prior strongly favors token 0 logits_ctx = torch.tensor([[3.5, 4.0, 0.0]]) # With context, token 1 is slightly ahead cad_probs = context_aware_decoding_step(logits_ctx, logits_prior, alpha=1.0) print("Standard Context Probs:", F.softmax(logits_ctx, dim=-1).tolist()) print("CAD Probs (Suppresses Prior):", cad_probs.tolist())
Interview-ready explanation
90-Second Spoken Pitch for Interviews
"Hallucinations are not random bugs—they are a direct consequence of how LLMs are trained and decoded. First, pretraining optimizes cross-entropy loss for plausible next-token continuation over lossily compressed web text, not factual verification. Second, during Supervised Fine-Tuning, if we force a model to imitate gold answers on facts outside its parametric knowledge, we accidentally train it to bluff confidently rather than abstain. Third, because autoregressive decoding is causal, a single wrong token early in a response triggers 'snowballing,' where the model fabricates supporting details to stay consistent with its own earlier output.
In production, we mitigate hallucinations across four layers:
- Prompt & Reasoning Design: Require Chain-of-Thought before stating conclusions (to prevent snowballing) and give the model an explicit abstention escape hatch (
'I don't know based on the provided context').
- Retrieval & Tool Use (RAG): Shift factual burden out of parametric weights into retrieved, reranked documents with mandatory inline citations, and delegate math or database lookups to deterministic tools.
- Decoding Controls: Use low temperature () or Context-Aware Decoding to force adherence to retrieved context over parametric priors.
- Automated Evaluation & Guardrails: Decompose responses into atomic claims and measure RAGAS Faithfulness via an NLI verifier before returning high-stakes outputs."