Unit 1 of 9

What is inference engineering?

  • 45 min
  • Reading, walkthrough, and knowledge check

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.

What stays fixed and what changes while a request runs
PartDuring inferenceShared 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)FixedYes
The request’s token IDsGrow by one per generated tokenNo
The request’s KV cacheGrows by one position per token, per layerNo
Sampling state (random seed, stop rules, counters)Updated every stepNo
Becoming an AI inference engineer · Watch on YouTube

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:

The same model in a notebook and in a service
QuestionNotebookService
When are the weights loaded?Every runOnce, at startup
How many requests run at once?OneDozens or hundreds, batched together
What happens when the GPU is busy?Nothing else is waitingA scheduler queues new requests or adds them to the running batch
Where does each request’s state live?In local variablesIn a shared KV cache budget that can fill up
When does the user see output?When the call returnsToken by token, as a stream
What if the user closes the tab?Not a concernThe 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.

What the chat app sends (JSON)
{
  "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
}
Chat appsystem and usermessagesChat templateadds roles andmarkersTokenizer66 token IDsPrefill66 positions in onepassDecode loop39 more passes, onetoken eachDetokenizertoken IDs back totextStreamone event per pieceof textUser's screentext appears as itarrivesfirst token
The request path. Text goes in along the top row; tokens come back along the bottom row, one per decode step, while the user reads.
  1. 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.

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

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

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

  5. 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, then sorry, 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.

  6. 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).

The prompt after the chat template (66 tokens)
<|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|>

An example reply (39 tokens, then <|eot_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

  1. Weight bytes8.03 billion × 2 bytes ≈ 16.06 GB
  2. Time to read them16.06 GB / 3.35 TB/s ≈ 4.8 ms
  3. Math for one token2 × 8.03 billion ≈ 16.06 GFLOP → 16.06 GFLOP / 989 TFLOPS ≈ 0.016 ms
  4. Math for the 66-token prefill66 × 16.06 GFLOP ≈ 1.06 TFLOP → about 1.1 ms
  5. Math for a 2,000-token prefill2,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.

Milliseconds per pass (lower bound)01020304005001,0001,5002,000Tokens processed in one forward passReading the weights: 1, 4.8Reading the weights: 2,000, 4.8Doing the math: 1, 0.02Doing the math: 2,000, 32.5Doing the mathReading the weightscrossover near 295 tokensReading the weightsDoing the mathIdealized floors from published H100 SXM specifications, not measurements.
The time for one forward pass is set by whichever line is higher. Below about 295 tokens per pass, reading the weights dominates; above it, math does. A decode step for one request sits at the far left.

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:

The metrics users and operators track, measured from the client’s side
MetricWhat it measuresOur request (illustrative)
Time to first token (TTFT)From sending the request to the first token arriving34 ms
Inter-token latency (ITL)The gap between two consecutive tokens arriving7 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 arriving307 ms
ThroughputWork finished per second by the whole server, such as output tokens or requestsDepends on every other request
NetworkNetwork: 0 to 10GPUGPU: 12 to 24GPU: 24 to 31GPU: 31 to 38GPU: 38 to 45GPU: 45 to 52GPU: 52 to 59GPU: 59 to 66GPU: 66 to 73GPU: 73 to 80GPU: 80 to 87GPU: 87 to 94GPU: 94 to 101GPU: 101 to 108GPU: 108 to 115GPU: 115 to 122GPU: 122 to 129GPU: 129 to 136GPU: 136 to 143GPU: 143 to 150GPU: 150 to 157GPU: 157 to 164GPU: 164 to 171GPU: 171 to 178GPU: 178 to 185GPU: 185 to 192GPU: 192 to 199GPU: 199 to 206GPU: 206 to 213GPU: 213 to 220GPU: 220 to 227GPU: 227 to 234GPU: 234 to 241GPU: 241 to 248GPU: 248 to 255GPU: 255 to 262GPU: 262 to 269GPU: 269 to 276GPU: 276 to 283GPU: 283 to 290GPU: 290 to 297ScreenScreen: 34 to 35.5Screen: 41 to 42.5Screen: 48 to 49.5Screen: 55 to 56.5Screen: 62 to 63.5Screen: 69 to 70.5Screen: 76 to 77.5Screen: 83 to 84.5Screen: 90 to 91.5Screen: 97 to 98.5Screen: 104 to 106Screen: 111 to 113Screen: 118 to 120Screen: 125 to 127Screen: 132 to 134Screen: 139 to 141Screen: 146 to 148Screen: 153 to 155Screen: 160 to 162Screen: 167 to 169Screen: 174 to 176Screen: 181 to 183Screen: 188 to 190Screen: 195 to 197Screen: 202 to 204Screen: 209 to 211Screen: 216 to 218Screen: 223 to 225Screen: 230 to 232Screen: 237 to 239Screen: 244 to 246Screen: 251 to 253Screen: 258 to 260Screen: 265 to 267Screen: 272 to 274Screen: 279 to 281Screen: 286 to 288Screen: 293 to 295Screen: 300 to 30204080120160200240280320Milliseconds after the user presses Enter (illustrative)first token, 34 msdone, 307 msrequest in flightprefilldecode steptoken appears
The example request over time, with illustrative timings. The first token reaches the screen at 34 ms; after that, one token arrives every 7 ms until the stream ends at 307 ms.

Where the 34 ms and 307 ms come from (illustrative)

  1. Request travels to the server10 ms
  2. Parse, apply the template, tokenize2 ms
  3. Queue wait on an idle server0 ms
  4. Prefill 66 tokens and sample the first token12 ms (the floor is 4.8 ms)
  5. First token travels back10 ms → TTFT = 10 + 2 + 12 + 10 = 34 ms
  6. 39 decode steps at 7 ms each273 ms (the floor is 4.8 ms per step)
  7. End of stream reaches the clientE2E = 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:

Batching trades a little ITL for a lot of throughput (idealized floors)
Requests per decode stepStep timeITL each user seesServer output
14.83 ms4.83 ms207 tokens/s
85.11 ms5.11 ms1,566 tokens/s
326.05 ms6.05 ms5,293 tokens/s
1289.80 ms9.80 ms13,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.

Common changes and what they cost
ChangeImprovesWorsens
Larger batchesThroughput and cost per tokenITL rises; a full KV cache makes new requests queue, raising TTFT
Starting a newcomer’s long prefill right awayThat request’s TTFTRunning streams pause while the prefill runs
Longer maximum outputComplete answersE2E, and each request holds cache memory longer, so fewer fit
StreamingPerceived wait: text appears at TTFTNothing: total work and E2E stay the same
Fewer bytes per weight (quantization)Decode speed and memoryPossible 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:

first_prediction.py
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")
You should see
Python prediction: 1.25
NumPy prediction:  1.25
FLOPs for this prediction: 4
FLOPs per token, Llama 3.1 8B: 16.06 billion

Both 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:

estimate_request.py
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")
You should see
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/s

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

count_tokens.py (optional)
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

Symptoms you may see, their usual cause, and the fix
SymptomLikely causeFix
Your latency estimate is far too lowYou 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 slowIt 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 complainIt measured throughput and ignored TTFT and ITL.Report per-user latency percentiles next to throughput.
Two runs of the same benchmark disagreeOutput 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 smallThe 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_seconds and vllm:inter_token_latency_seconds histograms.

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

Request traceReady

Knowledge check

Which value changes during ordinary inference?

Choose one answer

Sources and further reading

Finished this unit?