Availit World How AI really works, in your language

Lesson 23 of 4626 minFacts checked October 20, 2026

What happens when you press Enter

You type a question, press Enter, and within a second a reply starts to appear, a few words at a time. In that second your words become one long text full of special markers, then a list of numbers. The whole prompt goes through billions of weights in one burst, and then the model writes its reply one token at a time, reading every one of its weights again for every token. This lesson follows one request from your keyboard to your screen, with real numbers for a real model.

In this lesson you will

  • Follow a request through every step, from the chat template to the last token
  • Explain the two phases of inference, prefill and decode, and why they behave so differently
  • Work out how fast a model can write from its size and the speed of its memory
  • Read the speed numbers people quote: time to first token, tokens per second and throughput
  • Know why replies arrive word by word, and what makes a model stop
On this page
  1. The journey in one picture
  2. Step 1: the request
  3. Step 2: the chat template
  4. Step 3: from text to numbers
  5. Step 4: prefill, reading the whole prompt at once
  6. Step 5: decode, one token at a time
  7. Why the maths units sit idle
  8. Step 6: choosing the token, and stopping
  9. Step 7: back to text, as it is written
  10. Measuring speed
  11. Many people at once
  12. Remember
  13. Check yourself

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.

From Enter to the last word
  1. The app builds a requestThe whole conversation so far, plus settings such as the maximum length
  2. The chat templateTurns the list of messages into one long text with special tokens between turns
  3. The tokenizerTurns that text into token IDs, a list of whole numbers
  4. PrefillThe whole prompt goes through the model at once. This fills the KV cache and gives the first new token
  5. DecodeOne token at a time: run the model, choose a token, add it, repeat
  6. Detokenize and streamEach new token is turned back into text and sent to your screen straight away
  7. 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.

A chat requestjson
{
  "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
}
  • messages is the whole conversation so far, not just your last message.
  • system is the instruction the app gives the model before you say anything.
  • max_tokens caps the length of the reply. temperature controls how adventurous the choice of each token is (next lesson).
  • stream asks 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.

What Llama 3.1 actually readstext
<|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

Why does the template end with an empty assistant header?

Show the answer

Answer: So that the most likely next text is the assistant’s reply The model only continues text. Ending the prompt where a reply should begin makes a reply the natural continuation.

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.

How long prefill takes
work ≈ 2 × parameters × prompt tokens

Each weight does one multiply and one add for every token: 2 operations.

2 × 8.03 billion × 2,000 ≈ 32 trillion operations

A 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 s

About 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.

The speed limit for one user
8.03 billion weights × 2 bytes = 16.06 GB

Llama 3.1 8B in BF16. Every new token reads all of it.

H100 memory speed: 3.35 TB per second

TB is terabytes: 1,000 GB.

16.06 GB ÷ 3,350 GB per second ≈ 4.8 ms per token

Reading the KV cache adds a little more, and the longer the context, the more it adds.

1 ÷ 4.8 ms ≈ 208 tokens per second

The 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
Try itPrefill and decode on one GPU

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

A model file is 8 GB and the chip reads memory at 1 TB per second. About how many tokens per second can it write for one user, at most?

Show the answer

Answer: About 125 Each token reads all 8 GB. 1,000 GB per second ÷ 8 GB = 125 reads, so about 125 tokens per second at best.

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.

Operations per byte (arithmetic intensity)
989 × 10¹² ÷ 3.35 × 10¹² ≈ 295

What the H100 needs to stay busy.

decode, 1 user: 2 operations ÷ 2 bytes = 1

Far below the line: memory-bound.

decode, 64 users: 128 operations ÷ 2 bytes = 64

One read of each weight now serves 64 people.

prefill, 2,000 tokens: about 2,000

Far 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.

Best possible speed for one user, Llama 3.1 8B in BF16 (16 GB)
  • Apple M5 Max (614 GB/s) 38 tokens per second
  • NVIDIA RTX 4090 (1,008 GB/s) 63 tokens per second
  • NVIDIA H100 SXM (3,350 GB/s) 208 tokens per second
  • NVIDIA H200 (4,800 GB/s) 299 tokens per second
  • NVIDIA B200 (8,000 GB/s) 498 tokens per second

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.

What arrives at the apptext
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, the delta.
  • 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

The numbers people quote
What it meansMostly set by
Time to first token (TTFT)The wait from pressing Enter to the first wordPrefill: 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 latencyDecode: model size and memory speed
Tokens per secondFor one user: 1 ÷ TPOT. Usually what reviews of local models meanDecode
ThroughputTokens per second for the whole server, all users togetherBatching, and how many KV caches fit in memory
End-to-end latencyFrom Enter to the last wordBoth: 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.

A whole reply
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 s

A 300-token reply to a 2,000-token prompt, for one user on one H100.

Which phase does each change speed up most?

0 of 6 sorted
  • 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.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

You send your 10th message in a chat. What does the model read?

Show the answer

Answer: All 10 messages and the replies, sent again by the app The model keeps nothing between requests. The app sends the whole conversation each time.

Why is prefill fast per token but decode slow?

Show the answer

Answer: Prefill uses each weight for every prompt token at once; decode reads all the weights again for each single token The work per token is the same. What differs is how many tokens share each read of the weights.

Which change makes a single user’s reply appear faster on the same chip?

Show the answer

Answer: A smaller model file, for example 4-bit instead of 16-bit Decode speed is roughly memory speed ÷ bytes read per token. Fewer bytes per weight means more tokens per second.

A model starts writing “User:” and answers itself. What is the most likely cause?

Show the answer

Answer: The wrong chat template, so it never learned where its turn ends in this format The model was trained to end its turn with a special token in one exact format. A different format confuses it.

What does time to first token mostly depend on?

Show the answer

Answer: The length of the prompt and the chip’s computing power, plus any queue The first token comes at the end of prefill, which processes the whole prompt.

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
Previous lesson All lessons

Choose your language