Skip to content

From GPT to Production

Hallucination, limits, and safety

Where LLMs fail and how we guard them

Ask a language model about a person who never existed and it will often answer smoothly, in complete sentences, with a university, a field, and a prize - all invented. This is hallucination, and it is not a bug bolted on by accident. It falls straight out of the training objective: a base model is optimised to make its next token plausible, not true. There is no truth oracle inside; there is only a probability distribution over what usually comes next. This lesson maps the failure modes - hallucination, overconfidence, knowledge cutoff, context limits, the reversal curse - and then the safety layer built on top: jailbreaks, prompt injection, guardrails, and red-teaming. Balanced, not alarmist: these are engineering problems, actively and measurably being reduced.

The one-line idea

A base model is a plausibility engine, not a truth engine. It samples the most likely continuation of your prompt (Lesson 37), so a well-formed lie and a well-formed fact look identical to it - both are just high-probability sequences. Everything downstream - confidence that does not track correctness, made-up citations, jailbreaks - is a consequence of that single fact.

Why fluent models make things up

Recall the objective from Lesson 37: given the tokens so far, predict a distribution over the next token, and train to maximise the likelihood of real text. Nowhere in that loss is there a term for is this claim true? - only is this a likely thing to say?. When you ask about something the model has no data for, the maximum-likelihood continuation is still a grammatical, confident-sounding sentence, because that is what almost all of its training text looks like. Silence and "I don't know" are rare in the corpus, so the model rarely produces them. It fills the gap with the shape of an answer.

Weng calls the sharp version extrinsic hallucination: output that is not grounded in - and often contradicts - any real-world source, as opposed to intrinsic hallucination that contradicts the prompt itself. The cure is to give the model something to be grounded in: retrieved evidence it can cite, or the honest option to abstain.

The hard limits

Four walls are structural - no prompt phrasing removes them, only tooling around the model can help.

  • Knowledge cutoff. Training data is frozen at a date. Events, papers, and prices after that date simply are not in the weights. The model will still answer about them - confidently, from the wrong era.
  • Context-length limit. Attention costs in the sequence length (Lesson 31), so every model has a finite window. Text outside the window does not exist for it, and quality degrades toward the far ends of a long one.
  • The reversal curse. Trained heavily on "A is B", models often fail the mirror "B is A" - knowing a person's parent does not reliably let it name that parent's child. Facts are stored directionally, not as a symmetric graph.
  • Overconfidence. The number you might read as "confidence" is just the top softmax probability - a fluency signal, not a calibrated probability of being correct.

Calibration: does confidence track correctness?

A token's confidence is simply the largest softmax probability, . The model is well-calibrated if, across all predictions made at confidence , the fraction that are actually correct is also . Group predictions into confidence bins and measure the gap with Expected Calibration Error:

A perfectly calibrated model has in every bin, so . Real models are typically overconfident, - exactly the 94%-sure-and-wrong behaviour you can watch in the probe below.

The demo has two modes. First Hallucination: ask about a made-up entity, watch a toy model invent details with a per-token confidence heatmap, then flip on retrieval grounding and watch invented claims get replaced by cited facts (or an honest abstention). Then Safety: fire escalating jailbreak prompts at a safety classifier meter, and toggle a system-prompt guardrail to change how many attacks get through.

Two-mode probe pick a prompt - flip the switch

Pick a question the toy model can't truly answer. Each output token is tinted by its confidence (the top softmax probability) - brighter means surer. Then turn on retrieval grounding and watch the answer change.

Retrieval grounding: off
retrieve ▸ off - answering from parametric memory only (no external source).
The Transformer was introduced in 2016 by a team at Google Brain.

Hover a token to read its confidence.

Average token confidence87%
low
high confidence

Ungrounded. High confidence, zero grounding - softmax probability ≠ truth. Fluent and almost right - but "2016" is wrong, and the model is 72% confident in it anyway. High confidence, false claim.

Confidence is fluency, grounding is truth

