AI ENGINEERING · LLM FOUNDATIONS · FOUNDATIONS · 1 OF 35

How Large Language Models Work: Next-Token Prediction

What a large language model really does: predict the next token, pick one, append it and repeat. How pretraining, instruction tuning and preference tuning turn a text predictor into an assistant, why fluent answers can still be wrong, what a model lacks (memory, live data, exact maths), stateless API calls, system, user and assistant messages, and why outputs change from run to run.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 18

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Predict
  • pick
  • append
  • repeat
  • pretrain, then tune
  • likely is not true
  • stateless
  • outputs vary

Notes

The idea

Here is the core idea. A language model does exactly one thing. You give it a piece of text, and it returns a probability for every token it knows, where a token is a word or a piece of a word. Given the capital of France is, it says Paris is very likely and most other tokens are not. That is the whole job. No database lookup, no stored plan. Just a very good guess at what comes next.

The one job
  • input: a sequence of tokens (word pieces, next episode)
  • output: a probability for every token in its vocabulary (~50k to ~250k of them)
  • that is all. no lookup, no plan stored anywhere, just: what comes next?

The core loop

One prediction gives one token. To get a paragraph, you loop. Run the model on the context, get the probabilities, pick one token, append it to the context, and run the model again on the longer text. Stop when the model picks a special end token or you hit the maximum length you set. Every answer you have ever seen from a chat assistant was written this way, one token at a time, each one depending on all the ones before.

Generation loop
tokens = tokenize(prompt)
while len(out) < max_tokens:
  probs = model(tokens)
  t = sample(probs)
  if t == END: break
  tokens.append(t)
  out.append(t)
return detokenize(out)

Worked example

Let us see the numbers. The model actually outputs a raw score for each token, called a logit. Say Paris scores six, a scores three point five, the scores three, and located scores two point five. Softmax turns scores into probabilities. Raise e to each score, then divide by the total. That gives Paris about eighty six percent, a about seven, the about four, located about three. Small gaps in score become big gaps in probability.

Scores to probabilities
token      score   e^score   prob
" Paris"     6.0     403      86%
" a"         3.5      33       7%
" the"       3.0      20       4%
" located"   2.5      12       3%
                   sum 468

prob = e^score / sum of e^score
(real vocab: ~100k rows, not 4)

Token by token

This has a practical consequence. The model reads your whole prompt in one parallel pass, which is fast. But it writes the answer one token per pass, and each pass runs through the entire network. So a long answer takes much longer than a long question. That is why output tokens usually cost several times more than input tokens, and why asking for a short answer is the cheapest speed up you have.

Three steps of one answer
step 1  "...France is"  → " Paris"
step 2  "...is Paris"   → "."
step 3  "...Paris."     → END

reading the prompt: parallel,
  fast (prefill)
writing the answer: one full
  pass per token (decode)

so long outputs are slow

Pretraining

Where does the skill come from? Stage one is pretraining. Take an enormous amount of text, web pages, books, code and papers, often more than ten trillion tokens. Show the model a passage, ask it to predict the next token, measure how wrong it was, and nudge billions of weights to be a little less wrong. Repeat that trillions of times. To predict text well, the model has to absorb grammar, facts, coding patterns and a fair amount of reasoning along the way.

Pretraining
  • data: a large slice of the public web, books, code, papers: ~10+ trillion tokens
  • task: hide the next token, predict it, measure the error, nudge the weights
  • repeat: trillions of times
  • result: a base model that continues any document

Instruction tuning

A base model is a document completer, not an assistant. Ask it how to reverse a list in Python, and it may simply continue with more questions, because that is what forum pages look like. Stage two, instruction tuning, fixes this. The model is trained further on many examples of a request followed by a good answer. Now it learns the pattern: when someone asks, respond helpfully. Same next token prediction, different data.

Base model vs assistant
  • prompt: "How do I reverse a list in Python?"
  • base model may continue: "How do I sort a list? How do I copy a list?"
  • after instruction tuning: "Use my_list[::-1] or my_list.reverse()."

