What an LLM is, and what it is not
A next-token sampler trained on most of the written internet: why it sounds right when it is wrong, and what that means for everything you build on it
A small chat model, asked to summarise a paper you invented a minute ago, replies that it cannot find the paper. You then give the same model the paper's citation followed by 'Abstract.' as plain text, with no chat formatting, and let it continue. What does it write?
A large language model does one thing. Given a sequence of tokens, it outputs a probability for every token in its vocabulary being the next one. Everything else, from chat to code generation to agents that book flights, is that one operation run in a loop with some software around it.
This chapter takes the loop apart. You will see where the randomness comes from and how to control it, why the output sounds authoritative whether or not it is true, what instruction tuning changed, and which jobs to give a model and which to keep away from it. The lab makes each claim visible on your own laptop with a local model, then compares a hosted Claude model on the same prompts.
The one thing a language model does
Text goes in as tokens: integer ids for pieces of words. The next chapter covers how text becomes tokens; for now, think of a token as roughly three quarters of an English word. A model like Llama 3.2 3B has a vocabulary of 128,256 tokens.
The model is a function. Its input is the token sequence so far. Its output is a vector of 128,256 numbers called logits, one per vocabulary entry. A softmax turns the logits into probabilities that sum to 1. That is the whole interface. Inside, the function is a transformer with a few billion learned weights, which chapter three opens up, but from the outside it is a very expensive way to answer “what comes next?”
Generation is a loop around that function:
- Run the model on the tokens so far and get a distribution over the next token.
- Pick one token from that distribution. This is sampling, and it is where every interesting behaviour in this chapter comes from.
- Append the chosen token to the input.
- Repeat until the model emits a special end-of-sequence token or you hit a length limit.
Three consequences follow directly from the loop, and you will meet each of them in production.
Output is produced one token at a time, left to right. The model cannot go back and revise an earlier token. If it commits to “The answer is 7” in the first few tokens, the rest of the response is conditioned on having said 7. Asking a model to reason before answering helps for exactly this reason: the reasoning tokens become part of the input that the answer is conditioned on.
Each token costs a full pass through the model. A 500-token answer is 500 sequential forward passes. That is why output tokens are slower and more expensive than input tokens, which the model can process in parallel. Chapter two puts prices on it.
The model has no state between calls. The loop’s only memory is the token sequence. A chat that “remembers” your name does so because the application re-sends the whole conversation every turn. Chapter two puts a cost on that too.
Sampling: turning probabilities into text
Step 2 of the loop, picking a token, is not part of the model. It is a few lines of code with settings, and those settings change the behaviour more than most prompt edits do.
Greedy decoding always takes the most probable token. It is deterministic: the same input gives the same output, on the same hardware and software. It is also prone to loops and bland text. Holtzman and colleagues showed in 2019 that maximising likelihood produces text that is measurably less human than sampling, with repetition being the most visible symptom.
Temperature reshapes the distribution before sampling. The logits are divided by a number T, then the softmax is applied: p_i = exp(z_i / T) / sum_j exp(z_j / T). With T below 1 the gaps between logits grow, so the top token gets more of the probability. With T above 1 they shrink, and unlikely tokens get picked more often. T = 0 would divide by zero, so implementations treat it as greedy.
A worked example. Suppose the top three logits for the token after “The capital of France is” are 9.0 for “ Paris”, 6.5 for “ a” and 6.0 for “ the”.
| Temperature | P(” Paris”) | P(” a”) | P(” the”) |
|---|---|---|---|
| 0.5 | 0.991 | 0.007 | 0.002 |
| 1.0 | 0.88 | 0.07 | 0.04 |
| 1.5 | 0.76 | 0.14 | 0.10 |
(Probabilities over these three tokens only; the remaining vocabulary takes a small share in practice.) At 1.5, roughly one run in four starts with something other than “ Paris”. That is not the model “being creative”; it is a dice roll you configured.
Top-k keeps only the k most probable tokens and renormalises. Top-p (nucleus sampling, from the same Holtzman paper) keeps the smallest set of tokens whose probabilities sum to at least p. Both cut off the long tail of the vocabulary, where tens of thousands of individually unlikely tokens together hold enough probability to derail a sentence. Ollama’s defaults are temperature 0.8, top_k 40 and top_p 0.9; you pass overrides in the request’s options.
Seeds make sampling reproducible. Ollama’s seed option fixes the random number generator, so the same prompt, settings and seed give the same text on the same build. Change the model version, the hardware or the batch it shares a GPU with, and that guarantee goes away.
Hosted APIs increasingly take these knobs away from you. Current Claude models (Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5 among them) reject non-default temperature, top_p and top_k values, and from API version 2026-10-21 a Messages request that sends any of the three gets a 400 error on every model. The provider decides how its model is sampled, and you steer behaviour with instructions, examples, structured output and the effort setting instead. That is a good reason to understand sampling on a local model, where you can still see it.
What sampling settings cannot do is make the model more correct. Temperature 0 picks the single most probable continuation. If the model’s most probable continuation is a wrong fact, greedy decoding gives you that wrong fact every time, reproducibly. Low temperature buys consistency, not accuracy.
Fluency is not knowledge
A model is trained on trillions of tokens of text with one objective: make the next token in the training data more probable. That objective rewards anything that helps prediction. Grammar helps, so the model learns grammar. Knowing that Paris is the capital of France helps predict text about France, so a version of that fact ends up encoded in the weights. Knowing what a confident legal citation looks like helps predict legal briefs, so that is learned too.
Notice what the objective does not reward: distinguishing the facts it encoded well from the ones it encoded badly. A fact seen ten thousand times in training is stored robustly. A fact seen twice is stored as a blur. A fact never seen is not stored at all. But in all three cases the model is equally good at producing text with the form of an answer, because form was seen billions of times. The fluency is uniform; the knowledge underneath it is not.
This is why fluency is a bad signal of correctness. In human writing, a precise, well-structured, confident paragraph is weak evidence that the writer knows the subject. In model output it is no evidence at all. Every answer is precise, well-structured and confident.
Two further limits come from the training data itself:
- A cutoff. The model knows nothing written after its training data was collected. It does not know today’s date, the current version of your library, or last week’s price change. Llama 3.2’s knowledge stops at the end of 2023. A well-tuned model asked directly about 2025 says so; asked indirectly, or in a form its tuning did not cover, it answers with the pattern of what such an answer would look like.
- No source. The weights do not record where a fact came from. The model cannot tell you which document taught it something, and when it cites one, the citation is generated the same way as everything else.
Hallucination is the default
“Hallucination” names the case where the model states something false with the same confidence as something true. It is tempting to treat it as a bug to be fixed in the next model version. It is better understood as the default behaviour of the mechanism.
At every step the sampler must emit some token. There is no “I don’t have this” branch in the loop, only a distribution over tokens. When the question is about something the model encoded well, the distribution is sharp and points at the right answer. When it is about something the model never saw, such as a paper you made up, the distribution is still a distribution, and whatever is sampled from it is written out in the same register as everything else.
Kalai and colleagues argued in 2025 that this is reinforced by how models are trained and scored. Most benchmarks give one point for a right answer and zero for both a wrong answer and “I don’t know”. Under that scoring a guess always has a higher expected score than an abstention, so a model optimised against those benchmarks learns to guess. A student who never leaves an exam question blank does the same thing for the same reason.
Models do get better at abstaining. Post-training (chapter four) teaches a model to say it does not know, and even the 3B model in the lab now declines when asked directly about a paper it cannot find. That is a learned behaviour on top of the sampler, not a change to it. It triggers on the situations it was trained on, such as a user asking about an unfamiliar title, and not on others: the same model will continue a fake citation into a fake abstract, and will answer a letter-counting question with a confident wrong number, because that question does not look like one it should refuse. Larger models fail less often, and when they fail it is harder to spot, because the wrong answers that remain are the ones that look most like right answers.
So the engineering stance is: assume any factual claim from a model is unverified until something outside the model has checked it. The rest of this course is largely about that something: retrieval that puts the source in front of the model (module three), citations you can check, evaluations that measure the error rate, and code that validates outputs before they reach a user.
What instruction tuning changes
A model straight out of pretraining is a base model. It continues documents. Give it “What is the capital of France?” and it might continue with “What is the capital of Germany? What is the capital of Spain?”, because on the internet a question is often followed by more questions, as in a quiz.
The models you call through APIs are instruction-tuned (also called chat or instruct models). After pretraining, they are trained further on examples of conversations in which an assistant follows instructions, and then on human or AI preferences between candidate answers. Chapter four covers how. The effects you see:
- A chat format. The conversation is serialised into one token sequence with special tokens that mark who is speaking: system, user, assistant. The model has learned that after the assistant marker comes a helpful reply. Ollama’s
/api/chatand the Anthropic Messages API both apply this template for you. - Instruction following. The model does what the user asks rather than continuing the user’s text.
- Trained dispositions. A tendency to be helpful, to refuse some requests, to admit uncertainty, to format answers with headings and lists. These are learned preferences, not rules. They can be strong or weak, and they vary between models and versions.
What instruction tuning does not change is the loop. It is still next-token prediction with a sampler. A polite, well-formatted wrong answer is still a wrong answer.
Model, API, product, agent
The word “LLM” gets used for four different things, and confusing them leads to bad decisions about cost, privacy and failure modes.
| Layer | What it is | Example | What you control |
|---|---|---|---|
| Model | A file of weights plus the architecture to run them | llama3.2:3b, 2.0 GB on disk |
Everything: hardware, sampling, context size, where the data goes |
| API | A hosted endpoint that runs a model for you and bills per token | Anthropic Messages API with claude-opus-5-5 |
The request: messages, system prompt, tools, max_tokens, effort. Not the weights, not some sampling settings |
| Product | An application that wraps an API with prompts, tools, retrieval, memory and a UI | Claude.ai, ChatGPT, your support bot | Whatever its builders exposed; you see none of the hidden prompts or tools |
| Agent | A loop in which the model chooses actions (tool calls), sees their results and decides again | A coding agent that edits files and runs tests | The tools, permissions and budget you give it |
When someone says “the model did X”, ask which layer did it. “ChatGPT searched the web” is the product. “Claude refused” might be the model’s training or the API’s safety layer. “The agent deleted the table” is the loop plus the permissions someone granted. Most production incidents in AI systems live in the product and agent layers, around a model that did what models do.
Good at, bad at
The mechanism predicts the strengths and weaknesses fairly well.
| Good at | Why |
|---|---|
| Transformation: rewrite, translate, reformat, change tone, convert prose to JSON | The answer is mostly present in the input; the model supplies form, which it is best at |
| Synthesis: summarise, compare, draft from notes | Same: the facts are in the context, the model arranges them |
| Soft classification: sentiment, intent, topic, “is this a complaint?” | Fuzzy categories that are hard to write rules for but easy to show by example |
| Generating plausible candidates: names, test cases, first drafts of code | Plausibility is the training objective |
| Bad at | Why | What to do instead |
|---|---|---|
| Exact arithmetic on long numbers | Digits are split into tokens unevenly; the model predicts digits rather than computing them | Extract the numbers with the model, compute in code |
| Counting characters, words or items | The model sees tokens, not characters; “strawberry” may be two or three tokens | Count in code |
| Recent or niche facts | Training cutoff; facts seen rarely are stored as a blur | Retrieve the source and put it in the context |
| Consistency across calls | Sampling, plus sensitivity to small changes in wording | Structured output, validation, fewer free-text decisions |
| Knowing what it does not know | The objective rewards plausible output, and the sampler always emits something | Grounding, citations you check, evaluation of the error rate |
The pattern behind the second table: when correctness is checkable by a computer, let the computer check it. Use the model for the part that is hard to write code for (understanding messy input, producing readable output) and use code for the part that has one right answer.
Working rules
You will refine these throughout the course. They are enough to stop the most common mistakes today.
- Treat model output as untrusted input. Validate structure with a schema, validate facts against a source, validate numbers in code. Never pass model output straight into a SQL query, a shell or a payment.
- Put the facts in the context. A model answering from its weights is recalling. A model answering from a document you supplied is transforming, which is the thing it is good at.
- Measure the error rate. “It worked when I tried it” is one sample from a distribution. Module three builds the evaluation sets that tell you how often it fails.
- Pin and record settings. Model id, sampling settings, prompt version. When behaviour changes, you need to know which of them moved.
You will stream tokens from a local model, vary the temperature and watch the distribution show through, catch the model inventing a paper, and then put the same questions to a hosted Claude model. Steps 1 to 4 run offline and cost nothing.
1. Set up the project and pull the model.
Every AI lab in this course lives under labs/ai/ in your ATLAS checkout and shares one uv project, labs/ai/pyproject.toml, which you create now. Later chapters add their packages to it with uv add and work in a subdirectory of labs/ai/; uv run finds the project from any subdirectory. Run this from the root of the checkout:
ollama pull llama3.2:3b
mkdir -p labs/ai && cd labs/ai
uv init --bare --python 3.12 # writes only pyproject.toml
uv python pin 3.12 # .python-version, so every lab runs on 3.12
uv add requests anthropic
mkdir -p sampler && cd sampler # this chapter's files go hereCheck the model answers through the REST API, which listens on port 11434:
curl -s http://localhost:11434/api/generate -d '{"model": "llama3.2:3b", "prompt": "Say hello in Yoruba.", "stream": false}' | python3 -m json.tool | head -20response field holding the answer, done: true, and counters: prompt_eval_count (input tokens), eval_count (output tokens), and durations in nanoseconds. The pull downloads about 2.0 GB once; the first request takes a few seconds longer while the model loads into memory.2. Stream a completion token by token.
Create llm.py. It is the helper every later step imports:
import json, requests
URL = "http://localhost:11434/api/generate"
def generate(prompt, temperature=0.8, num_predict=200, raw=False, show=True, **extra):
# extra: any other Ollama option, e.g. seed=42, top_k=40, top_p=0.9
options = {"temperature": temperature, "num_predict": num_predict, **extra}
body = {"model": "llama3.2:3b", "prompt": prompt, "raw": raw, "options": options}
text, final = "", None
with requests.post(URL, json=body, stream=True, timeout=300) as r:
r.raise_for_status()
for line in r.iter_lines():
chunk = json.loads(line)
text += chunk["response"]
if show:
print(chunk["response"], end="", flush=True)
if chunk["done"]:
final = chunk
return text, final
if __name__ == "__main__":
_, f = generate("Explain in three sentences what a transformer language model does.")
tps = f["eval_count"] / f["eval_duration"] * 1e9
print(f"\n\ninput tokens: {f['prompt_eval_count']} output tokens: {f['eval_count']} {tps:.0f} tokens/s")uv run python llm.pyinput tokens: 37 output tokens: 90 73 tokens/s. Each JSON line from the server is one sampled token appended to the text. The input count is larger than the words in your prompt because the server wrapped it in the model’s chat template. On an Apple-silicon laptop expect roughly 20 to 80 tokens per second; on an older CPU-only machine, under 10.3. Vary the temperature.
Create temps.py:
from llm import generate
prompt = "Complete with one short phrase and nothing else: The best thing about living in Lagos is"
for t in (0, 0.7, 1.5):
print(f"--- temperature {t}")
for _ in range(5):
text, _ = generate(prompt, temperature=t, num_predict=25, show=False)
print(" ", repr(text.strip()[:80]))uv run python temps.py'the energy of the city.' five times: greedy decoding picks the same top token at every step. At 0.7, several distinct phrasings circling the same few ideas (energy, culture, street life, hospitality). At 1.5, five different lines with a wider vocabulary and looser format: capitalised, quoted, sometimes not quite a completion of the sentence. The model is the same in all fifteen runs; only the dice changed. Run the script twice: the temperature-0 lines match across runs, the others do not.4. Ask for something it cannot know, two ways.
Create confabulate.py. It asks about a paper that does not exist, first as a chat question, then as the start of a document for the model to continue. raw=True tells Ollama to skip the chat template, so the model sees bare text with no user or assistant markers. It also asks a question whose answer is checkable:
from llm import generate
questions = [
"Summarise the 2021 paper 'Recursive Gradient Folding for Sparse Tokenisers' by Adeyemi and Kowalski. Include its main result.",
"How many r's are in 'strawberry raspberry'? Answer with a number only.",
]
document = ("Adeyemi, T. and Kowalski, M. (2021). Recursive Gradient Folding for "
"Sparse Tokenisers.\n\nAbstract. ")
if __name__ == "__main__":
for q in questions:
print(f"\n### chat: {q}")
for run in range(3):
text, _ = generate(q, temperature=0.7, num_predict=120, show=False)
print(f"[run {run + 1}] {text.strip()[:300]}")
print("\n### raw continuation of a citation")
for run in range(3):
text, _ = generate(document, temperature=0.7, num_predict=120, raw=True, show=False)
print(f"[run {run + 1}] {text.strip()[:300]}")uv run python confabulate.pystraw and berry, not letters, and the abstention it learned for unknown papers never triggers, because the question looks answerable. The raw continuation drops the caution entirely: each run writes a fluent abstract (“We propose a novel sparse tokeniser…”) with a different invented method. Same weights, same paper; the only change is whether the text looks like a chat turn or a document.5. Ask a hosted model the same questions.
This step calls the Anthropic API with claude-opus-5-5 at low effort. Two short questions use a few hundred input tokens and up to a thousand or two output tokens including thinking, at $4 per million input and $20 per million output tokens: about $0.01 to $0.04 per run. Create claude_compare.py:
import anthropic
from confabulate import questions
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
total_in = total_out = 0
for q in questions:
print(f"\n### {q}")
with client.beta.messages.stream(
model="claude-opus-5-5",
max_tokens=4000,
output_config={"effort": "low"},
# if a safety classifier declines, retry on a fallback model (the API chapter explains)
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
messages=[{"role": "user", "content": q}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print(f"\n[stop_reason={final.stop_reason}]")
total_in += final.usage.input_tokens
total_out += final.usage.output_tokens
cost = total_in * 4 / 1e6 + total_out * 20 / 1e6
print(f"\ninput {total_in} tokens, output {total_out} tokens, about ${cost:.4f}")The script imports the question list from confabulate.py; the __main__ guard there stops the local runs from repeating. Then:
export ANTHROPIC_API_KEY=sk-ant-...
uv run python claude_compare.pytemps.py, change the temperatures to (3.0,) and run it. Surprisingly, the lines stay mostly readable. Ollama’s defaults, top_k 40 and top_p 0.9, cut the vocabulary down to a few dozen plausible tokens before the temperature-flattened draw, so even a wild temperature can only pick among sensible words. Now pass top_k=1000, top_p=1.0 in the generate call: the output turns into fragments and punctuation salad such as '".Knowing-how-good-eye-crèle.... _let-it fade]', because the tail of unlikely tokens finally gets its share. Finally set top_k=1 at the same temperature: five identical lines again, because one candidate leaves nothing to draw. Temperature is one stage in a pipeline of filters, and the setting that looks like it controls randomness is not the only one that does.Template
# AI feature fit assessment: <feature>
Owner: <name, role>. Date: <date>. Approver: <name, role>.
Decision needed: <build, build in part, or do not build; from whom, by when>.
Out of scope: <what this assessment does not cover>.
## 1. What the feature must do
<one paragraph: the user, the input, the output, and which outputs must be exactly right>
## 2. How a model would fail here
| Failure | Why the mechanism produces it | Evidence (lab output, eval run or assumption) | Cost if it reaches a user |
## 3. The non-model alternative
<what you would build without a model, what it costs, where it breaks>
## 4. Verdict
<model for which part, code for which part, a person for which cases>
## 5. How success would be measured
| Measure | Target | Test set and size | Who runs it, how often |
Rollback: <the number that switches the feature off, and who flips it>
## 6. How this could be wrong
<one way, and what would show it> WORKED EXAMPLE
The product manager for a finance tool writes this at a real company; the head of finance approves it before engineering starts. The feature is the chapter’s invoice job: a model reads 10,000 supplier invoices a month and replies with the VAT total for the quarterly return.
Header. Owner: product manager, finance tools. Date: 20 November 2026. Approver: head of finance. Decision needed: build in part, or do not build, before next quarter’s engineering plan is fixed. Out of scope: filing the return, foreign-currency invoices and choosing VAT rates (finance supplies the rate table).
Must do. Read PDFs of varying layouts and give each line item and its net amount. The totals go on a tax return, so they must be exact.
How a model fails. It predicts digits instead of computing them. The lab shows the mechanism on counting: asked how many r’s are in ‘strawberry raspberry’, two local sets of runs gave 9, 9, 8 and 12, 10, 7. The answer is 6. Sums fail the same way. Temperature 0 gave five identical lines in step 3, so it makes an answer repeatable, not right. The prototype matched a calculator on 20 invoices, which says little about 10,000.
Alternative. One parser per supplier layout, plus code for the arithmetic. It is exact but breaks when a supplier changes template.
Verdict. The model extracts line items as JSON. Code sums them, applies VAT and compares with the printed total. A mismatch goes to a person.
Measured by. Assumed: 200 hand-checked invoices as the test set. Targets: line items correct on at least 98%, and every mismatch caught. Assumed cost: 1,500 input and 300 output tokens an invoice at $4 and $20 per million, which is $0.012, or $120 a month. Rollback (assumed): if a monthly sample of 50 finds a wrong total, extraction is switched off.
Could be wrong. The printed total may itself be wrong. A sample where code and printed total agree but a person disagrees would show it.
Now you
You are the product manager at Owoleaf, whose support assistant answers customers from the help-centre page ‘Fees and limits’. Support proposes a feature: the assistant tells a customer the exact fee for a transfer and the date a failed card top-up will be refunded. The page gives transfer fees in bands (₦10 up to ₦5,000, ₦25 from ₦5,001 to ₦50,000, ₦50 above) and says a failed top-up is refunded to the same card within 5 business days, or up to 14 for cards issued outside Nigeria. Use the lab: step 4 shows a model giving confident wrong numbers that change between runs, and step 3 shows what temperature does and does not fix. Decide which parts need a model, which need a lookup in code, and how you would measure it. The support lead reads your assessment to decide whether to fund the build, and the head of engineering approves it.
Self-check
Finance wants a tool that reads 10,000 supplier invoices a month (PDFs of varying layouts), pulls out each line item and its net amount, and produces the VAT total per supplier for the quarterly return. A colleague has a prototype prompt that asks the model to read an invoice and reply with the VAT total. It matched a calculator on the 20 invoices they tried. What do you build?
- TALK [1hr Talk] Intro to Large Language Models Andrej Karpathy, 2023
The best hour-long mental model of what an LLM is: a lossy compression of the internet plus a small program that runs it. Watch the first 40 minutes; the security section at the end is covered later in this course.
- POST What Is ChatGPT Doing … and Why Does It Work? Stephen Wolfram, 2023
Builds next-token prediction from word counts upwards, with plots of real probability distributions and the effect of temperature. Read up to the section on neural nets; the later material overlaps with chapter three.
- PAPER The Curious Case of Neural Text Degeneration Holtzman, Buys, Du, Forbes, Choi, 2019
Why greedy decoding produces repetitive text and why sampling from the full distribution produces nonsense, and the nucleus (top-p) sampling that sits between them. The figures alone explain most sampler settings. Read: sections 1 to 3 and figure 1; skip the detailed evaluation.
- PAPER Why Language Models Hallucinate Kalai, Nachum, Vempala, Zhang, 2025
Makes the case that hallucination follows from the training objective and from benchmarks that reward guessing over abstaining, which is the stance this chapter takes. Read: sections 1 and 4 (the argument about evaluation scoring); skim the formal results in between.
- TALK Large Language Models explained briefly 3Blue1Brown (Grant Sanderson), 2024
Eight minutes, beautifully animated: next-token prediction, pretraining and instruction tuning. Good to send to a colleague who needs the picture without the maths.
- DOC Ollama API reference
The endpoints the lab uses: /api/generate and /api/chat, the options object (temperature, top_k, top_p, seed, num_predict, num_ctx), and the timing counters on the final streamed object. Skip the model management endpoints for now.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.