The journey in one picture
Running a trained model to get an answer is called inference. Training happens once and costs millions; inference happens every time anyone presses Enter, billions of times a day. Every chat app follows the same path, whether the model is open or closed, and whether the GPU is in a data centre or in your own laptop.
- The app builds a requestThe whole conversation so far, plus settings such as the maximum length
- The chat templateTurns the list of messages into one long text with special tokens between turns
- The tokenizerTurns that text into token IDs, a list of whole numbers
- PrefillThe whole prompt goes through the model at once. This fills the KV cache and gives the first new token
- DecodeOne token at a time: run the model, choose a token, add it, repeat
- Detokenize and streamEach new token is turned back into text and sent to your screen straight away
- StopAt an end-of-turn token, a length limit, or a stop word
The rest of this lesson walks through these steps one by one. The example is Llama 3.1 8B Instruct running on one NVIDIA H100 GPU. Its numbers are public, which makes it easy to check every calculation.
Step 1: the request
When you press Enter, the app sends a request to a server. Almost every server today understands the same shape of request, first made popular by OpenAI’s API: llama.cpp, vLLM, SGLang, Ollama and most cloud providers all accept it.
{
"model": "llama-3.1-8b-instruct",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Why is the sky blue?"}
],
"max_tokens": 300,
"temperature": 0.7,
"stream": true
}
messagesis the whole conversation so far, not just your last message.systemis the instruction the app gives the model before you say anything.max_tokenscaps the length of the reply.temperaturecontrols how adventurous the choice of each token is (next lesson).streamasks the server to send each piece of the reply as soon as it is ready.
Step 2: the chat template
A model has no idea what a “message” or a “role” is. It only continues text. So before anything else, the server turns the list of messages into one long text, using special tokens to mark where each turn starts and ends. The rules for this are the chat template, a small program that ships with the model.
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024
You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
Why is the sky blue?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
- Each marker in
<|…|>is a single special token with its own ID:<|begin_of_text|>is 128000 and<|eot_id|>(end of turn) is 128009. - The template adds the date lines by itself. 26 July 2024 is the default when the app gives no date.
- The text ends with the header of an assistant turn that has no content yet. The most natural continuation is the assistant’s reply, so that is what the model writes.
During post-training the model saw huge numbers of conversations in exactly this format, so it learned that text after assistant<|end_header_id|> is a helpful answer, and that the answer ends with <|eot_id|>. The template is stored as a small Jinja program in the model’s tokenizer_config.json, and inside GGUF files for llama.cpp.
Quick check
Step 3: from text to numbers
The tokenizer splits the text into tokens and replaces each one with its ID, a whole number between 0 and 128,255 for Llama 3.1. Special tokens are added straight from the template; the rest is split as you saw in the tokens lesson. The prompt above is a few dozen tokens. A long chat, a pasted document or an agent’s tool results can easily reach thousands or hundreds of thousands.
From here on, the model sees nothing but this list of numbers. Each ID picks one row of the embedding table, and those vectors are what enter the first layer.
Step 4: prefill, reading the whole prompt at once
Now the model reads the prompt. All of its tokens go through all 32 layers together, in one pass. This is possible because the whole prompt is already known: nothing has to wait for anything else. This phase is called prefill.
Prefill does two jobs. It stores the keys and values of every prompt token in every layer, the KV cache, so they never have to be computed again. And at the very last position it produces scores for the next token, so prefill ends with the first token of the reply.
work ≈ 2 × parameters × prompt tokensEach weight does one multiply and one add for every token: 2 operations.
2 × 8.03 billion × 2,000 ≈ 32 trillion operationsA 2,000-token prompt to Llama 3.1 8B. Attention between the tokens adds about 1 trillion more.
H100 peak: 989 trillion operations per second (BF16)Real code reaches perhaps half of that, about 500 trillion.
33 trillion ÷ 500 trillion per second ≈ 0.07 sAbout 70 milliseconds before the first token appears.
Prefill keeps the GPU’s maths units busy, because every weight is used by 2,000 tokens each time it is loaded. It is compute-bound: its speed is set by how many operations the chip can do per second.
Step 5: decode, one token at a time
Then comes the slow part. Token 2 of the reply depends on token 1, token 3 on token 2, and so on, so the reply has to be written one token at a time. Each step runs just one new token through all 32 layers, looks back at the KV cache, picks the next token and adds it to the cache. This phase is called decode.
For a single token, the maths is tiny: about 16 billion operations, which an H100 finishes in 0.02 milliseconds. But to do it, the GPU must read all 16 GB of weights out of its memory, and memory is much slower than maths.
8.03 billion weights × 2 bytes = 16.06 GBLlama 3.1 8B in BF16. Every new token reads all of it.
H100 memory speed: 3.35 TB per secondTB is terabytes: 1,000 GB.
16.06 GB ÷ 3,350 GB per second ≈ 4.8 ms per tokenReading the KV cache adds a little more, and the longer the context, the more it adds.
1 ÷ 4.8 ms ≈ 208 tokens per secondThe best possible speed for one user. No software trick can beat it without reading fewer bytes.
Decode is memory-bound: its speed is set by how fast the chip can read memory, not by how fast it can calculate. This one fact explains a large part of modern AI engineering. Smaller files (quantization), reading only some of the weights (mixture of experts), smaller KV caches, and chips with faster memory all exist mainly to make decode faster.
Prefill
- Reads the prompt: all tokens at once
- Each weight read is used for every prompt token
- Compute-bound: limited by operations per second
- Sets the wait before the first token
- Grows with the length of the prompt
Decode
- Writes the reply: one token per step
- Each weight read is used for one token per user
- Memory-bound: limited by bytes per second
- Sets the speed of the writing
- Grows with the length of the reply
Make the prompt long and the reply short, like a question about a pasted document. Then make the prompt short and the reply long, like asking for a story. Watch which phase takes the time.
This interactive part needs JavaScript.
Quick check
Why the maths units sit idle
Compare the two numbers of an H100: 989 trillion operations per second, but only 3.35 trillion bytes read per second. To keep its maths units busy, it needs to do about 295 operations for every byte it reads. Decode for one user does about 1: two operations per weight, and each weight is two bytes. So during decode, more than 99 % of the chip’s computing power waits for memory.
989 × 10¹² ÷ 3.35 × 10¹² ≈ 295What the H100 needs to stay busy.
decode, 1 user: 2 operations ÷ 2 bytes = 1Far below the line: memory-bound.
decode, 64 users: 128 operations ÷ 2 bytes = 64One read of each weight now serves 64 people.
prefill, 2,000 tokens: about 2,000Far above the line: compute-bound.
This is why servers batch: they decode for many users in the same step. Reading the 16 GB once and using it for 64 people costs almost the same time as using it for one, so the server writes up to about 64 times as many tokens per second in total. Each user’s KV cache still has to be read separately, which is why long contexts limit how many users fit. The serving lesson shows how this is organised.
The same thinking is called the roofline model: a chart with operations per byte along the bottom. Below a certain point, memory sets the speed; above it, compute does. Papers on inference speed use it all the time.
Memory speed ÷ 16.06 GB, from each maker’s published memory bandwidth. Real speeds are lower. A 4-bit version of the same model is about a third of the size, so it runs about three times as fast on the same chip; see the quantization lesson.
Step 6: choosing the token, and stopping
At the end of each step the model gives a score, a logit, to every one of its 128,256 tokens. The scores become probabilities, and one token is chosen. How it is chosen (the most likely one, or a random pick shaped by temperature and other settings) is the subject of the next lesson.
The loop stops for one of three reasons:
- The model chooses its end-of-turn token,
<|eot_id|>for Llama 3.1. The server reports"finish_reason": "stop". - The reply reaches
max_tokens. The reply is cut off mid-sentence and the reason is"length". - The text contains a stop string the app asked for, such as
\nUser:.
When a model decides to use a tool, it writes a tool call and then stops in the same way, with the reason "tool_calls". The app runs the tool and sends a new request with the result. That loop is how agents work, and it is Part 7 of this course.
Step 7: back to text, as it is written
Each new token ID is turned back into text, detokenized, and sent to you at once. With "stream": true, the server keeps the connection open and sends one small message per token, using a simple format called server-sent events.
data: {"choices":[{"delta":{"content":"The"}}]}
data: {"choices":[{"delta":{"content":" sky"}}]}
data: {"choices":[{"delta":{"content":" looks"}}]}
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
- Each
data:line carries the new piece of text, thedelta. - The last messages give the reason for stopping, then
[DONE]. - This is why replies appear word by word: you are watching decode happen.
There is one catch, which matters for most of the world’s scripts. Many tokenizers work on bytes, and one letter can take several bytes: the Urdu letter ب is 2 bytes in UTF-8, a Bengali letter 3, and most emoji 4. A token can end in the middle of a letter. A good server holds those bytes back until the letter is complete. A careless one sends half a letter, and you see “�”.
Measuring speed
| What it means | Mostly set by | |
|---|---|---|
| Time to first token (TTFT) | The wait from pressing Enter to the first word | Prefill: prompt length and computing power; also waiting in the queue |
| Time per output token (TPOT) | The gap between words once writing has started; also called inter-token latency | Decode: model size and memory speed |
| Tokens per second | For one user: 1 ÷ TPOT. Usually what reviews of local models mean | Decode |
| Throughput | Tokens per second for the whole server, all users together | Batching, and how many KV caches fit in memory |
| End-to-end latency | From Enter to the last word | Both: TTFT + TPOT × the number of tokens after the first |
Serving papers such as DistServe set targets for TTFT and TPOT separately, because people notice them differently: a long wait at the start, or words that crawl.
latency ≈ TTFT + TPOT × (output tokens − 1)The first token comes from prefill; the rest come one by one.
0.07 s + 0.0048 s × 299 ≈ 1.5 sA 300-token reply to a 2,000-token prompt, for one user on one H100.
Which phase does each change speed up most?
-
A chip with twice the operations per second
Answer: Prefill
-
A chip with twice the memory speed
Answer: Decode
-
Shrinking the model file to 4 bits
Answer: Decode
-
A shorter system prompt
Answer: Prefill
-
Asking for a shorter answer
Answer: Decode
-
Reusing the saved KV cache of a prompt the server has seen before
Answer: Prefill
Many people at once
A real server is answering many people at the same time, and their requests arrive at random moments. Three ideas, each from a paper you can read, shape how servers handle this:
- Continuous batching (Orca, 2022): new requests join the batch at any decode step, and finished ones leave, instead of the whole batch waiting for its slowest member.
- Chunked prefill (Sarathi-Serve, 2024): a long prompt is split into pieces mixed in with other users’ decode steps, so one long document does not freeze everyone else’s replies.
- Disaggregation (Splitwise, 2023, and DistServe, 2024): prefill and decode run on different GPUs, each set up for its own job. DeepSeek, among others, serves this way.
The next lessons take these steps and costs one at a time: sampling (how each token is chosen), the KV cache (its memory), quantization (fewer bytes per weight), hardware (memory speed) and serving (sharing GPUs among many users).
Remember
- Inference is running a trained model. Every request goes: request → chat template → tokens → prefill → decode loop → detokenize and stream → stop.
- The app sends the whole conversation every time. The model keeps no memory between requests.
- The chat template turns messages into one text with special tokens. A wrong template makes a model act strangely.
- Prefill reads the whole prompt at once, fills the KV cache and is compute-bound. It sets the time to first token.
- Decode writes one token per step, reads every weight each time and is memory-bound. Best speed for one user ≈ memory speed ÷ model size.
- Servers batch many users so one read of the weights serves them all. Replies stream by server-sent events and stop at an end-of-turn token, a length limit or a stop string.
Words to know
- Inference
- Running a trained model to get an output. Every chat message is one inference request.
- Chat template
- The rules that turn a list of messages into the single text a model actually reads.
- Special token
- A token with a job, such as marking the start of a turn or the end of the model’s reply.
- Prefill
- The first phase: processing the whole prompt at once and filling the KV cache.
- Decode
- The second phase: writing the reply one token per step.
- Compute-bound
- Limited by how many operations per second the chip can do.
- Memory-bound
- Limited by how many bytes per second the chip can read from memory.
- Batching
- Processing many users’ tokens in the same step, so each weight read serves them all.
- TTFT
- Time to first token: the wait before the reply starts.
- TPOT
- Time per output token: the gap between tokens once writing has begun.
- Throughput
- Total tokens per second across all users of a server.
- Streaming
- Sending each piece of the reply as soon as it is written, usually by server-sent events.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
Efficiently Scaling Transformer Inference
Google’s careful analysis of inference costs for very large models: when the time to read memory sets the speed, and when the time to compute does.
-
Orca: A Distributed Serving System for Transformer-Based Generative Models
Introduced continuous batching (it calls it iteration-level scheduling). Used by almost every server since.
-
Efficient Memory Management for Large Language Model Serving with PagedAttention
The vLLM paper. Read it with the KV cache lesson.
-
Splitwise: Efficient generative LLM inference using phase splitting
Microsoft measured prefill and decode on real traffic and showed they need different hardware.
-
DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving
Defines TTFT and TPOT targets clearly and puts the two phases on separate GPUs.
-
Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve
Chunked prefill. The abstract and introduction explain the prefill and decode trade-off in plain words.
-
LLM Inference Unveiled: Survey and Roofline Model Insights
A survey of speed-up methods, each placed on the roofline chart.
-
DeepSeek-V3/R1 Inference System Overview
A short, rare look at a real service: its layout, its daily traffic and its costs.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonSampling: how the next token is chosen