Preference tuning

Stage three is preference tuning. Generate two answers to the same prompt, and have a person, or another model following written rules, pick the better one. Then train the model to make the preferred kind of answer more likely. You will hear R L H F, reinforcement learning from human feedback, and D P O. This stage shapes tone, helpfulness, when to refuse, and how much to admit uncertainty. Many newer models also get reinforcement learning on tasks with checkable answers, like maths and code.

Preference tuning
  • show two answers to a prompt
  • a person or a model picks the better one train the model to make the preferred kind more likely (RLHF, DPO and variants)
  • shapes: helpfulness, tone, honesty, refusals, format

Fluent but wrong

Now the big catch. The model learned to produce likely text, not true text. Most of the time those agree. But ask for a citation on a niche topic and it can produce a perfectly formatted paper title, authors and year that do not exist. There is no not found state. It always emits some next token. This is called hallucination. The fixes are to put the real source in the context, allow it to say it does not know, and verify important claims outside the model.

Why hallucinations happen
  • the goal is likely text, not checked facts
  • rare facts are stored weakly
  • there is no "not found": it always emits a next token
  • guessing was often rewarded
  • fixes: give it the source, allow "I don't know", verify outside the model

What it lacks

Be clear about what the model does not have. It has no memory between calls. Its knowledge stops at a training cutoff, so it does not know today's news or your latest prices. It has no built in calculator, so long arithmetic can slip, because it predicts digits rather than computing them. And it cannot see your database or act on anything. Your app fills every one of these gaps, by putting data into the context and by offering tools.

What a model does not have
  • memory between calls
  • live data: knowledge stops at a training cutoff date
  • a calculator: maths is done by pattern, so long sums slip
  • your data: orders, docs, users
  • the ability to act on its own
  • your app supplies all of these
  • through context and tools

Stateless calls

Here is how that feels in an API. Every call is stateless. The chat app only looks like it remembers, because it re sends the whole conversation every time. Say each turn adds about two hundred tokens. Turn one sends two hundred, turn ten sends two thousand, and the ten turns together send eleven thousand input tokens. Cost grows roughly with the square of the conversation length, so long chats get trimmed or summarised.

Re-sending history
each turn adds ~200 tokens

turn 1 sends     200 tokens
turn 2 sends     400
turn 10 sends  2,000
total over 10  11,000 input

grows as n squared over a
chat; trim or summarise it

Message roles

A request is a list of messages, each with a role. The system message sets the rules and persona, like you are a support bot for Acme, be brief. User messages are what the person typed. Assistant messages are the model's own earlier replies, which your app sends back. Under the hood all of this is flattened into one token stream with special role markers, and the model simply predicts the next assistant turn. Roles are a convention it was trained on, not a hard wall.

One request
system:    You are a support bot
           for Acme. Be brief.
user:      Where is order 1182?
assistant: Let me check that.
user:      It is two days late.

flattened into one token stream
with role markers; the model
writes the next assistant turn

Why outputs vary

Why does the same prompt give different answers? The sampler usually draws a token according to the probabilities, rather than always taking the top one. With Paris at eighty six percent, roughly one run in seven picks something else, and every later token then shifts too. Setting temperature to zero makes output nearly repeatable, but not guaranteed, because of batching and floating point details on the server. Models behind an alias also get updated. Episode four covers sampling properly.

Sources of variation
  • sampling: tokens are drawn by probability, not always the top one temperature 0: nearly the same, not guaranteed (batching, floating point)
  • model updates behind an alias
  • so: never test exact strings

Common mistakes

A few mistakes catch almost everyone. Using the model as a fact database without giving it sources. Assuming it remembers the previous call. Trusting its arithmetic instead of handing sums to real code. Writing tests that expect an exact string, which break on the next run. Calling a model alias that silently changes under you instead of pinning a version. And forgetting that long outputs are the slow, expensive part of every request.

