Root Causes and Mitigations of LLM Hallucinations

Medium · Machine Learning · Machine Learning Engineer · Technical Screen

Prompt

Generative large language models (LLMs) frequently emit polished, authoritative-sounding prose that states false facts or invents details absent from provided reference documents—a failure mode widely referred to as hallucination.

Give a structured technical account of why LLMs hallucinate across the model lifecycle, addressing:

  1. Training objectives & corpus properties: How standard likelihood-based pretraining (alongside post-training alignment incentives) and real-world dataset characteristics push models toward plausible guessing rather than verified truth.
  2. Architecture & training dynamics: Structural and optimization constraints—including sequential autoregressive token prediction, train-versus-inference prefix mismatch (exposure bias), lossy storage in neural weights, and the lack of native external grounding.
  3. Runtime & inference triggers: How decoding hyperparameters, prompt phrasing or context window position, and out-of-distribution queries shape hallucination rates at serving time.
  4. Industry mitigations: Practical engineering defenses deployed in production systems to curb hallucinations, and why driving the error rate to absolute zero remains elusive.

Scope & Expectations

  • Objective & data foundations: Distinguish statistical plausibility under cross-entropy loss from factual truth, and connect long-tail data sparsity, noise, temporal cutoffs, and post-training reward design to confident guessing.
  • Model & generation mechanics: Explain how shared parametric memory, irreversible left-to-right token commitment, exposure bias, and missing truth-lookup circuits turn uncertainty into fluent fabrication.
  • Inference behavior: Clarify what greedy versus stochastic decoding actually changes (variance vs. bias) alongside prompt presuppositions, long-context attention dilution, and domain shift.
  • Layered production defenses: Summarize practical grounding, tool-calling, abstention calibration, and verification workflows paired with balanced accuracy-versus-coverage monitoring.

