Chapter 0 · Inference Basics¶
0.1 What are the two phases of LLM inference, and how do prefill and decode differ? ★★★¶
One-sentence answer
LLM inference has two phases, prefill and decode: prefill processes the whole prompt at once in parallel, computing and caching the keys and values of all prompt tokens (the KV cache) and producing the first output token; decode then generates the remaining tokens one at a time, processing only one new token per step yet reading all the weights and the KV cache from GPU memory at every step. Prefill is therefore compute-bound and determines the time to first token (TTFT), while decode is memory-bandwidth-bound and determines the time per output token (TPOT).
I will address three aspects: what each phase does, why their bottlenecks differ, and what this difference means for an inference system.
(1) Prefill processes the whole prompt in parallel, whereas decode generates tokens sequentially, one at a time.
Autoregressive generation means the model predicts the next token from all existing tokens, appends it to the input, and predicts again. In this process the prompt is fully known from the start, so the prefill phase can, just like the forward pass in training, use the causal mask to compute all prompt tokens in parallel in a single forward pass. This forward pass has two outputs: the key and value of every prompt token at every layer are stored, forming the KV cache (see Chapter 1); and the output distribution at the last position is used to sample the first output token. Then the decode phase begins: since token \(t+1\) cannot be computed until token \(t\) has been sampled, generation can only proceed step by step. Each step feeds only the newest token into the model, computes its query, key and value, appends the new key and value to the KV cache, and attends over the entire cached history to obtain the distribution of the next token; this loop continues until an end-of-sequence token is generated or the length limit is reached.
(2) The two phases have different bottlenecks: prefill is compute-bound, and decode is memory-bandwidth-bound.
Before the GPU can compute, it must first read the weights from GPU memory (HBM) into its compute units. In prefill, hundreds or thousands of tokens pass through each layer together, so the main operation is matrix-matrix multiplication; each read of the weights is reused for all those tokens, the compute units can be fully used, and the bottleneck is compute. In decode, each sequence has only one token per step, so the main operation degenerates into matrix-vector multiplication: all the weights are read once, yet used for computation on just this one token; in addition, the sequence's entire KV cache must be read. GPU compute is far faster than memory bandwidth, so decode spends most of its time waiting for data to arrive, and the bottleneck is memory bandwidth (see 0.2 for the quantitative analysis).
(3) This difference determines the latency breakdown, the unit cost and the design of inference systems.
- Latency breakdown: The duration of prefill determines how long the user waits for the first token (TTFT), and it grows with prompt length; the duration of each decode step determines how fast subsequent tokens are generated (TPOT), and it grows with model size and context length (see 0.3 for the metric definitions). For requests with long outputs, such as reasoning models that routinely generate thousands of tokens, the total time is dominated by decode.
- Unit cost: In prefill, many tokens share a single read of the weights, so each input token consumes far less GPU time than each output token. This is also why the price of output tokens in APIs is usually several times that of input tokens.
- System design: The two phases have different needs, and putting them in the same batch causes interference: the prefill of a long prompt makes every request decoding in the same step wait. Chunked prefill and prefill/decode disaggregation (P/D disaggregation) exist precisely to address this; see Chapter 3.
In summary: prefill is "read the weights once, compute many tokens", so it is compute-bound and determines TTFT; decode is "read the weights once, compute only one token per sequence", so it is bandwidth-bound and determines TPOT. Most inference optimization revolves around this difference.
Going deeper: comparing the two phases, and their orders of magnitude
(1) Comparing the two phases.
| Prefill | Decode | |
|---|---|---|
| Tokens processed per step | The whole prompt (hundreds to thousands) | One per sequence |
| Main operation | Matrix × matrix | Matrix × vector (a very thin matrix across the batch) |
| Bottleneck | Compute | Memory bandwidth: every step reads all weights and the KV cache |
| What it does to the KV cache | Writes the K and V of all prompt tokens at once | Appends one token's K and V per step and reads the whole history |
| Metric it determines | TTFT | TPOT / ITL |
| Time grows with | Prompt length (the attention part grows roughly quadratically for very long prompts) | Output length, model size, context length |
(2) An intuition for the orders of magnitude: processing an input token is far cheaper than generating an output token.
Take an 8B model on one H100 (see 0.4 for the estimation method): assuming the achieved compute is half of peak, prefilling a 1,000-token prompt takes about 30 ms; meanwhile each decode step must read about 16 GB of weights, with a lower bound of about 5 ms. In other words, processing 1,000 input tokens takes only about as long as six or seven decode steps.
(3) Prefill is not always compute-bound.
When the prompt is very short (for example, only a few tokens), prefill has too few tokens to amortize the weight reads, so it is also bandwidth-bound; when the prompt is extremely long, attention compute grows quadratically with length and becomes the main cost of prefill, and the efficiency of attention kernels such as FlashAttention becomes critical (see Chapter 2 of the "Model Architecture" direction).
Follow-up questions
Follow-up 1: Is the first output token generated in the prefill phase or the decode phase?
In the prefill phase. The prefill forward pass outputs the distribution of the next token at the last prompt position, from which the first output token is sampled, so TTFT includes the queueing time and the entire prefill. Only the tokens after it are each generated by one decode step.
Follow-up 2: If training can be parallel, why can't generation be?
Because during training the full sequence is known, whereas during generation the next token depends on the sampled value of the previous one. In training, the causal mask lets each position see only itself and earlier tokens, so a single forward pass computes the predictions for all positions in parallel (teacher forcing). Prefill can be parallel for the same reason: the prompt is also known. Output tokens, however, do not exist until they are sampled, so they can only be generated one at a time. Speculative decoding first guesses several tokens cheaply and then has the large model verify them in one parallel pass, partially working around this limitation (see Chapter 3).
Follow-up 3: Why are output tokens more expensive than input tokens in APIs?
Because generating an output token takes far more GPU time than processing an input token. Input tokens are processed in parallel during prefill, where one read of the weights is shared by many tokens; output tokens are generated one by one during decode, where every step reads the weights and the KV cache again, and the KV cache memory stays occupied throughout generation. By the same logic, input tokens that hit the prefix cache skip even the prefill compute, which is why they are priced lower (see Chapter 1).
Common mistakes
- Do not say that prefill also processes tokens one at a time: The prompt is known, and all prompt tokens are computed in parallel in one forward pass.
- Do not say that decode is compute-bound: Each decode step involves very little computation; the bottleneck is the memory bandwidth needed to read the weights and the KV cache.
- Do not say that the KV cache is created only during decode: The prompt's KV cache is written all at once during prefill; decode merely appends to it step by step.
- Do not say that TTFT is determined by decode speed: TTFT is mainly determined by queueing and prefill; it is TPOT that is determined by decode.
0.2 Why is the decode phase memory-bound? ★★¶
One-sentence answer
Because every decode step reads all the weights from GPU memory but computes only one token per sequence: in bf16, every 2 bytes of weights read support only about 2 floating-point operations, so the arithmetic intensity is about 1 FLOP per byte (about \(B\) for batch size \(B\)), far below the GPU's ratio of compute to bandwidth (about 300 on an H100), so the compute units spend most of their time waiting for data. A larger batch lets one read of the weights serve several sequences, so throughput grows almost linearly; however, each sequence's KV cache cannot be shared across the batch, and memory limits how large the batch can be.
I will address three aspects: how to tell what limits an operation, why decode falls on the bandwidth-bound side, and why batching helps and where its limits lie.
(1) The criterion is arithmetic intensity, i.e. how many floating-point operations are performed per byte read from memory.
Arithmetic intensity is defined as the number of floating-point operations (FLOPs) of an operation divided by the number of bytes it reads from and writes to memory. The roofline model (Williams et al. 2009) relates it to two hardware limits: the GPU can perform at most \(P\) floating-point operations per second (peak compute) and move at most \(W\) bytes per second to and from memory (bandwidth). If an operation's arithmetic intensity is below \(P/W\), the computation finishes long before the data has been read, so its speed is set by bandwidth, which is called memory-bound; otherwise it is set by compute, which is called compute-bound. The threshold \(P/W\) is called the ridge point. On an H100, for example, dense bf16 compute is about 989 TFLOPS and memory bandwidth is about 3.35 TB/s, so the ridge point is about 300 operations per byte. In other words, an operation must perform at least about 300 operations per byte read to keep the compute units busy.
(2) The arithmetic intensity of decode is roughly the batch size, far below the ridge point.
The main computation in decode is multiplying the weight matrices by the current token. Each parameter performs one multiplication and one addition per token, i.e. 2 FLOPs, while in bf16 each parameter takes 2 bytes. Hence at batch size 1, every 2 bytes read support only 2 operations, an arithmetic intensity of about 1, roughly one three-hundredth of the H100's ridge point. As a result, the compute units are idle most of the time, waiting for weights to arrive from memory, and the time per step is roughly "weight bytes divided by bandwidth". By contrast, in prefill \(T\) tokens are multiplied by the same weights at once, so the arithmetic intensity is about \(T\); a prompt of a few hundred tokens is enough to cross the ridge point, which is why prefill is compute-bound. In addition, decode must read the entire KV cache while doing very little computation on it, which adds further pressure on bandwidth.
(3) Batching raises throughput substantially, but it has three limits.
Since the bottleneck is reading the weights, decoding \(B\) sequences together reads the weights once and computes one token for each of the \(B\) sequences, raising the arithmetic intensity to about \(B\). While \(B\) is far below the ridge point, the time per step barely changes, yet throughput grows almost linearly. However, this gain has three limits:
- The KV cache cannot be shared across the batch: Each sequence's KV cache is its own, so the number of KV bytes to read grows in proportion to the batch, and the arithmetic intensity of the attention part does not increase with batch size. The longer the context, the larger this part's share, and the smaller the gain from a bigger batch.
- Memory caps the batch size: Most of the memory left after the weights holds the KV cache, and the batch can be no larger than the number of sequences that fit. The size of the KV cache and how memory is managed therefore directly determine throughput (see Chapter 1).
- The larger the batch, the slower each request: Each step reads more KV cache and does more computation, and beyond the ridge point the time per step grows linearly with batch size, so the generation speed each user experiences drops. This is the trade-off between throughput and latency (see 0.3).
In summary: decode is memory-bound fundamentally because each full read of the weights computes only one token per sequence; batching raises throughput by amortizing the weight reads, and its ceiling is set mainly by the KV cache.
Going deeper: the roofline formula, the arithmetic intensity of the two kinds of operations, and common hardware
(1) The roofline model.
Here \(P\) is peak compute, \(W\) is memory bandwidth, and \(I\) is arithmetic intensity. When \(I < P/W\), attainable compute is set by \(I \times W\) (memory-bound); when \(I > P/W\), attainable compute is capped by \(P\) (compute-bound).
(2) In decode, the arithmetic intensity of the linear layers is about \(B\), and that of attention is about the GQA group size.
For a model with \(N\) parameters, one decode step at batch size \(B\) costs about \(2NB\) FLOPs in the linear layers and reads \(2N\) bytes of bf16 weights:
Attention is different. Let the context length be \(s\), the head dimension \(d_h\), and let each KV head be shared by \(g\) query heads (\(g\) is the GQA group size; \(g=1\) for MHA). On one KV head, \(QK^\top\) and the weighted sum over \(V\) together take about \(4gsd_h\) FLOPs, while reading K and V takes \(4sd_h\) bytes (bf16):
This is independent of both batch size and context length. For example, with 32 query heads and 8 KV heads, \(g=4\), far below the ridge point, so attention in decode is memory-bound no matter how large the batch. This also shows that GQA and MLA not only shrink the KV cache but also raise the arithmetic intensity of attention in decode (see Chapter 2 of the "Model Architecture" direction).
(3) The ridge points of common GPUs.
| GPU | Dense bf16 compute | Memory bandwidth | Ridge point (operations per byte) |
|---|---|---|---|
| A100 SXM 80GB | About 312 TFLOPS | About 2.0 TB/s | About 150 |
| H100 SXM | About 989 TFLOPS | About 3.35 TB/s | About 300 |
The headline compute figure on a datasheet is often the value with structured sparsity (1,979 TFLOPS for the H100); estimates should use the dense value. Since ridge points are usually between one or two hundred and a few hundred, the batch would need to reach several hundred for the linear layers in decode to become compute-bound; in practice, the KV cache usually fills memory well before that.
Follow-up questions
Follow-up 1: If you switch to a GPU with more compute but the same bandwidth, does batch-1 decode get faster?
Hardly at all. At batch size 1, the time per step is set by the time needed to read the weights; the compute units are already idle most of the time, and more compute only makes them idler. Conversely, a GPU with higher bandwidth (for example, a model with faster HBM) directly speeds up batch-1 decode. Compute becomes the bottleneck only when the batch is large enough to cross the ridge point.
Follow-up 2: Since compute sits idle during decode, how can it be put to use?
The core idea is to make each read of the weights serve more tokens. A larger batch does this along the sequence dimension; speculative decoding does it along the time dimension: it first guesses the next few tokens cheaply, then has the large model verify them in parallel in one forward pass, so a single read of the weights may settle several tokens, and the extra computation is absorbed by the idle compute (see Chapter 3).
Follow-up 3: Why does quantizing only the weights (e.g. to INT4) speed up decode, even when computation still runs in bf16?
Because decode time depends mainly on how many bytes are read, not on how much computation is done. With weights stored in 4 bits, each step reads about a quarter of the bytes of bf16; dequantizing them back to bf16 inside the kernel adds some computation, but that computation is absorbed by idle compute and barely affects the time. When the batch is very large and close to compute-bound, however, this gain shrinks (see Chapter 3 for quantization methods).
Common mistakes
- Do not say that decode is slow because of attention's \(O(n^2)\) computation: The attention computation in each decode step grows only linearly with context length and is small in itself; decode is slow because it reads the weights and the KV cache.
- Do not say that a larger batch reduces per-token latency: A larger batch raises total throughput; the time per step does not shrink, and it grows once past the ridge point.
- Do not say that batching amortizes the reads of the KV cache: Each sequence's KV cache is its own; only the reads of the weights can be amortized (except in special implementations for shared prefixes).
- Do not estimate decode speed at small batch sizes from peak compute: Use bandwidth instead; an estimate from compute comes out two orders of magnitude too high (see 0.4).
0.3 Which metrics matter for an inference service? ★★¶
One-sentence answer
An inference service focuses on two kinds of metrics: latency metrics, namely TTFT (time to first token, set by queueing and prefill), TPOT and ITL (the average time per output token and the gap between adjacent tokens, set by the time of each decode step), and end-to-end latency; and capacity metrics, namely throughput (tokens generated per second per GPU) and goodput (the throughput that can be sustained while meeting latency SLOs). A larger batch raises throughput but lengthens each step and worsens latency, so in practice one looks for an operating point under the SLO constraints.
I will address three aspects: latency metrics, throughput and goodput, and the trade-off between them.
(1) Latency metrics describe a single user's experience, and each corresponds to a different stage of the request.
- TTFT (time to first token): The time from a request's arrival to receiving its first output token, including queueing and the prefill of the whole prompt. The longer the prompt and the busier the system, the larger the TTFT; it determines whether the service feels responsive.
- TPOT (time per output token): The average time to generate each output token after the first, set by how long each decode step takes; it determines how fast text appears when streaming.
- ITL (inter-token latency): The time gap between each pair of adjacent output tokens. TPOT is its average within a request, but ITL looks at the whole distribution, especially the tail: if the prefill of a long prompt cuts into the same batch midway, a few token gaps suddenly stretch and the user notices stutter, which the average hides.
- End-to-end latency (E2E latency): The time from a request's arrival to the generation of its last token, roughly TTFT plus TPOT times the number of remaining tokens. Non-streaming calls and multi-step agent calls care more about this metric.
(2) Throughput determines cost, while goodput combines throughput with latency requirements.
Throughput usually refers to the number of tokens the system generates per second (often normalized per GPU), or the number of requests completed per second, and it directly determines the cost per token. Looking at throughput alone is misleading, however: an enormous batch yields very high throughput, but by then each user's latency may already be unacceptable. Services therefore specify SLOs (service level objectives), for example "90% of requests have TTFT below some value and TPOT below some value". Goodput counts only the part of throughput that meets the SLOs; DistServe (Zhong et al. 2024) defines it concretely as the maximum request rate per GPU that can be sustained while the SLO attainment meets its target (for example, 90% of requests meeting both the TTFT and TPOT constraints). It reflects a system's real serving capacity better than raw throughput.
(3) Throughput and latency trade off, and the operating point is chosen according to the SLOs and the application.
This trade-off, again, stems from the bandwidth bottleneck of decode (see 0.2). The larger the batch, the more sequences one read of the weights serves, so throughput rises; however, each step also reads more KV cache and does more computation, so each step becomes slower and TPOT rises; at the same time, more requests compete for resources, queueing and interference between prefills both increase, and the tails of TTFT and ITL worsen. The system therefore picks an operating point under the SLO constraints: a chat product must first keep TTFT and TPOT within what users accept and then maximize throughput; offline batch jobs (such as generating synthetic data or running evaluations) barely care about per-request latency and simply maximize throughput. Different applications also have different emphases: a reasoning model generates thousands or tens of thousands of tokens per answer, so TPOT dominates the total time; an agent calls the model many times in a row with an ever-longer context, so TTFT and prefix caching (see Chapter 1) become especially critical.
In summary: latency metrics measure a single user's experience and throughput measures cost, while goodput answers "how many requests can be served while meeting the latency requirements", which is the number that matters most when evaluating an inference system.
Going deeper: formulas, a summary of metrics, and an example of SLOs
(1) Decomposing latency.
Here \(n_{\text{out}}\) is the number of output tokens. Different benchmarking tools compute TPOT and ITL slightly differently (for example, averaging within each request first or averaging over all tokens together), so check the definitions before comparing numbers across systems.
(2) Summary of metrics.
| Metric | Definition | Main drivers | Where it matters |
|---|---|---|---|
| TTFT | Request arrival → first output token | Queueing, prompt length, prefill speed | Interactive responsiveness |
| TPOT | Average time per token after the first | Decode step time: batch size, model size, context length | Streaming speed, long outputs |
| ITL | Gap between adjacent tokens (look at the distribution) | Decode step time, plus stalls from inserted prefills | Smoothness, tail latency (P99) |
| E2E latency | Request arrival → last token | TTFT plus all decode steps | Non-streaming calls, agents |
| Throughput | Tokens generated or requests completed per second per GPU | Batch size, memory utilization | Cost |
| Goodput | Throughput sustainable while meeting SLOs | Both latency and throughput | Real serving capacity |
(3) A public example of SLOs.
In MLPerf Inference, the Llama 2 70B server scenario requires TTFT of at most 2 s and TPOT of at most 200 ms; the interactive scenario added later tightens these to a TTFT of 450 ms and a TPOT of 40 ms (about 25 tokens per second per user). The same hardware achieves markedly lower throughput under the stricter SLOs, which is exactly the throughput–latency trade-off at work.
(4) Comparing systems with a curve.
Evaluations often plot results at different concurrency levels as a curve: the horizontal axis is the tokens per second each user receives (interactivity), and the vertical axis is the tokens generated per second per GPU (throughput). The closer the curve is to the upper right, the better the system; reporting only one point on the curve can easily hide how the system performs at the other end.
Follow-up questions
Follow-up 1: How would you reduce TTFT? And TPOT?
The means differ, because TTFT is mainly set by queueing and prefill, whereas TPOT is mainly set by the time of each decode step.
- Reducing TTFT: Use prefix caching to skip prefixes that have already been computed; use more tensor parallelism to speed up prefill; reduce queueing through scheduling, for example by limiting concurrency or prioritizing short requests; use P/D disaggregation so that prefill is not disturbed by decode; shorten the prompt.
- Reducing TPOT: Use a smaller batch; quantize the weights and the KV cache to reduce the bytes read per step; use speculative decoding so that each forward pass settles several tokens; use architectures such as GQA and MLA to shrink the KV cache; use tensor parallelism to spread the reads across the bandwidth of several GPUs (see Chapter 3 for acceleration methods).
Follow-up 2: How are TPOT and throughput related?
TPOT measures the speed of a single request and throughput measures the speed of the whole system; they are not reciprocals of each other. Throughput is roughly the batch size divided by the time per step. For example, with a batch of 64 and 25 ms per step, each user's TPOT is 25 ms (40 tokens per second), while the system's throughput is about 2,560 tokens per second. As the batch grows, TPOT gets worse while throughput improves, so the two must be reported separately.
Follow-up 3: Why is looking at average latency not enough?
Because the problems users notice usually lie in the tail. A system with a very low average TPOT can still subject a few requests to noticeable stutter or long waits, because of inserted long-prompt prefills, request queueing, or preemption caused by memory shortage. This is why SLOs are usually defined on percentiles such as P90 or P99 rather than on the mean.
Common mistakes
- Do not treat TPOT as the reciprocal of throughput: TPOT is the speed of a single request and throughput is the speed of the whole system; they differ by a factor of the batch size.
- Do not report only average latency: Stutters and long waits occur in the tail, so report percentiles such as P90 and P99.
- Do not say that higher throughput always means a better service: Throughput detached from SLOs is meaningless; look at goodput, which meets the latency requirements.
- Do not attribute TTFT entirely to model speed: Under high load, queueing time can far exceed the prefill itself.
0.4 How do you estimate inference speed and cost? ★¶
One-sentence answer
On the compute side, processing or generating one token takes about \(2N\) FLOPs (\(N\) is the parameter count), which can be used to estimate prefill time; decode is bandwidth-bound, so the speed of a single sequence is bounded by roughly "memory bandwidth ÷ bytes read per step". For example, an 8B model has about 16 GB of bf16 weights, so on an H100 with 3.35 TB/s of bandwidth it can generate at most about 200 tokens per second. Cost is roughly the GPU's hourly price divided by the tokens generated per hour, so the key is how large the batch can be.
I will address three aspects: how to estimate compute, how to estimate the upper bound on decode speed, and how to go from speed to cost.
(1) Compute: about \(2N\) FLOPs per token, which is used to estimate prefill time.
In the forward pass, every parameter performs one multiplication and one addition for each token, so the compute per token is about \(2N\) FLOPs (Kaplan et al. 2020), where \(N\) is the parameter count; this ignores attention scoring, which is a small share when the context is not too long. Prefill is compute-bound, so processing a prompt of length \(T\) takes roughly \(2NT\) divided by the achieved compute. For example, an 8B model processing 1,000 tokens needs about \(1.6\times10^{13}\) FLOPs; at half of the H100's dense compute (about 500 TFLOPS), this takes about 30 ms. For MoE models, \(N\) should be replaced by the number of parameters actually activated per token.
(2) Decode speed: the upper bound is the bandwidth divided by the bytes read per step.
Decode is memory-bound (see 0.2): each step must read at least all the weights and the current batch's KV cache, so the time per step has a lower bound:
Here \(M_{\text{weights}}\) is the size of the weights in bytes, \(M_{\text{KV}}\) is the size of each sequence's KV cache in bytes, \(B\) is the batch size, and \(W\) is the memory bandwidth. At batch size 1 with a short context, the KV cache can be ignored, and the speed of a single sequence is bounded by roughly the bandwidth divided by the weight bytes. For example, an 8B model has about 16 GB of bf16 weights and an H100 has about 3.35 TB/s of bandwidth, so each step takes at least about 5 ms, i.e. at most about 200 tokens per second; quantizing the weights to 4 bits (about 4 GB) raises this bound by about 4× (see Chapter 3 for weight quantization). Estimating from compute instead would wrongly give tens of thousands of tokens per second, two orders of magnitude too high. Real systems use only part of the peak bandwidth, so actual speed falls below this bound.
(3) Cost: the price of GPU time divided by throughput, where the key is how large the batch can be.
The cost per million tokens is roughly the GPU's hourly price divided by the tokens generated per hour (in millions). At batch size 1, a GPU generates only about 200 tokens per second, which is expensive; with a batch of several dozen, the weight reads are amortized and the time per step increases only modestly, so throughput can rise by one to two orders of magnitude and the unit cost falls proportionally. However, the batch size is capped by the memory available for the KV cache, and the larger the batch and the longer the context, the more KV cache each step must read and the slower each request becomes. The core of estimating cost is therefore estimating "how large a batch fits in memory while meeting the latency requirements" (see Chapter 1 for estimating the KV cache).
In summary: estimating inference performance comes down to two sentences: for prefill, look at compute: \(2N\) times the number of tokens, divided by compute; for decode, look at bandwidth: the bytes read per step, divided by bandwidth; cost then depends on how large the batch can be.
Going deeper: the estimation formulas and an order-of-magnitude example
(1) Three estimation formulas.
Here \(T\) is the prompt length, \(P\) is peak compute, MFU (model FLOPs utilization) is the fraction of peak compute actually achieved, throughput is measured in tokens per second, and \(t_{\text{step}}\) is the time of one decode step. As the counterpart of MFU, the fraction of peak bandwidth actually achieved is sometimes called MBU (model bandwidth utilization), a measure of how efficiently decode is implemented.
(2) An order-of-magnitude example: Llama 3 8B on one H100.
| Scenario | Data read per step | Lower bound on time per step | Upper bound on throughput |
|---|---|---|---|
| Batch 1, short context | Weights, about 16 GB | About 5 ms | About 200 tokens/s |
| Batch 32, 4K context per sequence | Weights, about 16 GB, plus KV cache, about 17 GB | About 10 ms | About 3,200 tokens/s |
In the batch-32 scenario, each sequence's KV cache is about 0.5 GB (see Chapter 1 for how to compute this), about 17 GB for 32 sequences, already comparable to the weights. The batch grows 32×, yet the time per step only roughly doubles, so throughput rises about 16×. The compute per step is then about \(2N \times 32 \approx 5\times10^{11}\) FLOPs, which takes only about 0.5 ms on an H100, showing that decode is still memory-bound. Assuming a GPU costs 2 dollars per hour (for illustration only), this scenario corresponds to about 0.17 dollars per million output tokens.
(3) For MoE models, estimate compute and reads separately.
An MoE model activates only some experts per token, so compute is estimated from the activated parameters; but at larger batch sizes different tokens activate different experts, so nearly all experts' weights are read at every step, and the bytes read approach the total parameter count. MoE models therefore read little and run fast at small batch sizes, but need techniques such as expert parallelism to amortize the reads at large batch sizes (see Chapter 5 of the "Model Architecture" direction).
Follow-up questions
Follow-up 1: Roughly how fast can a single request be generated for a 70B model running in bf16 on two H100s?
At most about 50 tokens per second. A 70B model has about 140 GB of bf16 weights, so it needs at least two 80 GB GPUs. With tensor parallelism, each GPU reads only its own half of the weights at every step, effectively pooling the bandwidth of the two GPUs to about 6.7 TB/s, so each step takes at least about 21 ms, i.e. at most about 50 tokens per second; in practice, communication between the GPUs adds overhead. Moreover, the two GPUs together have only about 20 GB left for the KV cache, so the batch cannot be large; in practice, such a model is usually deployed with FP8 weights or on more GPUs.
Follow-up 2: How do you estimate the maximum number of requests one GPU can serve concurrently?
Divide the remaining memory by the KV cache per request. Take Llama 3 8B on an 80 GB GPU: subtract about 16 GB for the weights, reserve some for activations and other overhead, and suppose about 60 GB remain for the KV cache; each request with a 4K context needs about 0.5 GB, so at most about 120 such requests can be served concurrently. The longer the context, the fewer requests can be served at once (see Chapter 1).
Follow-up 3: Why does the actual speed always fall short of the bandwidth bound?
Because bandwidth cannot be fully used, and each step has other overheads. Real kernels achieve only part of the peak bandwidth; each step also carries fixed costs such as kernel launches, sampling and scheduling, which are especially significant at small batch sizes (techniques such as CUDA Graphs exist to reduce them); and multi-GPU deployments add communication time. The bandwidth bound is therefore useful for judging orders of magnitude and bottlenecks, not as the expected actual speed.
Common mistakes
- Do not estimate decode speed at small batch sizes from peak compute: Estimated from compute, an 8B model could generate about 60,000 tokens per second, whereas the bandwidth bound is only about 200.
- Do not use the peak compute with sparsity: The 1,979 TFLOPS on the H100 datasheet is the sparse value; dense bf16 is about 989 TFLOPS.
- Do not ignore reading the KV cache at long contexts: When the batch's KV cache is comparable to the weights, the time per step multiplies.
- Do not mix up the two parameter counts of an MoE model: Compute is estimated from the activated parameters, while the bytes read at large batch sizes approach the total parameter count.