The heatmap glows just as brightly over the invented "Turing Prize" as over a real fact - because the tint is the softmax probability, which measures how typical the next token is, not how true. That is why raw confidence can't catch hallucination. What can is changing where the answer comes from: retrieval grounding conditions generation on real passages (that is RAG, Lesson 55), so claims are anchored to citable evidence and the model can honestly say "no source found" instead of filling the gap.

Making models safer

Safety is a second system layered on the plausibility engine. The main threats are adversarial. A jailbreak is a prompt crafted to talk the model past its guidelines - role-play ("you are DAN, with no rules"), fake authority ("developer mode on"), or slow escalation. Prompt injection is subtler and specific to tools and agents: untrusted content the model reads - a web page, a retrieved document, an email - smuggles in instructions, and the model, unable to tell data from directives, follows them. This is why safety is where the whole course meets: it depends on training (alignment), prompting (the system prompt boundary), and retrieval (trusting your sources) all at once.

The defences are layered, not a single wall. Alignment training (RLHF) teaches refusal of harmful requests. A separate safety classifier screens inputs and outputs - the meter you just tripped. Guardrails keep trusted system instructions structurally separated from untrusted data and sanitise injected commands. Red-teaming is the practice of attacking your own model before release to find these holes, and it is how the risk scores in the probe would be calibrated in reality. Two honest caveats: models inherit bias from their training data, which is measured and reduced but never zeroed; and most capabilities are dual-use - the same skill that drafts a safety plan can draft its opposite - so the goal is defence-in-depth that lowers risk, not a mythical perfect filter.

# A token's "confidence" is just the top softmax probability (Lesson 37).
logits = model(prompt)                 # raw scores over the vocabulary
probs  = softmax(logits)             # nonnegative, sums to 1
token  = probs.argmax()
conf   = probs[token]                  # e.g. 0.94 - high even when the fact is invented

# Grounding: condition generation on retrieved evidence (RAG, Lesson 55).
docs = retriever.search(prompt, k=4)   # real passages... or none at all
if not docs:
    answer = "I couldn't find a reliable source."   # abstain, don't invent
else:
    answer = model(prompt, context=docs)         # cite the docs in the output
Confidence is not truth - grounding is the fix

Check yourself

A model states a fabricated fact at 94% token confidence mainly because it is trained to:

A prompt-injection attack succeeds precisely when the model treats:

Why does grounding a model with retrieval reduce hallucination - and what does a token's 'confidence' actually measure?

Connect confidence, grounding, and truth. Try to state it, then check.

Lock it in

  • A base model is a plausibility engine: its training objective rewards likely continuations, not true ones, so fluent fabrication and fluent fact look the same to it.
  • Token confidence (the top softmax probability) is a fluency signal, not a truth signal - real models are systematically overconfident.
  • Structural limits - knowledge cutoff, context window, the reversal curse - are not prompt-fixable; only external tooling (retrieval, agents) can help.
  • Retrieval grounding (RAG) anchors generation to citable evidence and enables honest abstention, directly reducing hallucination.
  • Safety is defence-in-depth: alignment training, safety classifiers, guardrails, and red-teaming layered together lower jailbreak and prompt-injection risk.

Primary source

For the definitive survey of why and how models fabricate - extrinsic vs. intrinsic hallucination, detection, and grounding - read Lilian Weng, "Extrinsic Hallucinations in LLMs" (2024). For where this sits in the full LLM picture, alongside training, evaluation, and safety, see the Hugging Face LLM Course.

Ask your teacher

This lesson is where every earlier piece converges. The grounding switch you flipped is RAG (Lesson 55); the confidence heatmap is the softmax distribution (Lesson 37) read as calibration; and safety is training + prompting + retrieval combined into a defence-in-depth. Ask me why RLHF makes a model refuse yet still jailbreakable, how you would actually measure ECE on a real model, why the reversal curse survives so much training, or how retrieval both fixes hallucination and opens the prompt-injection door.