Mistakes to avoid
  • using it as a fact database without giving it sources
  • assuming it remembers the last call
  • trusting its arithmetic
  • asserting exact output strings in tests
  • not pinning a model version
  • ignoring output length cost

Where it shines

So where does it shine? Language work over text you provide. Summarise a ticket, pull fields out of an invoice, classify an email, rewrite a paragraph, translate, draft code. It is weaker at recalling exact facts with no source, at arithmetic and counting, at anything about today, and at decisions that must be fully audited. The pattern is consistent. Give it the facts and the tools, and let it do the language part.

Good fit vs poor fit
  • good fit: summarise, extract fields, classify, rewrite, draft, translate, write code
  • poor fit, unless helped: exact facts with no source arithmetic, counting today's data decisions needing audit

Numbers worth knowing

Numbers worth knowing, all rough. A token is about four characters of English, or three quarters of a word. Vocabularies hold roughly fifty thousand to a quarter of a million tokens. Large models are pretrained on ten trillion tokens or more, and have from about a billion to over a trillion parameters. Context windows run from around a hundred thousand to a million tokens. Output arrives at tens to hundreds of tokens per second, and costs about three to five times more per token than input.

Ballpark numbers
1 token            ~4 chars, ~0.75 words
vocabulary         ~50k - 250k tokens
pretraining data   ~10+ trillion tokens
parameters         ~1B to ~1T+
context window     ~128k - 1M+ tokens
output speed       ~30 - 300 tokens/s
first token        ~0.2 - 2 s
output vs input    ~3 - 5x price/token

Say it like this

How to say it. A language model predicts a probability for every possible next token. We sample one, append it, and repeat until a stop token. Pretraining on huge text gives it knowledge, and instruction and preference tuning turn it into an assistant. It is stateless and can be fluently wrong, so the application sends the history, grounds answers in real data and validates the output. That last sentence is what interviewers listen for.

In the interview
  • "An LLM predicts a probability for every next token; we sample one, append, repeat. Pretraining gives knowledge, instruction and preference tuning make it an assistant. It is stateless and can be fluently wrong, so we send history, ground it in data and validate the output."

Interview questions

Q1At a high level, how does a large language model generate text?

It takes the text so far as tokens and outputs a probability for every token in its vocabulary. A sampler picks one, it is appended to the input, and the model runs again, repeating until an end token or a length limit.

Q2What are the main training stages of a modern chat model?

Pretraining on trillions of tokens to predict the next token, which builds a base model; instruction tuning on prompt and answer examples so it follows requests; and preference tuning (RLHF, DPO or similar) so it produces the kinds of answers people prefer.

Q3What is the difference between a base model and an instruction-tuned model?

A base model only continues documents, so a question may be followed by more questions. An instruction-tuned model has been trained on request and response pairs, so it answers the request in the style of an assistant.

Q4Why do LLMs hallucinate?

They are trained to produce likely text, not verified facts, and they always emit some next token instead of reporting "not found". Rare facts are stored weakly, so the model fills gaps with plausible content. Grounding in supplied sources and verification reduce it.

Q5Does the model remember earlier messages in a conversation?

No. API calls are stateless. The application re-sends the relevant history with every request, which is why input tokens and cost grow as a conversation gets longer.

Q6What are system, user and assistant messages?

The system message sets rules and persona, user messages carry the person's input, and assistant messages are the model's earlier replies. They are flattened into one token sequence with role markers, and the model predicts the next assistant turn.

Q7Why can the same prompt give different outputs?

The next token is usually sampled from the probability distribution rather than always taking the top choice, and one different early token changes everything after it. Even at temperature zero, server-side batching and floating-point effects, plus model updates, can change results.

Q8Why is generating output slower and more expensive than reading input?

The prompt is processed in one parallel pass, but output is produced one token per full forward pass through the network. That sequential work is why output tokens are priced several times higher and why shorter answers are faster.