Skip to content
E
Educatum

Hallucination is a known issue in Large Language Models (LLMs). How can you evaluate and mitigate it?

Curated by Educatum AI teamLast updated:
Large Language Models (LLMs)
Direct Answer

LLM hallucinations occur when models generate plausible-sounding claims that contradict provided context (intrinsic) or fabricate unverified real-world facts (extrinsic). Reliable evaluation relies on atomic claim decomposition, natural language inference (NLI) entailment against retrieved evidence, and self-consistency sampling rather than surface overlap metrics like BLEU. Mitigation combines retrieval-augmented generation (RAG), verification/constrained decoding, and post-training alignment that rewards grounded citations and calibrated abstention.

Study Card: Evaluating and Mitigating Hallucination in LLMs

Direct Answer

Hallucination in LLMs refers to generating fluent, confident text that is either intrinsic (contradicting or unsupported by the user-provided context) or extrinsic (fabricating false or unverifiable claims relative to world knowledge).

  • Evaluation: Surface n-gram metrics like BLEU or ROUGE fail badly at hallucination detection because flipping a single critical token (e.g., "16th" to "1st", or inserting "not") preserves high n-gram overlap while reversing truth value. Rigorous evaluation uses:
    1. Atomic Claim Decomposition & Verification (e.g., FActScore): Break responses into atomic facts and verify each against trusted evidence using an NLI entailment model or verifier LLM.
    2. RAG Faithfulness: Measure context-entailment precision (whether every claim in the answer is entailed by retrieved passages).
    3. Sampling Consistency (e.g., SelfCheckGPT): Sample multiple outputs at T>0T > 0; fabricated details tend to diverge across samples while grounded knowledge remains consistent.
    4. Benchmarks: TruthfulQA, HaluEval, and SimpleQA.
  • Mitigation:
    1. Retrieval-Augmented Generation (RAG): Retrieve authoritative documents at inference time, inject them with explicit citation instructions, and constrain outputs to retrieved evidence.
    2. Verification & Decoding Strategies: Apply Chain-of-Verification (CoVe), self-consistency, or constrained/structured decoding.
    3. Post-Training Alignment: Use RLHF/DPO with factuality rewards and explicit abstention training so models say "I don't know" rather than guessing when uncertain.

Key Terms

  • Intrinsic Hallucination: Output that directly contradicts or invents unsupported details beyond the provided source context (e.g., in summarization or RAG).
  • Extrinsic Hallucination: Output containing fabricated world facts that cannot be verified against ground-truth knowledge.
  • NLI Faithfulness / Entailment: Using a Natural Language Inference classifier to score whether a premise (retrieved context) entails, is neutral toward, or contradicts a generated claim.
  • Atomic Claim Decomposition: Splitting a multi-sentence model generation into minimal, independently verifiable propositions.
  • Retrieval-Augmented Generation (RAG): Grounding generation by retrieving external documents into the prompt before decoding.

Example

Suppose an LLM is asked for a short biography of Abraham Lincoln and writes: "Abraham Lincoln was the first president of the USA." Comparing against the ground truth "Abraham Lincoln was the 16th president of the USA", 9 of 10 tokens match—so a naive BLEU score remains misleadingly high despite a blatant factual hallucination. Instead, an atomic verifier decomposes the claim (Abraham Lincoln, ordinal_president, 1st) and checks it via NLI against a retrieved Wikipedia passage ("...16th president..."), flagging a contradiction. At inference time, mitigating this with RAG supplies the verified passage directly in the prompt and instructs the model to cite only the provided context or abstain.

Code Implementation

import re

# 1. Grounded RAG prompt construction with explicit abstention policy
def build_grounded_prompt(question: str, retrieved_chunks: list[str]) -> str:
    context = "\n".join(f"[{i+1}] {chunk}" for i, chunk in enumerate(retrieved_chunks))
    return (
        "Answer the question using ONLY the numbered context below. "
        "Cite sources as [1], [2], etc. If the context does not contain "
        "enough information, reply: 'Insufficient evidence in provided context.'\n\n"
        f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
    )

# 2. Claim-level verification (illustrative atomic check vs. naive token overlap)
def token_jaccard(a: str, b: str) -> float:
    sa, sb = set(re.findall(r"\w+", a.lower())), set(re.findall(r"\w+", b.lower()))
    return len(sa & sb) / len(sa | sb)

def verify_numeric_ordinal_claim(claim: str, evidence: str) -> str:
    """Illustrates why semantic/entity checks catch errors that overlap metrics miss."""
    claim_ordinals = set(re.findall(r"\b(?:\d+(?:st|nd|rd|th)|first|sixteenth)\b", claim.lower()))
    ev_ordinals = set(re.findall(r"\b(?:\d+(?:st|nd|rd|th)|first|sixteenth)\b", evidence.lower()))
    if claim_ordinals and ev_ordinals and claim_ordinals != ev_ordinals:
        return f"CONTRADICTION (claim={claim_ordinals}, evidence={ev_ordinals})"
    return "ENTAILED_OR_NEUTRAL"

# 3. Self-consistency check across stochastic samples (SelfCheck-style agreement)
def self_consistency_rate(samples: list[str]) -> float:
    normalized = [s.strip().lower() for s in samples]
    most_common = max(set(normalized), key=normalized.count)
    return normalized.count(most_common) / len(normalized)

evidence = "Abraham Lincoln served as the 16th president of the United States."
hallucinated_claim = "Abraham Lincoln was the first president of the United States."

print(f"Naive token Jaccard (misleadingly high): {token_jaccard(hallucinated_claim, evidence):.2f}")
print("Verifier result:", verify_numeric_ordinal_claim(hallucinated_claim, evidence))
print("Low-consistency samples score:", self_consistency_rate(["16th", "1st", "15th"]))
print("\n" + build_grounded_prompt("Which president was Abraham Lincoln?", [evidence]))
  • Calibration & Uncertainty Estimation: Measuring whether token probabilities or verbalized confidence align with empirical accuracy.
  • Chain-of-Verification (CoVe): Prompting a model to draft an answer, generate verification questions, answer them independently, and revise unsupported claims.
  • Sycophancy: Model tendency to agree with inaccurate user premises at the expense of factual truth.
  • LLM-as-a-Judge & NLI Verifiers: Automated evaluation pipelines (e.g., MiniCheck, AlignScore) that score faithfulness without relying on surface string overlap.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.