Skip to content
Skip to lesson
Back to Topics
LearnApplied LLM Engineering & RAGHallucination Detection & Mitigation
MediumAlignment & Safety16 min read

Hallucination Detection & Mitigation

Separate factual claims from retrieved evidence using atomic claim verification, semantic consistency, calibrated NLI scoring, and conformal risk-coverage gates.

On this page

When an engineering documentation assistant answers a question about PyTorch compiler behavior, it can quote a real documentation header and still deliver a subtle bug into user code. Consider a developer asking a assistant whether torch.compile supports custom torch.autograd.Function backward passes with multiple tensor outputs, and whether fullgraph=True silently falls back to eager execution when an unsupported Python hook runs. Two retrieved PyTorch documentation passages confirm that custom autograd.Function backward passes work inside torch.compile, while fullgraph=True raises an error on graph breaks instead of falling back to eager mode (fullgraph=False is the flag that falls back per graph break).

Now examine a fluent four-sentence reply generated from those passages: the assistant notes that custom backward passes compile cleanly (supported), promises that multi-tensor custom outputs fuse automatically into one CUDA graph (fabricated), claims fullgraph=True silently falls back to eager mode (contradicted), and remarks that torch.compile shipped in PyTorch 2.0 (accurate in general weights, yet missing from the retrieved context). Evaluating that reply at the whole-answer level or rewarding its clean syntax and valid document link hides both the fabricated optimization promise and the inverted compiler semantics. Research on why language models hallucinate shows that standard pretraining and post-training objectives reward confident guessing whenever uncertainty goes unpenalized [1]. Production reliability demands checking every atomic statement individually before deciding whether to serve, prune, re-retrieve, or abstain.

Verification pipeline splitting a generated draft into atomic claims, scoring each claim against retrieved documents with an NLI verifier, and routing to serve verified claims or retry and abstain.
Claim-level verification decomposes a generated draft into atomic statements, checks each unit against retrieved context chunks via a calibrated NLI verifier, and routes the result to serve verified clauses, re-retrieve, or abstain.

Context grounding vs. world accuracy

Every evaluation pipeline must separate two orthogonal questions that coarse benchmarks often collapse into one number [2]. Context grounding asks whether a generated claim follows logically from the documents retrieved in the prompt (P(entailed | claim, docs)). External accuracy asks whether the claim holds true in the real world at serving time regardless of what the retriever happened to return.

Treating those two axes independently produces a clear taxonomy for routing decisions:

Failure regimeContext supportWorld truthExample from torch.compile QAOperational action
Supported & truePresentTrueCustom autograd.Function backward compilesKeep and serve with citation
Extrinsic fabricationAbsentFalseMulti-tensor outputs auto-fuse into one CUDA graphPrune clause or re-retrieve
Intrinsic contradictionContradictedFalsefullgraph=True silently falls back to eager modeBlock draft and abstain or rewrite
Uncited true factAbsentTruetorch.compile shipped in PyTorch 2.0Retrieve supporting doc before citing
Stale retrieved indexPresent in chunkFalse nowDeprecated flag kept in an outdated index snapshotRefresh index before trusting chunk

Two practical consequences follow directly from this grid. First, surface lexical overlap metrics miss contradictions because negations (does not fall back versus silently falls back) share almost identical unigrams and bigrams. Second, uncited true statements (C4) remain risky in grounded enterprise assistants because citation checks fail silently whenever users click the attached snippet to verify an unmentioned version history or policy threshold.

Quadrant chart mapping context support against world accuracy. C1 (Supported) serves directly, C4 (Uncited) needs a retrieved citation, C2 (Fabricated) and C3 (Contradicted) are pruned or blocked, and Stale doc triggers index refresh.
Separating retrieved evidence support from external factual accuracy yields distinct routing rules: prune or re-retrieve unsupported clauses, block contradictions, and refresh stale indexes.

Modern atomic verification frameworks such as FActScore [3] and RAGAS Faithfulness [4] address mixed-quality paragraphs by splitting long answers into minimal propositions before grading. Once a reply is decomposed into mm atomic claims {c1,…,cm}\{c_1, \dots, c_m\}, we measure two key quantities across a serving policy:

Unsupported Risk=Served Unsupported ClaimsTotal Served Claims,Safe Recall=Served Supported ClaimsTotal Ground-Truth Supported Claims\text{Unsupported Risk} = \frac{\text{Served Unsupported Claims}}{\text{Total Served Claims}}, \qquad \text{Safe Recall} = \frac{\text{Served Supported Claims}}{\text{Total Ground-Truth Supported Claims}}

