A large language model does not think up a full answer and then type it. It picks one small piece of text, then the next, then the next, each time asking a single question: what is likely to come after this?
That one loop explains a lot of everyday behaviour: why answers stream word by word, why the first word takes longer than the rest, why the same question can get different answers, why long chats cost more, and why a model can say something false with full confidence.
This article walks through the whole path from your prompt to the answer: tokens, embeddings, attention, probabilities, sampling and the KV cache. It uses small numbers you can check by hand, real model sizes and a short Python script you can run yourself. The maths never goes beyond multiplying, adding and one exponential function.
1. The Short Version: One Token at a Time
Everything an LLM does at answer time fits in one loop:
1. turn the text into tokens "Hi there" -> [17250, 612]
2. run all tokens through the model -> one score per possible token
3. turn the scores into probabilities -> " Paris" 0.62, " a" 0.10 ...
4. pick one token -> " Paris"
5. append it to the input, go to 2 until a stop token or a limit
This is called autoregressive generation: every new token is generated from all tokens before it, including the ones the model itself just wrote. There is no separate draft that gets revised before you see it. Whatever planning the model does has to happen inside the computation for each single token, and a sentence it started in step 40 has to be continued in step 41.
The token IDs above are only an illustration; every model has its own vocabulary. In code, the loop looks like this:
tokens = tokenize(prompt)
while len(tokens) < max_tokens:
probs = model(tokens) # probabilities for the NEXT token
next_token = sample(probs) # pick one
if next_token == END_OF_TEXT:
break
tokens.append(next_token)
stream_to_user(detokenize([next_token]))
That is the whole trick at the outside. The rest of this article opens the two interesting boxes: what happens inside model() and what happens inside sample().
2. Tokens: How Text Becomes Numbers
A neural network can only work with numbers, so the first step turns text into a list of integers. The units are tokens: common words, parts of words, single characters or bytes.
Most models use a variant of byte pair encoding (BPE). The idea: start with single bytes, then repeatedly merge the pair that appears most often in the training text into a new token. After tens of thousands of merges, frequent words like the or house are one token, and rare words are split into pieces.
A typical split looks like this (the exact pieces depend on the tokenizer):
"The cat sat"
-> ["The", " cat", " sat"] 3 tokens
"unbelievably"
-> ["un", "believ", "ably"] 3 tokens
"Straßenbahnhaltestelle" (German for tram stop)
-> ["Stra", "ßen", "bahn", "hal", "test", "elle"] 6 tokens
Note the leading space: cat with a space is a different token from cat at the start of a line. In most tokenizers, a space belongs to the word after it.
Some numbers to get a feel:
| Model | Vocabulary size |
|---|---|
| GPT-2 (2019) | 50,257 |
| Llama 2 | 32,000 |
| Llama 3 | 128,256 |
For English text, OpenAI's rule of thumb is about 4 characters or 0.75 words per token. German, code and most other languages need more tokens for the same content, because the vocabulary was learned mostly from English text. Since APIs bill and limit by tokens, the same answer in German usually costs more.
Tokens also explain a classic weakness. Ask a model how many letters r are in strawberry and it may get it wrong, because it never sees the letters: it sees something like ["str", "aw", "berry"], three numbers. Counting letters means reasoning about spelling it only learned indirectly.
3. Embeddings: Every Token Becomes a Vector
A token ID like 9906 is just a row number. The model looks up that row in a big table, the embedding matrix, and gets a vector of numbers: the token's starting point in a space with thousands of dimensions.
Llama 3 8B
vocabulary 128,256 tokens
vector size 4,096 numbers per token
embedding table 128,256 x 4,096 = about 525 million numbers
Nobody designs these vectors. They start random and are adjusted during training until tokens that are used in similar ways end up close to each other. Directions in this space start to carry meaning. The famous example from the older word2vec models:
vector("king") - vector("man") + vector("woman") ≈ vector("queen")
Modern LLMs are not that tidy, but the principle holds: meaning is position and direction in a high-dimensional space.
One thing is missing: order. "dog bites man" and "man bites dog" contain the same tokens. Models therefore add position information. Most current models use rotary position embeddings (RoPE), which rotate parts of each vector by an angle that depends on the token's position, so the model can tell how far apart two tokens are.
After this step the prompt is no longer text. It is a matrix: one row of 4,096 numbers per token.
4. The Transformer: A Stack of Identical Layers
The core of the model is a stack of transformer layers. Llama 3 8B has 32 of them, GPT-2 small has 12. Every layer has the same two parts:
- Attention: each token looks at the tokens before it and collects the information it needs.
- Feed-forward network (MLP): each token's vector is processed on its own, through a large layer and back. This is where much of the learned knowledge seems to be stored.
Each part does not replace the vector; it adds a change to it. Researchers call the vector that flows through the layers the residual stream:
x = embedding(token) + position
for layer in layers: # 32 times in Llama 3 8B
x = x + attention(norm(x)) # mix in context
x = x + mlp(norm(x)) # transform
logits = unembed(norm(x)) # one score per vocabulary token
You can picture the residual stream as a shared notebook for each token position. Early layers write down simple facts ("this is a noun", "this follows 'the'"), later layers write more abstract ones ("this sentence is a question about geography", "the answer should be a city").
Where do the 8 billion parameters of an 8B model live? For Llama 3 8B the split is easy to compute from its published sizes:
MLP 3 × 4,096 × 14,336 × 32 layers ≈ 5.6 billion
attention (2 × 4,096² + 2 × 4,096 × 1,024) × 32 ≈ 1.3 billion
embedding and unembedding 2 × 128,256 × 4,096 ≈ 1.1 billion
total ≈ 8.0 billion
About 70% of the model is MLP. Attention is the part that gets the attention, but most of the weights sit in the feed-forward layers.
5. Attention: How Tokens Look at Each Other
Attention is the part that made transformers famous. Take the sentence:
The animal didn't cross the street because it was too tired.
To understand it, the model needs to know that it means the animal, not the street. Attention lets the vector of it pull in information from animal.
For this, every token produces three vectors from its current state:
| Vector | Question it answers |
|---|---|
| Query (Q) | What am I looking for? |
| Key (K) | What do I contain? |
| Value (V) | What do I pass on if someone attends to me? |
The token compares its query with every key. A high match means "this token is relevant to me". The matches are turned into weights that add up to 1, and the token takes the weighted mix of the values.
score(i, j) = (query_i · key_j) / √d
weights = softmax(scores) # all positive, sum to 1
output_i = Σ weights_j × value_j
5.1 A Worked Example
Three tokens, the cat sat, with tiny 2-number vectors so you can check it by hand. We compute the attention output for sat.
query(sat) = [1.0, 0.5]
token key value score = q·k / √2
the [0.1, 0.2] [0.0, 1.0] (0.10 + 0.10) / 1.414 = 0.141
cat [1.0, 0.8] [1.0, 0.0] (1.00 + 0.40) / 1.414 = 0.990
sat [0.4, 0.3] [0.5, 0.5] (0.40 + 0.15) / 1.414 = 0.389
Softmax turns the scores into weights: raise e to each score and divide by the sum.
e^0.141 = 1.151 e^0.990 = 2.691 e^0.389 = 1.476 sum = 5.318
weights: the 0.217 cat 0.506 sat 0.277
output(sat) = 0.217 × [0.0, 1.0]
+ 0.506 × [1.0, 0.0]
+ 0.277 × [0.5, 0.5]
= [0.645, 0.355]
sat pays half of its attention to cat, the one who sits. The output vector is added to the residual stream of sat, which now carries a bit of "who is sitting". In a real model the same thing happens with vectors of 128 numbers per head, and the queries, keys and values come from learned weight matrices.
The division by √d keeps scores from growing too large in big dimensions, which would make softmax put almost all weight on a single token.
5.2 Causal Mask and Multiple Heads
Two details matter for generation:
- Causal mask: a token may only attend to itself and to tokens before it. When the model reads
the cat sat,catcannot peek atsat. This is what makes the model a next-token predictor: during training it learns to predict each token without seeing the future. It also makes training efficient: one pass over a text of 1,000 tokens gives 1,000 prediction exercises at once. - Multi-head attention: each layer runs attention many times in parallel with different weights. Llama 3 8B has 32 heads per layer. One head may track grammar, another which noun a pronoun refers to, another the previous token. Their outputs are combined.
causal mask for "the cat sat on" (x = may attend)
the cat sat on
the x
cat x x
sat x x x
on x x x x
6. From the Last Vector to Probabilities
After the last layer, only one position matters for the next token: the last one. Its vector of 4,096 numbers is multiplied by the unembedding matrix, which gives one score per vocabulary entry: 128,256 numbers called logits.
Softmax turns the logits into probabilities that add up to 1. For the prompt The capital of France is, the top of the list could look like this (illustrative numbers):
| Next token | Probability |
|---|---|
| " Paris" | 0.62 |
| " a" | 0.10 |
| " the" | 0.07 |
| " located" | 0.05 |
| " one" | 0.03 |
| all other 128,251 tokens | 0.13 |
This is the key point of the whole article: the model's output is not a word, it is a probability distribution over all tokens. The model never "decides". Something outside it, the sampler, picks a token from this distribution.
It also shows why a wrong answer can come out fluently. If the training data made " Lyon" a plausible continuation in some context, the model can produce it with the same confidence as a true fact. It ranks continuations; it does not look anything up.
7. Sampling: Picking the Next Token
The sampler decides how to pick from the distribution. These are the usual settings you find in every LLM API.
7.1 Greedy
Always take the most likely token. Deterministic, but the text tends to become repetitive and dull, and it can get stuck in loops.
7.2 Temperature
Temperature divides the logits before softmax. Below 1 the distribution gets sharper, above 1 it gets flatter. Three tokens with logits 2.0, 1.0 and 0.1:
probability = softmax(logits / T)
T = 0.5 T = 1.0 T = 2.0
token A 0.864 0.659 0.502
token B 0.117 0.242 0.304
token C 0.019 0.099 0.194
Low temperature makes the model safe and predictable: good for code, extraction and facts. High temperature gives more variety: useful for brainstorming, risky for facts. Temperature 0 means greedy in most APIs.
7.3 Top-k and Top-p
Even with sensible temperature, the long tail of 128,000 unlikely tokens adds up. Picking one of them now and then derails a sentence. Two filters cut the tail:
- Top-k: keep only the k most likely tokens, for example 40.
- Top-p (nucleus sampling): keep the smallest set of tokens whose probabilities add up to p, for example 0.9. When the model is sure, that set is tiny; when it is unsure, it is larger.
With the France table and top-p 0.8: " Paris" (0.62) + " a" (0.10) + " the" (0.07) = 0.79, still below 0.8, so " located" (0.05) is added. Only these four remain, are rescaled to sum to 1, and one of them is drawn.
A complete sampler fits in a few lines:
import math, random
def sample(logits, temperature=0.7, top_p=0.9):
if temperature == 0: # greedy
return max(range(len(logits)), key=lambda i: logits[i])
scaled = [l / temperature for l in logits]
m = max(scaled) # for numeric stability
exps = [math.exp(s - m) for s in scaled]
total = sum(exps)
probs = sorted(((e / total, i) for i, e in enumerate(exps)),
reverse=True)
kept, acc = [], 0.0
for p, i in probs: # top-p filter
kept.append((p, i))
acc += p
if acc >= top_p:
break
r = random.random() * acc # draw from what is left
for p, i in kept:
r -= p
if r <= 0:
return i
return kept[-1][1]
This is why the same question gives different answers: the model computes the same distribution every time, but the draw is random. With temperature 0 you get (almost) the same answer each time; small differences can still come from floating point maths on GPUs and from batching.
8. Prefill, Decode and the KV Cache
Generation has two very different phases, and you can feel both in every chat.
Prefill: the whole prompt is processed at once. All tokens go through all layers in parallel, which GPUs are very good at. The time until the first token appears is called time to first token (TTFT) and grows with the prompt length.
Decode: after that, one token per step. Each step only adds one new token, but that token needs to attend to all earlier tokens.
Recomputing the keys and values of all earlier tokens in every step would be wasteful. They do not change, because of the causal mask. So the model stores them: the KV cache. Each new step computes K and V for the one new token, appends them, and reads the rest from memory.
The cache is not small. For Llama 3 8B, which uses grouped-query attention with 8 key-value heads:
per token = 2 (K and V) × 32 layers × 8 KV heads
× 128 numbers per head × 2 bytes (16-bit)
= 131,072 bytes = 128 KiB
8,192 tokens of context -> 1 GiB
128,000 tokens (Llama 3.1) -> about 15.6 GiB, per conversation
This is why long contexts are expensive to serve, why providers charge for input tokens and why many offer cheaper "cached input" prices: a prompt prefix that was already processed can reuse its KV cache instead of running prefill again.
9. Why Decode Speed Is About Memory, Not Maths
In every decode step, the GPU has to read all model weights once to compute one token. For an 8B model in 16-bit numbers that is 16 GB. The maths per weight is tiny; moving the weights from memory to the compute units is the bottleneck.
weights 8 × 10^9 parameters × 2 bytes = 16 GB
H100 memory about 3.35 TB/s
lower bound 16 GB / 3.35 TB/s ≈ 4.8 ms per token
-> at most about 200 tokens/s for one user
This is the same lesson as in Latency Is the New Bandwidth: the limit is often not how fast you can compute, but how fast you can move data. Three common tricks follow directly from it:
- Batching: serve many users in the same step. The weights are read once and used for all of them, so the cost per user drops sharply.
- Quantization: store weights in 8 or 4 bits instead of 16. Half or a quarter of the bytes to read, so up to two or four times faster decode, at a small loss in quality.
- Speculative decoding: a small, fast model guesses several tokens, and the big model checks them all in one step. When the guesses are right, you get several tokens for the price of one big step.
10. Chat Is Just Text
A chat with an LLM looks like a conversation, but the model only ever sees one long sequence of tokens. A chat template turns the messages into text with special marker tokens. A simplified example (each model family has its own markers):
<|system|>
You are a helpful assistant. Answer briefly.
<|user|>
What is the capital of France?
<|assistant|>
The capital of France is Paris.<|end|>
<|user|>
And of Italy?
<|assistant|>
The model continues the text after the last <|assistant|> marker, and generation stops when it produces the end marker. Some consequences:
- The model has no memory between requests. The app sends the whole conversation again with every message. A long chat means a long prompt, more prefill time and more cost.
- The context window is a hard limit. When the conversation no longer fits, the app has to drop or summarise old messages. The model does not "forget"; it was simply never shown them.
- The system prompt is just text at the start. It is powerful because the model was trained to follow it, not because it is technically separate. This is also why prompt injection works: instructions hidden in a web page or document end up in the same token sequence.
11. Where the Answers Come From: Training
All of the above is the model at answer time, with fixed weights. The weights themselves come from training in roughly three stages:
| Stage | Data | What the model learns |
|---|---|---|
| Pretraining | Trillions of tokens of web text, books, code | Predict the next token: language, facts, patterns |
| Instruction tuning | Example dialogues written or checked by people | Answer questions instead of just continuing text |
| Preference training (RLHF and similar) | Answers ranked by people or by rules | Prefer helpful, honest and safe answers |
Pretraining is by far the largest stage: Llama 3, for example, was pretrained on more than 15 trillion tokens. It is the same next-token game as generation, played billions of times. The model sees The capital of France is, predicts a distribution, is told the real next token was Paris, and all weights are nudged slightly so that Paris becomes a bit more likely next time. Repeat over trillions of tokens and the cheapest way to predict well is to learn grammar, facts, and patterns of reasoning.
This is also where the limits come from. The model knows what was in its training data up to a cutoff date, weighted by how often it appeared. That is why modern assistants add tools: web search, code execution, or a lookup in your own documents (retrieval-augmented generation, RAG). The retrieved text is simply placed into the prompt, and the same next-token loop now has the facts in front of it.
12. What This Means When You Use an LLM
Knowing the loop turns a lot of prompt folklore into plain engineering:
| Observation | Explanation from the loop | What to do |
|---|---|---|
| The first token is slow, the rest stream fast | Prefill processes the whole prompt first | Keep prompts and chat history short; reuse a fixed prompt prefix so it can be cached |
| The same prompt gives different answers | The sampler draws at random | Temperature 0 to 0.3 for extraction, code and tests; higher for ideas |
| "Think step by step" improves hard answers | Every written token is one more full pass through the model | Let the model write its reasoning before the final answer |
| The model ignores a rule from early in a long chat | Everything competes for attention in one long sequence | Repeat important rules near the end, or start a fresh conversation |
| JSON output is sometimes broken | Each token is sampled on its own, nothing checks the whole | Use the API's structured output mode, which removes invalid tokens before sampling |
| Answers stop in the middle | A token limit (max_tokens) ended the loop | Raise the limit or ask for a shorter answer |
| The answer sounds sure but is wrong | The model ranks plausible text, it does not look facts up | Put the source documents into the prompt and ask for answers based on them |
Structured output deserves a second look, because it is the sampler from section 7 at work. The API knows which tokens may come next to keep the JSON valid against your schema, sets the probability of every other token to zero, and only then draws. The model is the same; only the choice is restricted.
13. Try It Yourself
You can watch the whole loop on your own machine with GPT-2, a small open model from 2019 (124 million parameters, 12 layers). The script prints the three most likely next tokens at every step and always takes the first one, which is greedy decoding:
python3 -m venv llm && source llm/bin/activate
pip install torch transformers
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
ids = tok("The capital of France is", return_tensors="pt").input_ids
print(tok.convert_ids_to_tokens(ids[0])) # see the tokens
for _ in range(6):
with torch.no_grad():
logits = model(ids).logits[0, -1] # scores, last position
probs = torch.softmax(logits, dim=-1)
top = torch.topk(probs, 3)
print([(tok.decode(int(i)), round(float(p), 3))
for p, i in zip(top.values, top.indices)])
next_id = top.indices[:1].unsqueeze(0) # greedy: take the best
ids = torch.cat([ids, next_id], dim=1)
print(tok.decode(ids[0]))
Things to try:
- Replace the greedy line with sampling,
next_id = torch.multinomial(probs, 1).unsqueeze(0), and run the script a few times. - Divide
logitsby 0.5 or 2.0 before softmax and watch the probabilities change. - Tokenize a German sentence and compare the token count with its English translation.
GPT-2 is small and often wrong, which is useful here: you can see exactly where a plausible but false continuation wins.
14. Conclusion
The whole path in one picture:
"The capital of France is"
│ tokenizer
v
[The] [ capital] [ of] [ France] [ is]
│ embedding + position
v
5 vectors × 4,096 numbers
│ 32 layers: attention + MLP (K and V go to the KV cache)
v
last vector → 128,256 logits → softmax → probabilities
│ sampler: temperature, top-p
v
" Paris" → appended to the input → next step
An LLM answer is a loop of one simple step, done very many times with a very large model:
- Text becomes tokens, tokens become vectors. The model never sees letters, which explains odd failures with spelling and counting.
- Attention mixes context into every token. Queries, keys and values decide which earlier tokens matter, and the KV cache stores them so each new token is cheap.
- The model outputs probabilities, the sampler picks. Temperature and top-p decide how safe or creative the result is, and why answers vary.
- Speed is about memory. The first token waits for prefill, every following token waits for the weights to be read.
- Fluent is not the same as true. The model ranks plausible continuations; facts come from training data, or from documents and tools you put into the prompt.
Next time an answer streams in word by word, you know what is happening: a distribution over 128,000 tokens, one draw, and the whole thing again.