Step-by-step walkthrough

  1. Define hallucinations and map where they come from

    In generative AI, a hallucination is a smooth, decisive-sounding model output whose claims clash with real-world facts or go beyond the evidence supplied in the prompt. Engineers typically split the problem into two distinct categories:

    • Open-world factuality errors: Output that contradicts real-world facts—such as inventing a non-existent court case, stating the wrong founding year for a company, or fabricating a paper citation.
    • Closed-book / context faithfulness errors: Output that contradicts or extrapolates beyond a document supplied in the prompt—such as summarizing a property listing and stating "remodeled in 2022" when the listing text never mentions a remodel year.

    Every cause traces back to one foundational mechanism: an autoregressive LLM (a model that generates text one token at a time, conditioning each step on the prompt x and previously emitted tokens y_<t) learns a probability distribution over the next plausible word piece, not a verified database query:

    p_theta(y_1, ..., y_T | x)  =  product_{t = 1..T}  p_theta(y_t | x, y_1, ..., y_{t-1})
    
    Where hallucinations enter across the LLM lifecycle:
      [Web Corpus] ---> [Cross-Entropy Pretraining] ---> [Weights & Token Loop] ---> [Post-Training] ---> [Decoding & Prompt]
       rare facts,       copies errors & covers           lossy compression,          raters & binary      wrong mode, false
       noise, cutoff     all plausible modes              snowballing, no lookup      exams reward         premises, OOD
                                                                                      guessing             queries
    
  2. How the pretraining objective rewards plausibility over truth

    During pretraining, an LLM minimizes next-token cross-entropy loss over trillions of tokens from web pages, books, and code:

    L(theta) = - sum_t log p_theta(y_t | y_<t)
    

    Mathematically, cross-entropy is minimized when the model's predicted distribution p_theta exactly matches the empirical training distribution p_data (equivalently, minimizing forward KL divergence KL(p_data || p_theta), a distance measure that heavily penalizes assigning near-zero probability to any continuation that appears in the data). That creates three direct drivers of hallucination:

    1. Copying human misconceptions minimizes the loss: Suppose after a prompt, 70% of web pages state a true fact and 30% repeat a famous myth. A model that suppresses the myth to 1% actually gets a worse (higher) pretraining loss than a model that repeats the myth 30% of the time:
    import math
    
    
    def cross_entropy(data_probs, model_probs):
        """Cross-entropy H(p_data, p_model) = -sum p_i * log(q_i)."""
        loss = 0.0
        for p_true_freq, q_pred in zip(data_probs, model_probs):
            loss -= p_true_freq * math.log(q_pred)
        return loss
    
    
    corpus_dist = [0.70, 0.30]  # 70% accurate pages, 30% misconception pages
    for candidate_model in ([0.70, 0.30], [0.90, 0.10], [0.99, 0.01]):
        print(candidate_model, "-> loss =", round(cross_entropy(corpus_dist, candidate_model), 3))
    # [0.7, 0.3]   -> loss = 0.611  (global minimum: faithfully reproduces the 30% myth!)
    # [0.9, 0.1]   -> loss = 0.765
    # [0.99, 0.01] -> loss = 1.389  (heavily penalized when encountering the myth in training)
    
    1. Mode-covering behavior spreads probability across guesses: Because log(0) = -infinity, forward KL forces the model to spread positive probability across every plausible-sounding continuation rather than concentrating exclusively on verified facts.
    2. Zero native incentive to say "I don't know": In pretraining text, questions ("In what year was Ada Lovelace born?") are almost always followed by confident four-digit years ("1815"), rarely by "I don't know". Even when the model has no idea which year is right, a plausible four-digit year maximizes next-token likelihood.
  3. How training data characteristics guarantee knowledge gaps

    Even with an ideal optimizer, the model can only learn what its training corpus supports:

    • The long tail of singleton facts: Frequently repeated facts ("Paris is the capital of France") are reinforced thousands of times, whereas obscure facts (a niche API flag, a local statute, or an unfamiliar person's birthday) appear once or zero times. For arbitrary facts that follow no generalizable rule, statistical theory (Kalai & Vempala, 2024) shows that any calibrated generative model without external lookup must hallucinate at a rate roughly at least the singleton rate—the fraction of facts appearing only once in pretraining (for example, if 20% of biographical birth-year mentions in the corpus appear only once, a non-abstaining model must guess wrong on roughly 20%+ of such queries).
    • Noise, contradictions, and fiction: Web text mixes peer-reviewed science with forum rumors, outdated tutorials, satire, and fictional stories under a single uniform training objective.
    • Temporal cutoff (staleness): Pretraining freezes the world at a cutoff date; asking for "the current mortgage rate" or "the current CEO" elicits confident answers memorized from an earlier year.
    • Missing provenance and confident prose style: Models see the surface pattern of academic citations (Author (Year), Journal) without a live index of which papers exist, so blending real author names with a plausible title produces realistic fake references delivered in authoritative textbook prose.
  4. Model, architecture, and optimization limits

    Several architectural properties turn uncertainty into fluent fabrication:

    • Lossy parametric memory and entity interference: Unlike a relational database that stores each record in an isolated row, an LLM compresses billions of facts into shared weight matrices (parametric memory). Related entities share overlapping internal representations, causing attribute blending—for example, merging two co-authors' biographies or swapping parameters between two similarly named libraries.
    • Left-to-right commitment and hallucination snowballing: Standard decoding emits tokens strictly left-to-right with no "backspace" key. Once an early token commits to a false claim (say, answering "Yes" to a trick question), attention over that "Yes" pushes subsequent tokens to invent plausible justifications rather than self-contradict (snowballing). Moreover, small per-fact error rates compound rapidly over long responses: if each of 10 independent factual claims has a 95% chance of being right, the chance the entire paragraph is error-free drops to 0.95^10 = 0.599 (~40% chance of at least one hallucination).
    • Exposure bias: During training, teacher forcing always feeds the ground-truth prefix y_1, ..., y_{t-1} into step t. At inference time, the model conditions on its own generated tokens y_hat_1, ..., y_hat_{t-1} (exposure bias). One slightly off-distribution token nudges the hidden state into unfamiliar territory where errors cascade.
    • Lack of built-in grounding and subword tokenization: Out of the box, a transformer forward pass has no external world model, calculator, or truth-lookup circuit, and subword tokenization chops multi-digit numbers and rare names into irregular chunks, making exact arithmetic or character-level reasoning error-prone while keeping surrounding grammar smooth.
  5. How post-training and accuracy-only benchmarks amplify guessing

    Post-training stages (Supervised Fine-Tuning / SFT and Reinforcement Learning from Human Feedback / RLHF, which aligns models to human preference ratings) make models far more helpful, yet can accidentally worsen overconfident guessing:

    • Fine-tuning on unfamiliar facts teaches bluffing: When SFT pairs contain answers the base model never learned during pretraining, gradient updates teach the model to output confident-sounding specifics even when its internal representations lack the underlying fact.
    • Rater bias and sycophancy: Human raters often prefer thorough, decisive, polite answers over brief hedges, nudging RLHF models toward overconfidence and sycophancy (agreeing with a user's mistaken premise rather than pushing back).
    • Binary exam grading rewards wild guessing: Most leaderboards award +1 for a right answer and 0 for both a wrong answer and "I don't know". Under a 0 penalty for falsehoods, guessing beats abstaining whenever confidence p > 0! Only when wrong answers carry an explicit penalty -k does abstaining become optimal below p = k / (1 + k):
    def expected_score(prob_correct, wrong_penalty_k):
        """Score +1 if right, -k if wrong, vs. 0 for saying 'I don't know'."""
        return 1.0 * prob_correct - wrong_penalty_k * (1.0 - prob_correct)
    
    
    # Suppose the model only has a 30% chance (p = 0.30) of knowing an obscure fact:
    for k in (0, 1, 3):
        ev = expected_score(0.30, k)
        threshold = k / (1.0 + k)
        print(f"Penalty k={k}: E[guess]={ev:+.2f} vs E[abstain]=0.00 -> answer only if p > {threshold:.2f}")
    # Penalty k=0: E[guess]=+0.30 vs E[abstain]=0.00 -> answer only if p > 0.00  (always guess!)
    # Penalty k=1: E[guess]=-0.40 vs E[abstain]=0.00 -> answer only if p > 0.50
    # Penalty k=3: E[guess]=-1.80 vs E[abstain]=0.00 -> answer only if p > 0.75
    
  6. Inference-time factors: decoding, prompts, and distribution shift

    Even with fixed model weights, inference settings heavily shift hallucination rates:

    • Decoding strategies (temperature, top-p, top-k): Scaling logits by temperature T (p_i^(1/T) renormalized) sharpens the distribution when T < 1 and flattens it when T > 1. High T samples unlikely tail tokens and directly increases random fabrications. However, setting T = 0 (greedy decoding) does NOT eliminate hallucinations: it reduces variance, not bias. Watch both cases below—when the top mode ("1815") is right versus when a popular misconception pushes the wrong mode ("1816") to the top:
    def apply_temperature(probs, temp):
        scaled = {tok: p ** (1.0 / temp) for tok, p in probs.items()}
        z = sum(scaled.values())
        return {tok: round(val / z, 3) for tok, val in scaled.items()}
    
    
    # Case A: Correct answer ('1815') is the mode -> lower T reduces hallucinations (45% -> 25%)
    right_mode = {"1815": 0.55, "1816": 0.25, "1812": 0.20}
    print("Right mode T=1.0:", apply_temperature(right_mode, 1.0))  # {'1815': 0.55, '1816': 0.25, '1812': 0.2}
    print("Right mode T=0.5:", apply_temperature(right_mode, 0.5))  # {'1815': 0.747, '1816': 0.154, '1812': 0.099}
    
    # Case B: Wrong answer ('1816') is the mode -> lower T locks in the hallucination (55% -> 72.9% -> 100% at T=0)!
    wrong_mode = {"1816": 0.55, "1815": 0.30, "1812": 0.15}
    print("Wrong mode T=0.5:", apply_temperature(wrong_mode, 0.5))  # {'1816': 0.729, '1815': 0.217, '1812': 0.054}
    
    • Prompt pitfalls and long-context attention decay: Prompts containing false presuppositions ("Why did Einstein win his second Nobel Prize?"), leading confirmations ("This home has a pool, right?"), demands for exact URLs/quotes, or instructions like "always give a complete answer" push the model to confabulate. In long prompts, facts buried in the middle of thousands of tokens receive weaker effective attention ("lost in the middle"), or clash with memorized parametric priors.
    • Distribution shift: Queries involving post-cutoff news, proprietary enterprise records, low-resource languages, or niche domain jargon fall outside the training distribution, causing fallback guessing.
  7. Practical industry techniques to reduce hallucinations

    No single technique eliminates hallucinations completely, so production systems layer defenses across grounding, training, and runtime verification:

    1. Retrieval-Augmented Generation (RAG) with verified citations: Fetch relevant passages from an authoritative index, prompt the model to answer strictly from those passages with inline citations, and run a lightweight natural language inference (entailment) classifier to verify that each cited span actually supports the generated claim.
    2. Deterministic tool calling and structured constraints: Offload exact facts, math, and live records to SQL/API calls, calculators, or code interpreters—for example, a real-estate assistant should fetch square footage, property taxes, and listing price from a structured listing API rather than model weights—and use constrained decoding (JSON schemas / enum grammars) so invalid IDs or fields cannot be emitted.
    3. Calibration and explicit abstention training: Include unanswerable and low-retrieval-confidence examples during SFT/RLHF where "I don't have enough verified information to answer" earns higher reward than an unsupported guess.
    4. Self-consistency and semantic entropy gating: Sample K independent responses at T > 0 and measure whether they agree in meaning (semantic entropy, clustering responses by mutual entailment and computing Shannon entropy over meaning clusters). High disagreement flags that the model is guessing, triggering abstention, human review, or deeper retrieval:
    import math
    from collections import Counter
    
    
    def answer_entropy(sampled_answers):
        """Return (top_agreement_fraction, shannon_entropy_nats) across K sampled short answers."""
        counts = Counter(sampled_answers)
        k = len(sampled_answers)
        top_share = counts.most_common(1)[0][1] / k
        entropy = 0.0
        for count in counts.values():
            p = count / k
            entropy -= p * math.log(p)
        return top_share, round(entropy, 3)
    
    
    print("Uncertain guess :", answer_entropy(["1815", "1815", "1816", "1812", "1820"]))  # (0.4, 1.332) -> abstain/verify!
    print("High consistency:", answer_entropy(["1815", "1815", "1815", "1815", "1815"]))  # (1.0, 0.0)   -> confident
    
    1. Claim-level verification and dual monitoring: Decompose long answers into atomic claims checked via Chain-of-Verification (answering independent verification questions per claim) or automated factuality judges, and always track hallucination rate alongside abstention rate in production so a model cannot game metrics by refusing every question.

Intuition & how it works

Picture an LLM as a brilliant improv actor who has read billions of web pages once, has no internet access on stage, is never allowed to hit backspace, and gets applauded for sounding fluent rather than pausing to say "I don't know." At every single step, an autoregressive language model (a neural network that predicts a probability distribution over the next subword token given the preceding tokens) simply picks a continuation that sounds statistically plausible in context—and plausibility is not the same thing as truth.

Naive intuition says hallucinations happen only because "the training data had bad facts" or "temperature was set above zero," so training a bigger model on cleaner data at temperature = 0 should cure them. That falls short at every layer of the stack: cross-entropy pretraining (minimizing -log p(next_token | context)) mathematically penalizes a model for suppressing myths present in human text and never rewards abstaining; parametric memory (compressing billions of facts into shared weight matrices) blurs rare entities together; left-to-right token generation commits early and snowballs to justify mistakes; and temperature = 0 (greedy decoding, always picking the single highest-probability token) still outputs a falsehood 100% of the time whenever the model's top guess is wrong.

Walk through a concrete 3-option token decision for "Ada Lovelace was born in the year ___": 1. When the model barely saw the fact: Suppose weights spread probability across three plausible 19th-century years: {"1815": 0.55, "1816": 0.25, "1812": 0.20}. Sampling at temperature = 1.0 fabricates a wrong birth year 45% of the time; sharpening to temperature = 0.5 (p^2 renormalized) lifts "1815" to 74.7% and cuts errors to 25.3%. 2. When a corpus misconception dominates: If noisy text pushed "1816" to 0.55 and "1815" to 0.30 (with "1812" at 0.15), lowering temperature to 0.5 boosts the wrong year to 72.9%, and temperature = 0 locks in "1816" deterministically every single run. 3. How layered mitigations catch it: Connecting a trusted retrieval source or structured lookup supplies "1815" directly in the prompt (grounding), while sampling 5 answers without retrieval reveals disagreement (["1815", "1815", "1816", "1812", "1820"], entropy 1.33 nats) so an abstention gate can withhold the unverified claim instead of bluffing.

Key points

  • Objective mismatch (plausibility vs. truth): Next-token cross-entropy minimizes forward KL divergence (KL(p_data || p_theta)), which is mode-covering (it spreads probability mass over all continuations seen in text) and reaches its mathematical minimum (0.611 vs 1.389 in a 70/30 split) by copying corpus misconceptions rather than saying "I don't know".
  • Data limits (long-tail singletons, staleness, no provenance): Facts seen once or zero times in pretraining cannot be reliably separated from noise (bounding calibrated closed-book error rates from below by the singleton fraction), post-cutoff events are unknown, and citations are learned as stylistic templates rather than verified pointers.
  • Architecture & optimization limits: Compressing facts into shared neural weights causes entity blending; left-to-right token emission cannot backtrack and snowballs once a false prefix is emitted (0.95^10 = 0.599 joint accuracy across 10 claims); exposure bias (training on ground-truth prefixes via teacher forcing, but generating on self-sampled prefixes) compounds drift; and weights have no built-in truth-lookup mechanism.
  • Post-training & evaluation incentives: Fine-tuning on facts absent from pretraining teaches confident bluffing, RLHF (Reinforcement Learning from Human Feedback) can reward verbose confidence and sycophancy (agreeing with false user premises), and binary 1/0 accuracy leaderboards make guessing strictly optimal whenever p > 0 unless wrong answers incur a penalty -k (raising the optimal answer threshold to p > k / (1 + k)).
  • Inference triggers: High temperature/top-p sampling draws low-probability tail fabrications, whereas temperature = 0 still fails whenever the top mode is biased; leading prompts, false presuppositions, middle-of-context dilution (lost in the middle), and out-of-distribution queries all elevate error rates.
  • Defense-in-depth mitigations: Combine RAG (Retrieval-Augmented Generation, injecting retrieved source passages into context) with claim-level entailment verification (checking that cited text logically proves each claim), deterministic API/SQL/calculator tool calls, schema-constrained decoding, explicit abstention training, and semantic entropy (measuring meaning disagreement across multiple sampled answers).

Common mistakes

  • Claiming temperature = 0 eliminates hallucinations: Greedy decoding only eliminates sampling randomness (variance); whenever the model assigns its highest probability to a misconception or blended entity (bias), temperature = 0 repeats that falsehood with 100% consistency.
  • Assuming model scale alone will drive hallucinations to zero: Larger models memorize more head and torso facts, but arbitrary singleton facts, private enterprise data, and events after the training cutoff remain fundamentally unknowable from static weights alone.
  • Treating RAG as a complete cure rather than a shift from open-world to faithfulness risk: Retrieval can fetch irrelevant chunks, the model's parametric memory can override a retrieved passage, or the generator can weave unsupported numbers between two valid citations unless faithfulness is explicitly checked.
  • Confusing exposure bias with standard overfitting: Overfitting memorizes training examples too tightly, whereas exposure bias is the train/inference mismatch between conditioning on gold ground-truth prefixes during teacher forcing and conditioning on the model's own imperfect generated tokens at runtime.
  • Tracking hallucination rate without abstention/coverage rate: A trivial filter that replies "I cannot answer" to 99% of user questions achieves near-zero hallucinations while being completely useless; always evaluate factuality precision alongside answer coverage.

Follow-up questions

  • How would you systematically measure the hallucination rate of a production LLM assistant? Construct a stratified golden evaluation set drawn from real domain traffic—covering closed-book facts, multi-document RAG queries, numerical reasoning, and unanswerable/false-premise prompts. Decompose each model response into atomic factual claims (in the style of FActScore) and label every claim as supported, contradicted, or unverifiable against authoritative sources using calibrated human annotators plus an automated LLM/entailment judge validated against human agreement. Track claim-level precision, response-level error rate (share of answers with >= 1 unsupported claim), and the abstention rate side by side.
  • How should an engineering team set the confidence threshold for abstaining rather than answering? Frame abstention as a cost-sensitive decision rule over a calibrated confidence score—derived from retrieval similarity, multi-sample semantic entropy, verbalized/logit confidence, or an entailment verifier. If a correct answer delivers +1 utility, abstaining delivers 0, and a hallucinated answer costs -k (for example k = 4 in financial or real-estate guidance), answer only when calibrated P(correct) > k / (1 + k) = 0.80, after fitting Platt or isotonic calibration on a held-out validation set so predicted probabilities match empirical accuracy.
  • Why does an LLM sometimes ignore a retrieved RAG passage when that passage contradicts memorized pretraining facts, and how do you fix it? During pretraining, the model relied heavily on strong parametric associations for high-frequency entities, so if a retrieved snippet updates a well-known fact (such as a recently changed price, executive, or policy) or sits buried in the middle of a long context window, parametric priors can outweigh context attention. Mitigate this by placing top-reranked evidence near the prompt boundaries, using explicit counterfactual context-faithfulness fine-tuning (training on examples where context deliberately overrides stale facts), quoting exact spans before answering, and running a post-generation entailment check against the retrieved passage.

Follow-up questions

Similar questions

More Zillow interview questions

All 3 Zillow questions →