Notice why partial pruning outperforms naive all-or-nothing serving when a draft mixes true statements with a non-essential fabricated embellishment. Dropping an unsupported clause (C2) eliminates the unsupported risk while preserving supported answers (C1), whereas keeping the draft unedited exposes users to false guarantees. However, when a draft contains a direct contradiction (C3), partial pruning can leave broken causal transitions or misleading reassurance, making full rewrite or safer.

claim-level-verification-routing.py

def evaluate_policy(policy: str, accept_cutoff: float = 0.70) -> dict[str, float]:
    served_claims = 0
    served_unsupported = 0
    served_supported = 0
    total_supported = sum(
        sup for row in RESPONSES for (_, sup, _, _) in row["claims"]
    )
    queries_answered = 0

    for row in RESPONSES:
        claims = row["claims"]
        has_contradiction = any(score < 0.20 for (_, _, _, score) in claims)

        if policy == "serve_all":
            kept = claims
        elif policy == "prune_and_block_contradiction":
            kept = [] if has_contradiction else [
                c for c in claims if c[3] >= accept_cutoff
            ]
        elif policy == "prune_unsupported":
            kept = [c for c in claims if c[3] >= accept_cutoff]
        else:
            raise ValueError(f"unknown policy: {policy}")

        if kept:
            queries_answered += 1
        for (_, sup, _, _) in kept:
            served_claims += 1
            served_supported += sup
            served_unsupported += (1 - sup)

    risk = served_unsupported / max(served_claims, 1)
    safe_recall = served_supported / max(total_supported, 1)
    coverage = queries_answered / len(RESPONSES)
    return {
        "risk": risk,
        "safe_recall": safe_recall,
        "coverage": coverage,
        "served_claims": served_claims,
    }
Output
serve_all                      | risk=0.400 | safe_recall=1.000 | coverage=1.000 | kept=10
prune_unsupported              | risk=0.000 | safe_recall=1.000 | coverage=1.000 | kept=6
prune_and_block_contradiction  | risk=0.000 | safe_recall=0.500 | coverage=0.333 | kept=3

Uncertainty and multi-sample consistency

When retrieved documents are absent or noisy, practitioners often inspect the generator's own probabilities or sample distribution for internal signals of doubt. At decoding step tt, given prefix (x,y<t)(x, y_{<t}) and vocabulary V\mathcal{V}, the token-level measures how flat or peaked the next-token distribution is, while sequence aggregates surprise over the generated tokens:

H(Yt∣y<t,x)=−∑v∈Vpt(v)log⁡pt(v),PPL⁡(y∣x)=exp⁡ ⁣(−1T∑t=1Tlog⁡pt(yt∣y<t,x))H(Y_t \mid y_{<t}, x) = -\sum_{v \in \mathcal{V}} p_t(v) \log p_t(v), \qquad \operatorname{PPL}(y \mid x) = \exp\!\left(-\frac{1}{T}\sum_{t=1}^{T} \log p_t(y_t \mid y_{<t}, x)\right)

Token entropy works well when a model hesitates over a single rare identifier or numeric hyperparameter such as a version string or port number. Yet raw token probabilities suffer from two systematic blind spots that break naive log-probability thresholds in practice.

First, surface lexical uncertainty rises whenever multiple synonymous phrasings compete for probability mass, even if every continuation conveys the exact same true meaning. Saying "raises a graph break error", "throws an exception on graph breaks", or "aborts compilation when a break occurs" spreads next-token mass across distinct words while carrying zero uncertainty about semantics. Second, minimum token probability depends heavily on arbitrary tokenization boundaries and punctuation styling.

Semantic Entropy [5] resolves lexical dilution by sampling KK candidate completions at temperature T>0T > 0, clustering completions that entail each other mutually into semantic equivalence classes c∈Cc \in \mathcal{C}, summing cluster probabilities P(c∣x)=∑y∈cp(y∣x)P(c \mid x) = \sum_{y \in c} p(y \mid x), and computing entropy over clusters rather than surface strings:

Hsem(x)=−∑c∈CP(c∣x)log⁡P(c∣x)H_{\text{sem}}(x) = -\sum_{c \in \mathcal{C}} P(c \mid x) \log P(c \mid x)

