#How LLMs work questions
AddedThis page is for the last few days before an interview, when you no longer need to learn a topic but need to say it well, quickly. Every question here is one an interviewer might ask about building with language models, or one you should be able to answer for yourself in the middle of a design. The first paragraph of each answer is the version you'd say out loud: 30 to 90 seconds, with the decision first and the reason straight after. The walkthrough under it is the reasoning you need when the follow-up is "why?", and the link at the end goes to the topic that teaches it properly.
Think of it as a deck of flashcards with the working shown. Read the question, close your eyes, answer it in your own words, then open the answer and compare: did you name the mechanism, the number or limit that drives the decision, and what goes wrong in production? If one of the three is missing, that's the card to go back to. The cost and sizing questions have small runnable models; their output was produced on Node 26 and is re-checked every time the site is validated, so you can trust the arithmetic and concentrate on the reasoning. Prices in them are Anthropic's published API prices as listed in December 2026.
This first group covers what a model does with a prompt: tokens, the generation loop, sampling, context, training, reasoning and hallucination.
Show answer
The model predicts one token at a time, in a loop. "My system prompt and messages are flattened into one token sequence. The model maps that sequence to a probability for every token in its vocabulary; the server picks one, appends it, and runs the model again, until an end-of-turn token or max_tokens. That's why replies can be streamed, why the model has no memory between calls, and why everything it knows is either in its weights or in the context I send."
- Tokenise: text becomes integer token ids. The model never sees letters or words, only ids.
- One forward pass gives a probability distribution over the whole vocabulary for the next position.
- Pick, append, repeat: generation is autoregressive. Each new token depends on all the earlier ones, so output is produced strictly left to right.
- Stop: the model emits its end-of-turn token, or the server stops at
max_tokens, which cuts the reply off mid-thought. - The follow-up is usually "so where's the memory?" There isn't any: each API call starts from the tokens in that request, which is why your application resends the conversation every turn.
Learn more: What a large language model is and Next-token prediction and the generation loop.
Show answer
Because it never sees the letters. "The tokenizer turns the word into a token id before the model runs, so the model gets an integer, not ten characters. To answer it has to recall the spelling from training text and count, which is error-prone. In an application I don't ask a language model to do character-level work: I do it in code or give the model a tool. The same thing explains weak arithmetic on long numbers, because digits are grouped into chunks."
- Tokenizers are built by merging frequent byte sequences, so a common word is often one token, and a rare word is several pieces.
- The model's input is that id sequence. Nothing about the id for a word says which letters it contains.
- Models often get famous examples right, by reasoning it through or because the question appeared in training. That isn't the same as being able to do it.
- The engineering answer is the important part: counting, exact string operations and arithmetic belong in code or a tool call, with the model deciding when to use them.
- Tokens are also the unit of billing and of context size, so the same concept answers "why is my bill in tokens?".
Learn more: Tokens and tokenizers.
Show answer
Input is processed in one parallel pass; output is generated one token at a time. "The whole prompt goes through the model at once, but each output token needs its own pass that depends on the previous one, so it ties up the hardware for far longer per token. Claude's output price is five times its input price on every current model. For latency: time to first token grows with the prompt, total time grows with output length. So the biggest latency lever is usually a shorter output."
- Prefill handles all input tokens together; decode is sequential by construction.
- Pricing reflects that: on Claude Opus 5.5, $4 per million input tokens against $20 per million output.
- Even so, most applications spend more on input, because there's so much more of it: long context in, short answer out. Check the split before optimising.
- Latency has two parts with different fixes: time to first token (prompt size, model size, caching) and generation time (output tokens divided by tokens per second).
- Streaming doesn't make generation faster. It lets the user start reading at the first token.
Learn more: Next-token prediction and the generation loop.
Show answer
By making the task well-specified, not by turning a knob. "Current Claude models don't accept temperature, top_p or top_k at all, and even greedy decoding isn't guaranteed repeatable on a serving cluster. So I specify the task clearly, give examples, use structured outputs when the result is data, ground facts in retrieved documents, and then measure consistency with an eval that runs each case several times. Where an answer must be identical every time, I cache it in my own system."
- Sampling picks from the model's distribution; temperature, top-p and top-k reshape that distribution. They still exist on open-weight models.
- On current Claude models those parameters are rejected. The controls are the prompt, the output format and effort.
- A schema-constrained output removes most format variation: the enum can only be one of your values.
- Variation that remains is information: a case that passes three times in five is an under-specified prompt or a retrieval problem.
- Identical-every-time is a storage requirement. Generate once, store the result, serve the stored copy.
Learn more: Sampling: temperature, top-p and top-k.
Use a 72-billion-parameter model shaped like Qwen2.5-72B: 80 layers, 8 key-value heads of size 128, 16-bit numbers.
Show answer
Every token in the context costs money, prefill time and KV-cache memory: about 320 KiB per token on a model that size, so 100,000 tokens is roughly 30 GiB for one conversation. "Input is billed per token on every call. Prefill runs every token through every layer, so time to first token rises. And while generating, the server keeps each earlier token's keys and values in memory, per layer, so it doesn't recompute them. That cache is why long contexts are expensive to serve, and it's on top of the quality problem: models use the middle of very long contexts less reliably."
// KV cache: each layer keeps one key and one value vector per KV head, for every token in the context.
const bytesPerToken = ({ layers, kvHeads, headDim, bytes }) => 2 * layers * kvHeads * headDim * bytes;
// The shape in Qwen2.5-72B-Instruct's published config: 80 layers, 8 KV heads of size 128, served in 16-bit.
const perToken = bytesPerToken({ layers: 80, kvHeads: 8, headDim: 128, bytes: 2 });
console.log(`per token: ${perToken / 1024} KiB`);
for (const tokens of [8_000, 100_000, 1_000_000]) {
console.log(`${tokens.toLocaleString("en-US").padStart(9)} tokens: ${((perToken * tokens) / 2 ** 30).toFixed(1).padStart(5)} GiB for one conversation`);
}per token: 320 KiB
8,000 tokens: 2.4 GiB for one conversation
100,000 tokens: 30.5 GiB for one conversation
1,000,000 tokens: 305.2 GiB for one conversation- Per token: a key and a value (×2), in each of 80 layers, for 8 heads of 128 numbers, at 2 bytes: 320 KiB.
- An 8,000-token chat needs about 2.4 GiB. A 100,000-token context needs about 30.5 GiB, a large slice of one accelerator for a single user.
- A million tokens would be about 305 GiB with this plain arithmetic, which is why providers of million-token windows invest in cache-saving techniques, and why long prompts are priced and rate-limited the way they are.
- The cache is also what makes generation affordable at all: without it, every new token would re-process the whole sequence.
- The practical conclusion is the same from all three angles: keep contexts lean, retrieve what's relevant, and use prompt caching when a large prefix really is reused.
Learn more: Transformers and attention, just enough.
Show answer
Because fitting isn't the same as working well or cheaply. "Sending a whole knowledge base on every request costs its full token count every time and slows the first token. Long contexts also dilute attention: the 'Lost in the Middle' results showed accuracy dropping when the relevant passage sat in the middle. Retrieval sends the few chunks that matter: cheaper, faster, usually more accurate, and it handles per-user permissions and corpora bigger than any window. Long context is right for one-off analysis of a big document, or with prompt caching when the same context is reused."
- Count what's in the window: system prompt, tool definitions, history, documents, and room for the output. It all counts.
- Money and latency scale with the tokens sent, on every call.
- Quality doesn't scale with them: position matters, and irrelevant text competes for attention.
- A corpus that changes, is large, or has access rules needs retrieval whatever the window size.
- The real skill is context engineering: deciding what goes into the window for this request, and in what order.
Learn more: Context windows.
Show answer
Training rewards plausible text, not true text, and nothing in it teaches "I don't know" by default. "Pre-training optimises for likely continuations, and preference tuning rewards confident, agreeable answers. So in an application I give the model the facts by retrieving them into the context, make abstaining legitimate in the prompt and the schema, make claims checkable with citations or tool calls my code can verify, and measure with an eval that includes unanswerable questions."
- Ground: retrieved documents in the context, with an instruction to answer only from them.
- Allow abstention: "I don't know" in the prompt,
nullin the schema, and evals that reward it when the answer isn't in the sources. - Verify: quotes checked against the source, prices and dates from tools, fields validated in code.
- Measure: track both accuracy and the rate of unsupported answers; a model that answers everything looks good on accuracy alone.
- Reasoning models hallucinate less on many tasks. That's a help, not a design.
Learn more: Why models hallucinate and How models are trained: pre-training, fine-tuning and RL.
Show answer
Effort trades quality for tokens and time within one model, so I set it per route, from evals. "Simple tasks where someone is waiting, like classification, extraction, routing and casual chat, get low effort, sometimes on a smaller model. Hard reasoning, code generation and multi-step agents get high or xhigh, because they measurably improve and cost per completed task can fall when fewer retries are needed. Thinking tokens are billed as output, so effort is a cost setting too. And budget_tokens is gone on current Claude models: adaptive thinking plus effort replaced it."
- Current Claude models use adaptive thinking: the model decides how much to think;
output_config.effortis the depth control. - Set effort explicitly per route, because defaults differ between models.
- Thinking tokens count as output tokens and count towards
max_tokens. - If users watch the stream, ask for summarised thinking, or the pause before the first visible token looks like a hang.
- Pass thinking blocks back unchanged on later turns.
Learn more: Reasoning models and thinking.
Show answer
With an eval on my own task, stepping down in cost until quality drops below the bar. "I build a small eval set from real inputs with a way to grade them. I try the strongest model to see what's achievable, then step down, a smaller model or the same model at lower effort, until it fails the bar. I compare latency at real prompt sizes and estimate monthly cost from real token counts, then check the constraints: context size, modalities, tools, data retention and region. I pick the cheapest option that passes, pin the model id, and re-run the eval when a new model appears."
- Public benchmarks shortlist candidates. They don't tell you how a model does on your task.
- Start from the top so you know whether the task is achievable at all.
- Cost and latency are measured, at real prompt and output sizes, not read off a leaderboard.
- Different routes can use different models: a small one to classify, a large one for the hard path.
- Pinning the id and keeping the eval is what makes the next model upgrade a one-day job.
Learn more: The model landscape and choosing a model.