Unit 1 of 9
What is inference engineering?
What you’ll learn
- Trace one chat request through the template, tokenizer, prefill, decode loop, detokenizer, and stream, with real token counts.
- Explain which parts of inference stay fixed and which grow with each request.
- Estimate prefill and decode time for Llama 3.1 8B on an H100 from memory bandwidth and compute.
- Define time to first token, inter-token latency, end-to-end latency, and throughput, and predict how a change trades one against another.
What inference is
Your team has a model: Llama 3.1 8B, a 16 GB file of numbers. In a notebook it answers a question in under a second. Next month it has to answer a few thousand customers at once, each expecting words on screen within half a second, on GPUs that cost money every hour. Getting from the notebook to that service is inference engineering.
Inference means using a trained model to produce outputs. Training chose the model’s weights; inference only reads them. For a language model, one inference step takes the tokens so far and produces a score for every possible next token. The system picks one token, adds it to the text, and runs the model again, until the answer is complete.
Two things are easy to confuse here. The model is the architecture plus its weights: the math. The serving system is everything around it: receiving requests, turning text into numbers, deciding which requests run on the GPU and when, holding each request’s memory, streaming results back, and cleaning up. Inference engineering is mostly the second part, done with a precise understanding of the first.
During ordinary inference, some things never change and some grow with every request. Keep this split in mind; the whole course builds on it.
| Part | During inference | Shared by requests? |
|---|---|---|
| Model weights (about 16 GB for Llama 3.1 8B in BF16) | Fixed. Read on every step, never written. | Yes: one copy serves everyone |
| Tokenizer vocabulary (128,256 entries) | Fixed | Yes |
| The request’s token IDs | Grow by one per generated token | No |
| The request’s KV cache | Grows by one position per token, per layer | No |
| Sampling state (random seed, stop rules, counters) | Updated every step | No |
What a serving system adds
A notebook call loads the weights, runs one prompt, and exits. A service keeps the weights loaded and answers many requests that overlap in time. That changes the questions you have to answer:
| Question | Notebook | Service |
|---|---|---|
| When are the weights loaded? | Every run | Once, at startup |
| How many requests run at once? | One | Dozens or hundreds, batched together |
| What happens when the GPU is busy? | Nothing else is waiting | A scheduler queues new requests or adds them to the running batch |
| Where does each request’s state live? | In local variables | In a shared KV cache budget that can fill up |
| When does the user see output? | When the call returns | Token by token, as a stream |
| What if the user closes the tab? | Not a concern | The request must stop and release its memory |
Every row is a design decision with a cost. The rest of this lesson follows one request through such a service, so you can see where each decision shows up.
Follow one request from Enter to the last token
Here is a real request to a support assistant running Llama 3.1 8B Instruct. The token counts below come from the model’s published tokenizer and chat template. The timings are illustrative: realistic for one H100 with no other traffic, but not measured.
{
"messages": [
{"role": "system", "content": "You are a support assistant for an online bookstore. Answer in two sentences or fewer."},
{"role": "user", "content": "My order arrived with a torn cover. Can I get a replacement?"}
],
"max_tokens": 200
}- Apply the chat template
The model was trained on conversations in one exact format, so the server wraps the messages in it. Llama 3.1’s template adds a header for each role, an end marker after each message, a knowledge-cutoff line, a default date, and an open header for the assistant’s reply. The special markers such as
<|eot_id|>are single tokens. - Tokenize
The tokenizer splits the templated text into tokens and maps each to an integer ID. This prompt becomes 66 tokens. The user typed 12 words (14 tokens) and the system message is 15 words (17 tokens); the template added the other 35. Prompt length, and therefore cost, is measured in tokens, not words.
- Wait for a slot
A scheduler decides when the request joins the batch running on the GPU. On an idle server that is immediate. On a busy one, the request waits in a queue, and that wait counts toward everything the user feels.
- Prefill
The model processes all 66 tokens in one parallel forward pass. Every layer stores a key and a value for each position in the request’s KV cache: 66 × 128 KiB = 8.25 MiB. The last position’s output is a vector of 128,256 scores, called logits, one per vocabulary entry. The sampler turns them into the first output token,
I. - Decode, one token per step
The new token goes back into the model alone, reading the cache instead of recomputing the prompt. Each pass yields one more token:
'm, thensorry, and so on. The reply below is 39 tokens, and the 40th token the model picks is<|eot_id|>, which ends the answer. That is 1 prefill pass plus 39 decode passes. - Detokenize and stream
The server converts each token ID back to text and sends it immediately as a server-sent event, so the user starts reading while the rest is generated. When the end token arrives, the server closes the stream and frees the request’s cache, which by then holds 66 + 39 = 105 positions (13.1 MiB).
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024
You are a support assistant for an online bookstore. Answer in two sentences or fewer.<|eot_id|><|start_header_id|>user<|end_header_id|>
My order arrived with a torn cover. Can I get a replacement?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
I'm sorry your book arrived damaged. Yes, you can get a free replacement: reply with
your order number and a photo of the cover, and we will ship a new copy right away.Notice Today Date: 26 Jul 2024 in the template. Nobody typed it: the template inserts that default unless the server passes a date. Templates quietly add tokens, and sometimes wrong facts, so always look at the rendered prompt. The tokens lesson covers tokenizers and templates in depth, and the generation lesson covers how the sampler picks tokens and when generation stops.
What limits speed: memory, bandwidth, and compute
A GPU has three resources that matter for inference, and each phase of the request runs out of a different one.
- Memory capacity (80 GB on an H100): it must hold the weights (about 16 GB) plus the KV cache of every active request. It decides how many requests fit at once.
- Memory bandwidth (3.35 TB/s on an H100 SXM): how fast the GPU can read what is stored. Every forward pass reads all 16 GB of weights.
- Compute (about 989 TFLOPS of dense BF16 math): how fast it can multiply and add. A forward pass does about 2 floating-point operations (FLOPs) per weight per token, so about 16 GFLOP per token for this model.
A forward pass takes at least as long as the slower of two jobs: reading the weights, and doing the math for the tokens in that pass. Work out both for our request:
Idealized floors for one forward pass, Llama 3.1 8B in BF16 on an H100 SXM
- Weight bytes
8.03 billion × 2 bytes ≈ 16.06 GB - Time to read them
16.06 GB / 3.35 TB/s ≈ 4.8 ms - Math for one token
2 × 8.03 billion ≈ 16.06 GFLOP → 16.06 GFLOP / 989 TFLOPS ≈ 0.016 ms - Math for the 66-token prefill
66 × 16.06 GFLOP ≈ 1.06 TFLOP → about 1.1 ms - Math for a 2,000-token prefill
2,000 × 16.06 GFLOP ≈ 32.1 TFLOP → about 32.5 ms
ResultA decode step spends 4.8 ms reading and 0.016 ms computing
Decode is lopsided: 300 times more time goes to reading weights than to math, so the compute units sit mostly idle. That is why a single stream of Llama 3.1 8B on an H100 tops out near 200 tokens per second, however fast the math is. A long prefill is the opposite: it does enough math per weight read to keep the compute units busy.
Two consequences follow. First, our 66-token prefill costs about the same as one decode step, so time to first token stays low for short prompts; an 8,000-token prompt needs at least 130 ms of math before the first token. Second, the way to use the idle compute in decode is to process many requests’ tokens in the same pass. One read of the weights then serves every request in the batch, which is the subject of the batching lesson.
Go deeperArithmetic intensity and the 295-token crossover
Arithmetic intensity is the number of FLOPs done per byte read. A decode step for one request does 2 FLOPs per weight and reads 2 bytes per weight: 1 FLOP per byte. The H100 can do 989 × 10^12 FLOPs while reading 3.35 × 10^12 bytes, a ratio of about 295 FLOPs per byte. Any pass with lower intensity waits on memory.
Processing N tokens in one pass multiplies the math by N without reading the weights again, so the intensity becomes about N FLOPs per byte. It reaches 295 at N ≈ 295, the crossover in the chart. Prompt tokens in prefill and requests in a decode batch both count toward N.
The model ignores two costs. Attention math grows with the square of the context, adding about 13% to an 8,000-token prefill of this model. Decode also reads each request’s KV cache, 128 KiB per cached token, which the estimate script below includes. Real kernels reach perhaps 60 to 80% of peak bandwidth, so measured times sit above these floors.
The metrics users feel, and how they trade off
Users do not see FLOPs. They see how long before text appears, how smoothly it flows, and how long until it is done. Operators also care how many users one GPU can serve. Each is a different number:
| Metric | What it measures | Our request (illustrative) |
|---|---|---|
| Time to first token (TTFT) | From sending the request to the first token arriving | 34 ms |
| Inter-token latency (ITL) | The gap between two consecutive tokens arriving | 7 ms |
| Time per output token (TPOT) | Average gap after the first token: (E2E − TTFT) / (output tokens − 1) | (307 − 34) / 39 = 7.0 ms |
| End-to-end latency (E2E) | From sending the request to the last token arriving | 307 ms |
| Throughput | Work finished per second by the whole server, such as output tokens or requests | Depends on every other request |
Where the 34 ms and 307 ms come from (illustrative)
- Request travels to the server
10 ms - Parse, apply the template, tokenize
2 ms - Queue wait on an idle server
0 ms - Prefill 66 tokens and sample the first token
12 ms (the floor is 4.8 ms) - First token travels back
10 ms → TTFT = 10 + 2 + 12 + 10 = 34 ms - 39 decode steps at 7 ms each
273 ms (the floor is 4.8 ms per step) - End of stream reaches the client
E2E = 34 + 273 = 307 ms
ResultE2E ≈ TTFT + (output tokens − 1) × TPOT
The last line is worth memorizing. A 500-token answer at 7 ms per token takes at least 3.5 s, however good the TTFT. Streaming does not shorten that, but it lets the user start reading at 34 ms instead of staring at a spinner for 307 ms.
These metrics pull against each other, because every request shares the same GPU. The biggest tension is batching. The script later in this lesson estimates the floors for Llama 3.1 8B with every request holding 1,000 tokens:
| Requests per decode step | Step time | ITL each user sees | Server output |
|---|---|---|---|
| 1 | 4.83 ms | 4.83 ms | 207 tokens/s |
| 8 | 5.11 ms | 5.11 ms | 1,566 tokens/s |
| 32 | 6.05 ms | 6.05 ms | 5,293 tokens/s |
| 128 | 9.80 ms | 9.80 ms | 13,058 tokens/s |
Going from 1 to 32 requests makes each stream 25% slower and the server 25 times more productive. At an illustrative $3 per GPU-hour, that is the difference between about $4.03 and $0.16 per million output tokens. Most of this job is choosing where to sit on curves like this one.
| Change | Improves | Worsens |
|---|---|---|
| Larger batches | Throughput and cost per token | ITL rises; a full KV cache makes new requests queue, raising TTFT |
| Starting a newcomer’s long prefill right away | That request’s TTFT | Running streams pause while the prefill runs |
| Longer maximum output | Complete answers | E2E, and each request holds cache memory longer, so fewer fit |
| Streaming | Perceived wait: text appears at TTFT | Nothing: total work and E2E stay the same |
| Fewer bytes per weight (quantization) | Decode speed and memory | Possible quality loss, which you must measure |
Try it: run a prediction and estimate a request
You need Python 3.9 or later and NumPy. Start with the smallest possible model: two weights and a bias, fixed in the file. The script computes one prediction in plain Python and again with NumPy. Nothing is trained; the weights are only read, which is the definition of inference. Save it as first_prediction.py and run it:
import numpy as np
# Inference only reads fixed weights; nothing here is trained or updated.
weights = [0.5, -0.25]
bias = 1.0
inputs = [2.0, 3.0]
python_prediction = sum(w * x for w, x in zip(weights, inputs)) + bias
numpy_prediction = float(np.dot(weights, inputs) + bias)
print(f"Python prediction: {python_prediction}")
print(f"NumPy prediction: {numpy_prediction}")
# Each weight costs one multiply and one add per token: 2 FLOPs.
flops = 2 * len(weights)
print(f"FLOPs for this prediction: {flops}")
print(f"FLOPs per token, Llama 3.1 8B: {2 * 8.03e9 / 1e9:.2f} billion")Python prediction: 1.25
NumPy prediction: 1.25
FLOPs for this prediction: 4
FLOPs per token, Llama 3.1 8B: 16.06 billionBoth ways give 1.25, because both do the same arithmetic: 2.0 × 0.5 + 3.0 × (−0.25) + 1.0. A real model does exactly this multiply-and-add, one multiply and one add per weight, with 8.03 billion weights instead of two. That is where the 16.06 billion FLOPs per token in this lesson’s estimates come from.
Next, turn this lesson’s arithmetic into a tool. The script below estimates idealized floors for our request, for longer prompts, and for different batch sizes. Save it as estimate_request.py and run it:
import numpy as np
# Llama 3.1 8B in BF16 on one H100 SXM, from published specifications
params = 8.03e9
weight_bytes = params * 2 # 2 bytes per BF16 weight
kv_per_token = 131_072 # bytes of KV cache per token (128 KiB)
bandwidth = 3.35e12 # bytes per second
peak_flops = 989e12 # dense BF16 FLOP per second
def pass_ms(new_tokens, cached_tokens):
"""Idealized forward pass: the slower of reading memory and doing math."""
read = (weight_bytes + cached_tokens * kv_per_token) / bandwidth
math = 2 * params * new_tokens / peak_flops
return 1000 * max(read, math)
prompt, output = 66, 40
prefill = pass_ms(prompt, 0)
decode = np.array([pass_ms(1, prompt + step) for step in range(1, output)])
print(f"prefill, {prompt} tokens: {prefill:.2f} ms")
print(f"one decode step: {decode.mean():.2f} ms")
print(f"GPU floor for request: {prefill + decode.sum():.0f} ms")
for tokens in (66, 295, 2_000, 8_000):
print(f"prefill {tokens:>5,} tokens: {pass_ms(tokens, 0):6.1f} ms")
for batch in (1, 8, 32, 128):
step = pass_ms(batch, batch * 1_000) # every request holds 1,000 tokens
rate = batch / step * 1000
print(f"batch {batch:>3}: step {step:5.2f} ms, {rate:6,.0f} tokens/s")prefill, 66 tokens: 4.79 ms
one decode step: 4.80 ms
GPU floor for request: 192 ms
prefill 66 tokens: 4.8 ms
prefill 295 tokens: 4.8 ms
prefill 2,000 tokens: 32.5 ms
prefill 8,000 tokens: 129.9 ms
batch 1: step 4.83 ms, 207 tokens/s
batch 8: step 5.11 ms, 1,566 tokens/s
batch 32: step 6.05 ms, 5,293 tokens/s
batch 128: step 9.80 ms, 13,058 tokens/sRead it in three parts. The GPU floor for our request is 192 ms, against 273 ms of illustrative decode in the timeline, a gap that real kernel efficiency and overheads fill. Prefill stays at 4.8 ms up to about 295 tokens and then grows with the prompt. Batching raises server output much faster than it raises step time. Change prompt, output, or the batch sizes and predict the result before you run.
To count tokens for your own prompts, use the model’s real tokenizer. This needs the transformers package and access to the gated Llama 3.1 model on Hugging Face; for the example prompt it prints 66.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
messages = [
{"role": "system", "content": "You are a support assistant for an online "
"bookstore. Answer in two sentences or fewer."},
{"role": "user", "content": "My order arrived with a torn cover. "
"Can I get a replacement?"},
]
text = tokenizer.apply_chat_template(messages, tokenize=False,
add_generation_prompt=True)
ids = tokenizer(text, add_special_tokens=False)["input_ids"]
print(len(ids))Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Your latency estimate is far too low | You counted words, or tokens before the chat template. | Count tokens after applying the template. Here 27 words became 66 tokens. |
| The first request after startup is very slow | It included model loading, compilation, or memory setup. | Send warm-up requests and leave them out of your measurements. |
| A benchmark reports high tokens per second, but users complain | It measured throughput and ignored TTFT and ITL. | Report per-user latency percentiles next to throughput. |
| Two runs of the same benchmark disagree | Output lengths differed, because generation stopped at different points. | Fix the prompts, max_tokens, sampling settings, and stop rules before comparing. |
| Memory runs out although each request is small | The KV cache for all concurrent requests was not counted. | Budget weights plus 128 KiB per token for every active token (for Llama 3.1 8B). |
How real serving engines are built
Production engines such as vLLM, SGLang, and TensorRT-LLM follow the same path you just traced. What they add is machinery to keep the GPU busy and the memory well used:
- An HTTP server with an OpenAI-compatible API that applies the chat template, tokenizes, and streams server-sent events.
- A scheduler that runs continuous batching: requests join and leave the running batch at every decode step instead of waiting for a whole batch to finish.
- A paged KV cache that hands memory to requests in small blocks and can share blocks between requests with the same prefix.
- Fast kernels for attention and matrix multiplication, plus captured GPU launch sequences (CUDA graphs) that cut per-step overhead in decode.
- Metrics for every stage, such as vLLM’s
vllm:time_to_first_token_secondsandvllm:inter_token_latency_secondshistograms.
This course builds the understanding underneath each item. The next lessons cover tensors and the forward pass, tokens and embeddings, attention, the generation loop, the KV cache, batching, and quantization. The last lesson, serving and measurement, measures a real endpoint and ties everything together. The vLLM course then applies it to a production engine.
Cheat sheet
- Inference reads fixed weights; each request’s token IDs, KV cache, and sampling state grow as it runs.
- Path: chat template → tokenizer → queue → prefill → decode loop → detokenizer → stream.
- Count tokens after the chat template: 27 words became 66 tokens in this lesson’s example.
- Decode reads all weights every step: about 4.8 ms for Llama 3.1 8B on an H100, so about 200 tokens per second per stream.
- Prefill math grows with prompt length and dominates above about 295 tokens per pass.
- TTFT is the wait, ITL is the rhythm, E2E ≈ TTFT + (tokens − 1) × TPOT, and throughput is the server’s total.
- Batching raises throughput much faster than it raises ITL, until memory or compute runs out.
Walkthrough
Follow one request from prompt to response
Knowledge check