Because computing full bidirectional entailment across O(K2)O(K^2) sample pairs adds serving latency, linear probes trained on hidden states before decoding can predict semantic entropy in a single forward pass [6]. In black-box APIs where neither logits nor hidden states are exposed, SelfCheckGPT [7] approximates consistency by comparing each sentence in a greedy primary reply against KK stochastic samples using NLI contradiction scores, QA equivalence, or n-gram overlap: genuine random fabrications vary across samples, whereas recalled facts repeat consistently.

Neither uncertainty nor consensus, however, can diagnose confident misconceptions. When pretraining corpora repeat an API myth or outdated syntax frequently, greedy decoding and stochastic samples converge on the same false answer with low token entropy, low semantic entropy, and 100% sample agreement. Self-consistency tells you whether a claim is unstable across draws, never whether it agrees with ground truth or retrieved documentation.

token-vs-semantic-entropy.py
def token_metrics(logits: np.ndarray, chosen_idx: np.ndarray) -> tuple[float, float, float]:
    """Return mean token entropy, min chosen prob, and sequence perplexity."""
    probs = softmax(logits, axis=1)
    step_entropies = np.array([entropy(p) for p in probs])
    chosen_probs = probs[np.arange(len(chosen_idx)), chosen_idx]
    perplexity = float(np.exp(-np.mean(np.log(np.clip(chosen_probs, 1e-12, 1.0)))))
    return float(np.mean(step_entropies)), float(np.min(chosen_probs)), perplexity

def semantic_cluster_entropy(sample_logprobs: np.ndarray, cluster_ids: list[int]) -> float:
    """Compute entropy after summing probability mass inside each meaning cluster."""
    weights = softmax(sample_logprobs)
    cluster_masses: dict[int, float] = {}
    for w, cid in zip(weights, cluster_ids):
        cluster_masses[cid] = cluster_masses.get(cid, 0.0) + float(w)
    dist = np.array(list(cluster_masses.values()))
    return float(entropy(dist))

# Case A: Grounded statement with sharp token focus
logits_grounded = np.array([[4.5, 0.3, -0.5, -1.0], [4.2, 0.4, -0.2, -0.8], [4.8, 0.1, -0.6, -1.2]])
tok_ent_a, min_p_a, ppl_a = token_metrics(logits_grounded, np.array([0, 0, 0]))
sem_ent_a = semantic_cluster_entropy(np.array([-0.2, -0.3, -0.25, -0.4, -0.35]), [0, 0, 0, 0, 0])

# Case B: Valid answer split across 3 synonymous phrasings (high token entropy, zero semantic entropy)
logits_paraphrase = np.array([[1.4, 1.3, 1.2, -1.5], [1.6, 1.5, 1.3, -1.2], [2.1, 1.8, 1.4, -1.0]])
tok_ent_b, min_p_b, ppl_b = token_metrics(logits_paraphrase, np.array([0, 1, 0]))
sem_ent_b = semantic_cluster_entropy(np.array([-1.1, -1.2, -1.3, -1.4, -1.5]), [0, 0, 0, 0, 0])

# Case C: Confident falsehood ("fullgraph=True falls back to eager"): low entropy everywhere
logits_myth = np.array([[4.4, 0.2, -0.4, -1.1], [4.6, 0.1, -0.5, -1.0], [4.3, 0.3, -0.3, -0.9]])
tok_ent_c, min_p_c, ppl_c = token_metrics(logits_myth, np.array([0, 0, 0]))
sem_ent_c = semantic_cluster_entropy(np.array([-0.1, -0.15, -0.2, -0.12, -0.18]), [0, 0, 0, 0, 0])

# Case D: Spontaneous fabrication drifting across 4 contradictory meanings across 5 samples
logits_fabric = np.array([[1.1, 1.0, 0.9, 0.8], [0.9, 0.8, 0.7, 0.6], [1.2, 1.0, 0.8, 0.5]])
tok_ent_d, min_p_d, ppl_d = token_metrics(logits_fabric, np.array([0, 1, 2]))
sem_ent_d = semantic_cluster_entropy(np.array([-1.2, -1.3, -1.5, -1.6, -1.8]), [0, 1, 2, 3, 1])

rows = [
    ("Grounded crisp", tok_ent_a, min_p_a, ppl_a, sem_ent_a),
    ("Paraphrase valid", tok_ent_b, min_p_b, ppl_b, sem_ent_b),
    ("Confident myth", tok_ent_c, min_p_c, ppl_c, sem_ent_c),
    ("Drifting fabric.", tok_ent_d, min_p_d, ppl_d, sem_ent_d),
]
for label, h_tok, p_min, ppl, h_sem in rows:
    print(f"{label:17s} | H_tok={h_tok:.3f} | min_p={p_min:.3f} | PPL={ppl:.2f} | H_sem={h_sem:.3f}")
Output
Grounded crisp    | H_tok=0.148 | min_p=0.960 | PPL=1.03 | H_sem=0.000
Paraphrase valid  | H_tok=1.160 | min_p=0.334 | PPL=2.67 | H_sem=0.000
Confident myth    | H_tok=0.149 | min_p=0.967 | PPL=1.03 | H_sem=0.000
Drifting fabric.  | H_tok=1.372 | min_p=0.225 | PPL=3.89 | H_sem=1.338

Calibrated NLI verification and conformal risk-coverage gates

Raw verifier scores, including cosine similarity from dense embeddings, cross-encoder NLI entailment logits, and judge rubrics, seldom behave as true probabilities out of the box [8]. Neural networks often exhibit overconfidence in the tails, meaning a raw score of 0.85 might reflect only 62% empirical claim support on production queries. Feeding uncalibrated scores directly into product cutoffs causes threshold drift whenever prompt lengths or retrieval scores shift.

Platt or logistic calibration maps raw verification features z∈Rdz \in \mathbb{R}^d to well-calibrated probabilities p^=σ(w⊤z+b)\hat{p} = \sigma(w^\top z + b) on a held-out calibration split [9]. We measure calibration quality using two complementary metrics: the , which captures proper squared-error sharpness and reliability jointly, and across quantile probability bins B1,…,BMB_1, \dots, B_M:

Brier=1n∑i=1n(p^i−yi)2,ECE=∑m=1M∣Bm∣n∣acc⁡(Bm)−conf⁡(Bm)∣\text{Brier} = \frac{1}{n}\sum_{i=1}^{n} (\hat{p}_i - y_i)^2, \qquad \text{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{n} \left| \operatorname{acc}(B_m) - \operatorname{conf}(B_m) \right|

Once p^i\hat{p}_i is calibrated, choosing an operational acceptance cutoff τ∈[0,1]\tau \in [0, 1] defines a Risk-Coverage Curve. Accepting a claim only when p^i≥τ\hat{p}_i \ge \tau yields empirical coverage C(τ)=1n∑iI[p^i≥τ]C(\tau) = \frac{1}{n}\sum_i \mathbb{I}[\hat{p}_i \ge \tau] and selective unsupported risk among served claims:

R^sel(τ)=∑i=1nI[p^i≥τ∧yi=0]max⁡(1,∑i=1nI[p^i≥τ])\hat{R}_{\text{sel}}(\tau) = \frac{\sum_{i=1}^{n} \mathbb{I}[\hat{p}_i \ge \tau \land y_i = 0]}{\max\bigl(1, \sum_{i=1}^{n} \mathbb{I}[\hat{p}_i \ge \tau]\bigr)}

To convert an empirical threshold into a finite-sample guarantee before deployment, [10] [11] controls any bounded loss Li(τ)∈[0,1]L_i(\tau) \in [0, 1] that is non-increasing in τ\tau. Conditional selective risk R^sel(τ)\hat{R}_{\text{sel}}(\tau) is not guaranteed monotone in τ\tau, whereas the unconditional false-claim loss Li(τ)=I[p^i≥τ∧yi=0]L_i(\tau) = \mathbb{I}[\hat{p}_i \ge \tau \land y_i = 0] is strictly non-increasing as the acceptance cutoff rises. Averaging Li(τ)L_i(\tau) over an independent calibration split of ncaln_{\text{cal}} claims gives empirical false-claim risk R^cal(τ)=1ncal∑i=1ncalLi(τ)=errors(τ)ncal\hat{R}_{\text{cal}}(\tau) = \frac{1}{n_{\text{cal}}}\sum_{i=1}^{n_{\text{cal}}} L_i(\tau) = \frac{\text{errors}(\tau)}{n_{\text{cal}}}. Selecting the smallest threshold τ^\hat{\tau} satisfying the finite-sample upper bound

Rupper(τ)=ncalR^cal(τ)+1ncal+1=errors(τ)+1ncal+1≤αR_{\text{upper}}(\tau) = \frac{n_{\text{cal}} \hat{R}_{\text{cal}}(\tau) + 1}{n_{\text{cal}} + 1} = \frac{\text{errors}(\tau) + 1}{n_{\text{cal}} + 1} \le \alpha

guarantees E[Ltest(τ^)]≤α\mathbb{E}[L_{\text{test}}(\hat{\tau})] \le \alpha on exchangeable test claims, explicitly accounting for calibration sample size instead of trusting a noisy point estimate (bounding conditional selective risk directly requires non-monotone hypothesis-testing procedures such as Learn-then-Test).

Smooth risk-coverage curves on a 0 to 30 percent unsupported-claim risk scale compare three verification signals from 40 to 92 percent answer coverage. At 70 percent coverage, calibrated NLI holds risk at 5 percent compared to 12 percent for SelfCheck and 19 percent for token probability alone.
Comparing risk-coverage curves across verification signals: combining NLI entailment, consistency, and token probability in a calibrated verifier cuts unsupported-claim risk steeply at fixed answer coverage.
calibrated-nli-conformal-gate.py
def simulate_verification_pairs(n: int, seed: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Generate correlated claim-evidence verification signals and binary ground-truth support."""
    rng = np.random.default_rng(seed)
    nli_logit = rng.normal(loc=0.5, scale=1.9, size=n)
    lexical_overlap = np.clip(0.35 + 0.14 * nli_logit + rng.normal(0.0, 0.16, n), 0.0, 1.0)
    selfcheck_agree = np.clip(0.55 + 0.12 * nli_logit + rng.normal(0.0, 0.18, n), 0.0, 1.0)
    min_tok_prob = np.clip(0.45 + 0.08 * nli_logit + rng.normal(0.0, 0.15, n), 0.02, 0.99)

    true_logit = -0.3 + 1.45 * nli_logit + 1.1 * (lexical_overlap - 0.4) + 1.0 * (selfcheck_agree - 0.5)
    p_supported = 1.0 / (1.0 + np.exp(-true_logit))
    y = rng.binomial(1, p_supported)
    features = np.column_stack([nli_logit, lexical_overlap, selfcheck_agree, min_tok_prob])
    raw_heuristic = 1.0 / (1.0 + np.exp(-(3.2 * nli_logit + 0.7)))  # Overconfident uncalibrated baseline
    return features, y, raw_heuristic

def expected_calibration_error(y_true: np.ndarray, y_prob: np.ndarray, n_bins: int = 8) -> float:
    edges = np.quantile(y_prob, np.linspace(0.0, 1.0, n_bins + 1))
    ece = 0.0
    for i in range(n_bins):
        lo, hi = edges[i], edges[i + 1]
        mask = (y_prob >= lo) & (y_prob <= hi if i == n_bins - 1 else y_prob < hi)
        if np.any(mask):
            ece += np.mean(mask) * abs(float(np.mean(y_true[mask])) - float(np.mean(y_prob[mask])))
    return float(ece)

X_train, y_train, _ = simulate_verification_pairs(400, seed=42)
X_cal, y_cal, raw_cal = simulate_verification_pairs(400, seed=43)
X_test, y_test, raw_test = simulate_verification_pairs(400, seed=44)

calibrator = LogisticRegression(C=1.0)
calibrator.fit(X_train, y_train)
p_cal = calibrator.predict_proba(X_cal)[:, 1]
p_test = calibrator.predict_proba(X_test)[:, 1]

print(
    f"Raw NLI heuristic  | Brier={brier_score_loss(y_test, raw_test):.4f} | "
    f"ECE={expected_calibration_error(y_test, raw_test):.4f} | "
    f"AUC={roc_auc_score(y_test, raw_test):.4f} | "
    f"AP={average_precision_score(y_test, raw_test):.4f}"
)
print(
    f"Calibrated verifier| Brier={brier_score_loss(y_test, p_test):.4f} | "
    f"ECE={expected_calibration_error(y_test, p_test):.4f} | "
    f"AUC={roc_auc_score(y_test, p_test):.4f} | "
    f"AP={average_precision_score(y_test, p_test):.4f}"
)

# Conformal Risk Control on monotone unconditional false-claim loss L_i(tau) = 1[p_i >= tau and y_i == 0]
alpha = 0.05
n_cal = len(y_cal)
thresholds = np.linspace(0.96, 0.50, 47)
selected_tau = 0.96
for tau in thresholds:
    accepted = p_cal >= tau
    errors = int(np.sum((y_cal == 0) & accepted))
    upper_risk = (errors + 1.0) / (n_cal + 1.0)
    if upper_risk <= alpha:
        selected_tau = float(tau)
    else:
        break

print(f"\nSelected Conformal Risk Control cutoff (alpha={alpha:.2f}): tau={selected_tau:.2f}")
for label, cutoff in [("Permissive 0.60", 0.60), ("Conformal gate", selected_tau), ("Strict 0.96", 0.96)]:
    acc = p_test >= cutoff
    cov = float(np.mean(acc))
    uncond_risk = float(np.mean((y_test == 0) & acc))
    sel_risk = float(np.mean(y_test[acc] == 0)) if np.any(acc) else 0.0
    print(f"{label:16s} | cutoff={cutoff:.2f} | test_cov={cov:.3f} | uncond_risk={uncond_risk:.3f} | sel_risk={sel_risk:.3f}")
Output
Raw NLI heuristic  | Brier=0.1220 | ECE=0.1155 | AUC=0.9400 | AP=0.9494
Calibrated verifier| Brier=0.0965 | ECE=0.0359 | AUC=0.9402 | AP=0.9497

Selected Conformal Risk Control cutoff (alpha=0.05): tau=0.75
Permissive 0.60  | cutoff=0.60 | test_cov=0.540 | uncond_risk=0.075 | sel_risk=0.139
Conformal gate   | cutoff=0.75 | test_cov=0.458 | uncond_risk=0.040 | sel_risk=0.087
Strict 0.96      | cutoff=0.96 | test_cov=0.230 | uncond_risk=0.003 | sel_risk=0.011

Look at both halves of the diagnostic output. Replacing an overconfident NLI logit heuristic with multi-feature logistic calibration lowers both Brier score and Expected Calibration Error substantially on unseen queries while preserving strong ranking discrimination (AUC and ). Then, selecting τ^\hat{\tau} conservatively on X_cal keeps unseen unconditional false-claim risk inside the α=0.05\alpha = 0.05 budget while surfacing the corresponding conditional selective risk among served claims.

Mitigation layers across generation and serving

No single intervention removes every hallucination failure mode cleanly, because hallucinations originate across retrieval gaps, decoding variance, and post-generation presentation. Effective production pipelines compose complementary defenses along the execution timeline:

  1. Decoding-time faithfulness amplification: Methods such as DoLa (Decoding by Contrasting Layers) [12] and Context-Aware Decoding (CAD) [13] subtract surface-layer priors from deeper factual layers or contrast context-conditioned logits against unconditioned prior logits: pCAD(yt∣x,D)=softmax⁡ ⁣((1+α)log⁡p(yt∣x,D)−αlog⁡p(yt∣x))p_{\text{CAD}}(y_t \mid x, D) = \operatorname{softmax}\!\bigl((1 + \alpha)\log p(y_t \mid x, D) - \alpha \log p(y_t \mid x)\bigr) Weighting context-dependent probability shifts suppresses fluent clichés memorized from pretraining whenever retrieved context points in a different direction.
  2. Verify-then-edit and independent verification: Chain-of-Verification (CoVe) [14] drafts an initial answer, formulates targeted verification questions for each claim, answers those verification questions independently without leaking the draft's phrasing, and revises only contradicted spans. Isolating verification prevents self-anchoring bias.
  3. Corrective retrieval and reflection tokens: When verifier scores indicate missing context rather than fabrication (C4), triggers a second query rewrite and broader search instead of guessing or immediately refusing, while Self-RAG [15] trains inline critique tokens to signal retrieval need and claim support mid-generation.
  4. Claim pruning vs. calibrated abstention: When core claims hold (C1) and a non-essential modifier lacks support (C2), pruning the unsupported clause preserves high utility without compromising accuracy. When a contradiction hits core logic (C3) or calibrated uncertainty exceeds risk tolerance α\alpha, the triggers fresh retrieval or abstains cleanly.
Bar chart on a 0 to 30 percent scale showing unsupported claim rates dropping cumulatively across layered mitigation stages: 28 percent on unverified RAG drafts, 21 percent with grounded prompting, 14 percent with SelfCheck consistency, 8 percent with atomic claim pruning, and 4 percent with corrective retrieval plus a calibrated verification gate.
Unsupported-claim rates fall cumulatively when prompt grounding, multi-sample consistency filtering, atomic claim pruning, and corrective retrieval plus a calibrated gate work in sequence.
layered-mitigation-benchmark.py
def simulate_pipeline_stages(n_queries: int = 200, seed: int = 42) -> None:
    """Compare unsupported-claim risk, supported recall, and net utility across defense stacks."""
    rng = np.random.default_rng(seed)
    claims_per_query = 4
    total_claims = n_queries * claims_per_query

    # True support: ~72% supported in retrieved docs, ~28% unsupported/fabricated in base drafts
    base_supported = rng.binomial(1, 0.72, size=(n_queries, claims_per_query))
    entail_signal = np.where(
        base_supported == 1,
        rng.normal(0.78, 0.16, size=(n_queries, claims_per_query)),
        rng.normal(0.32, 0.20, size=(n_queries, claims_per_query)),
    )
    consistency = np.where(
        base_supported == 1,
        rng.normal(0.84, 0.12, size=(n_queries, claims_per_query)),
        rng.normal(0.42, 0.24, size=(n_queries, claims_per_query)),
    )

    # Layer 1: Base unverified draft serves all claims
    # Layer 2: Grounded prompt recovers 25% of unsupported claims (~7pp risk drop)
    prompt_supported = np.where(
        (base_supported == 0) & (rng.random((n_queries, claims_per_query)) < 0.25),
        1,
        base_supported,
    )
    prompt_signal = entail_signal + 0.08 * (prompt_supported - base_supported)

    # Layer 3: SelfCheck consistency filter blocks queries with low sample agreement
    sc_keep_query = np.min(consistency, axis=1) >= 0.45

    # Layer 4: Atomic claim pruning removes individual claims with weak entailment
    pruned_keep = prompt_signal >= 0.56

    # Layer 5: Corrective re-retrieval lifts uncertain queries before calibrated gate
    reretrieved_supported = np.where(
        (prompt_supported == 0) & (prompt_signal >= 0.36) & (rng.random((n_queries, claims_per_query)) < 0.60),
        1,
        prompt_supported,
    )
    reretrieved_signal = np.where(
        reretrieved_supported > prompt_supported,
        rng.normal(0.76, 0.12, size=(n_queries, claims_per_query)),
        prompt_signal,
    )
    gate_keep = reretrieved_signal >= 0.64

    configs = [
        ("Base draft", base_supported, np.ones_like(base_supported, dtype=bool)),
        ("Grounded prompt", prompt_supported, np.ones_like(base_supported, dtype=bool)),
        ("SelfCheck filter", prompt_supported, np.repeat(sc_keep_query[:, None], claims_per_query, axis=1)),
        ("Claim pruning", prompt_supported, pruned_keep),
        ("Retry + conformal", reretrieved_supported, gate_keep),
    ]

    false_claim_penalty = 5.0
    for name, truth, served_mask in configs:
        n_served = int(np.sum(served_mask))
        sup_served = int(np.sum((truth == 1) & served_mask))
        unsup_served = int(np.sum((truth == 0) & served_mask))
        risk = unsup_served / max(n_served, 1)
        recall = sup_served / max(int(np.sum(truth == 1)), 1)
        utility = (sup_served - false_claim_penalty * unsup_served) / total_claims
        print(
            f"{name:18s} | unsup_risk={risk:.3f} | recall={recall:.3f} | "
            f"net_utility={utility:+.3f} | served={n_served}/{total_claims}"
        )

simulate_pipeline_stages()
Output
Base draft         | unsup_risk=0.279 | recall=1.000 | net_utility=-0.672 | served=800/800
Grounded prompt    | unsup_risk=0.207 | recall=1.000 | net_utility=-0.245 | served=800/800
SelfCheck filter   | unsup_risk=0.120 | recall=0.533 | net_utility=+0.135 | served=384/800
Claim pruning      | unsup_risk=0.017 | recall=0.833 | net_utility=+0.604 | served=537/800
Retry + conformal  | unsup_risk=0.000 | recall=0.742 | net_utility=+0.627 | served=502/800

Notice the utility swing in that progression. Simply tightening a query-level SelfCheck filter trims risk only partially while sacrificing full-query recall whenever one weak sentence contaminates three solid ones. Decomposing at claim granularity and pairing corrective retrieval with a calibrated verification threshold pushes net serving utility up sharply while driving unsupported-claim leak rates down toward single digits.

Common pitfalls and production telemetry

Even well-calibrated verifiers degrade in production when surrounding infrastructure introduces silent mismatches:

  • Judging the answer instead of its claims: Whole-answer pass/fail rubrics hide bad secondary clauses inside accurate summaries and prevent safe partial pruning.
  • Treating agreement as factual verification: Self-consistency catches unstable hallucinations across draws, yet misses shared parametric misconceptions and stale training cutoffs completely.
  • Unadjusted verifier thresholds under distribution shift: A cutoff tuned on short clean documentation queries breaks when long noisy customer logs enter retrieval; track Brier score and verifier score histograms continuously against labeled audit slices.
  • Verifying against mutable live indexes without version IDs: If an index updates between generation and inspection, later debugging cannot reconstruct why a claim passed or failed. Log document IDs, chunk hashes, verifier probability, pruned claim count, and routing outcome alongside standard OpenTelemetry GenAI semantic spans [17].

Check your understanding

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 7 answered
1.A RAG assistant accurately states from pretraining weights that torch.compile launched in PyTorch 2.0, while none of the retrieved context chunks mention PyTorch 2.0. Under a grounded documentation verification gate, how should this claim be classified and handled?
2.Why can raw token predictive entropy falsely flag a completely accurate RAG answer as uncertain, and how does semantic entropy fix this?
3.A model generates five independent samples at temperature 0.7 claiming that fullgraph=True silently falls back to eager mode, giving zero semantic entropy and 100% SelfCheck agreement. Retrieved documentation states fullgraph=True raises an error. What does this failure demonstrate?
4.An uncalibrated NLI verifier assigns probability 0.90 to a batch of 100 claims, but only 65 of those claims turn out to be supported. What does this gap signal?
5.In Conformal Risk Control over n_cal = 99 calibration claims, you evaluate candidate threshold tau and observe 4 unsupported claims accepted (out of 60 accepted claims overall). Using the finite-sample upper bound (errors + 1) / (n_cal + 1) on unconditional false-claim risk, does tau satisfy a strict target risk alpha = 0.045?
6.A draft response makes two accurate statements backed by retrieved PyTorch docs and adds a third unsupported remark about automatic CUDA graph fusion. Another draft directly inverts fullgraph=True semantics against the retrieved text. Which serving policy is preferable?
7.In Context-Aware Decoding (CAD) with prior weight alpha = 1.0, context probabilities for three candidate tokens are [0.60, 0.30, 0.10] and no-context prior probabilities are [0.20, 0.60, 0.20]. Following p_cad proportional to p_ctx^(1+alpha) / p_prior^alpha, what is the normalized CAD distribution?

7 questions remaining.

References

Why Language Models Hallucinate

Kalai, A. T., Nachum, O., Vempala, S. S., & Zhang, E. · 2025

https://arxiv.org/abs/2509.04664

A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions

Huang et al. · 2023

https://arxiv.org/abs/2311.05232

FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation.

Min, S., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2305.14251

Ragas: Faithfulness

Ragas maintainers · 2026

https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/

Detecting Hallucinations in Large Language Models Using Semantic Entropy

Farquhar, S., et al. · 2024 · Nature

https://www.nature.com/articles/s41586-024-07421-0

Semantic Entropy Probes: Robust and Cheap Hallucination Detection in LLMs

Kossen, J., Han, J., Razzak, M., Schut, L., Malik, S., & Gal, Y. · 2024

https://arxiv.org/abs/2406.15927

SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models.

Manakul, P., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2303.08896

On Calibration of Modern Neural Networks

Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. · 2017

https://arxiv.org/abs/1706.04599

Probability calibration

scikit-learn Developers · 2026

https://scikit-learn.org/stable/modules/calibration.html

A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification

Angelopoulos, A. N. & Bates, S. · 2021

https://arxiv.org/abs/2107.07511

Conformal Risk Control

Angelopoulos, A. N., Bates, S., Fisch, A., Lei, L., & Schuster, T. · 2022 · arXiv preprint

https://arxiv.org/abs/2208.02814

DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language Models

Chuang, Y.-S., Xie, Y., Luo, H., Kim, Y., Glass, J., & He, P. · 2024 · ICLR 2024

https://arxiv.org/abs/2309.03883

Trusting Your Evidence: Hallucinate Less with Context-aware Decoding

Shi, W., Han, X., Lewis, M., Tsvetkov, Y., Zettlemoyer, L., & Yih, W.-t. · 2024 · NAACL 2024

https://aclanthology.org/2024.naacl-short.69/

Chain-of-Verification Reduces Hallucination in Large Language Models

Dhuliawala, S., et al. · 2024 · Findings of ACL 2024

https://aclanthology.org/2024.findings-acl.212/

Self-RAG released short-form inference scorer (pinned source)

Asai, A., et al. · 2023

https://github.com/AkariAsai/self-rag/blob/1fcdc420e48f50a7d7ab1ece5494221b93252e99/retrieval_lm/run_short_form.py#L134-L157

TruthfulQA: Measuring How Models Mimic Human Falsehoods.

Lin, S., et al. · 2021 · ACL 2022

https://arxiv.org/abs/2109.07958

OpenTelemetry GenAI Semantic Conventions

OpenTelemetry Authors · 2026

https://github.com/open-telemetry/semantic-conventions-genai

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.