Slides · Production: cost, serving and observability

LLM inference and serving

LLM inference and serving

Why decode is slow, why memory caps how many users fit on a GPU, and what each speed-up costs you.

Concept

The servers are idle, yet the queue grows

  • On sale day the dashboard shows servers that are not working hard, and the queue keeps growing.
  • If compute is not the limit, something else is: memory bandwidth and memory capacity.
  • Even if you never self-host, these ideas explain provider behaviour: why long prompts delay the first token, why long answers take so long, why prompt caching exists.

By the end you can:

  1. Explain why decode is bandwidth-bound and why KV-cache memory caps concurrency.
  2. Read serving metrics and map a symptom to a cause.
  3. Match each speed-up technique to the bottleneck it attacks and the cost it adds.
  4. Decide between a hosted API and self-hosting with a break-even estimate.

Concept

Mental model: a narrow straw and a bus

  • A GPU is a very fast calculator with a narrow straw to its memory. One token for one user drains the straw, because all the weights must pass the calculator for every token.
  • Batching is a bus: one trip through the weights serves many riders, so the cost of the trip is shared.
  • Each rider carries a bag (their KV-cache) that takes a seat’s worth of memory. The bus fills up from bags before it fills up from riders.
  • A good scheduler lets riders get on and off at every stop instead of waiting for the whole route.

Compare

Two phases, two bottlenecks

AspectPrefillDecode
What happensThe whole prompt is processed in parallelOne new token per step, reusing stored keys and values
Limited mainly byComputeMemory bandwidth: moving weights, keys and values to the chip
Shows up asTime to first tokenTime between tokens
Grows withPrompt length and loadOutput length
  • NVIDIA’s inference-optimization post calls decode a memory-bound operation: the speed of moving weights, keys, values and activations from memory dominates its latency.
  • Two scarce resources follow: bandwidth limits decode speed, capacity limits how many requests are in flight.

Source1 Mastering LLM Techniques: Inference Optimization

Diagram

One server, end to end

Diagram: Reading downward, requests enter a scheduler that batches them continuously, run prefill, and store keys and values in a paged cache that...

Incoming requests

Scheduler: continuous batching

Prefill: compute-bound

Paged KV-cache with shared prefixes

Decode loop: bandwidth-bound

Stream tokens

Diagram summary: Reading downward, requests enter a scheduler that batches them continuously, run prefill, and store keys and values in a paged cache that can share prefixes. They then loop through decode, streaming tokens as they go. The techniques later in this lesson each attach to one of these stages.

Math

Why decode has a speed ceiling

max tokens per second (one stream)=memory bandwidthbytes read per step\text{max tokens per second (one stream)} = \frac{\text{memory bandwidth}}{\text{bytes read per step}}bytes read per step≈number of parameters×bytes per parameter\text{bytes read per step} \approx \text{number of parameters} \times \text{bytes per parameter}
SymbolMeaning
memory bandwidthBytes the GPU can move per second (assumed 3,000 GB/s, illustrative)
parameters13 billion in this example
bytes per parameter2 for 16-bit, 1 for 8-bit, 0.5 for 4-bit
Weight precisionWeights read per stepUpper bound for one stream
16-bit13×109×2=26 GB13 \times 10^{9} \times 2 = 26\ \text{GB}3,00026≈115\dfrac{3{,}000}{26} \approx 115 tokens/s
8-bit13 GBabout 231 tokens/s
4-bit6.5 GBabout 462 tokens/s
  • The bound ignores KV-cache reads and other overheads, so real speeds are lower.
  • More arithmetic power with the same bandwidth leaves the bound unchanged.

Source1 Mastering LLM Techniques: Inference Optimization

Worked example

Batching shares the weight read

Same 26 GB model, same 3,000 GB/s (illustrative). Each decode step reads the weights once, however many requests are in the batch.

Requests per stepWeight reads per stepTokens produced per stepCeiling on aggregate tokens/s (weights only)
126 GB1about 115
826 GB8about 923
  • The ceiling for 8 requests is 8×3,00026\dfrac{8 \times 3{,}000}{26}.
  • The real gain is smaller: each request also reads its own KV-cache, compute eventually becomes the limit, and every request holds memory. That is the next slide.

Math

KV-cache memory per token

KV bytes per token=2×L×Hkv×dhead×b\text{KV bytes per token} = 2 \times L \times H_{kv} \times d_{\text{head}} \times bKV bytes per request=KV bytes per token×nseq\text{KV bytes per request} = \text{KV bytes per token} \times n_{\text{seq}}
SymbolMeaning
2One key and one value per head
LLNumber of transformer layers
HkvH_{kv}Key and value heads. Fewer than query heads with grouped-query attention (GQA)
dheadd_{\text{head}}Size of each head
bb2 for 16-bit
  • NVIDIA’s post writes the same per-token size with nheads×dheadn_{\text{heads}} \times d_{\text{head}} and notes that the total grows linearly with batch size and sequence length.
  • MQA and GQA reduce the number of key-value heads. NVIDIA notes MQA can cost accuracy and that GQA balances multi-head and multi-query attention.

Source1 Mastering LLM Techniques: Inference Optimization

Worked example

Worked example: how many requests fit?

Illustrative plan: an 80 GiB GPU, 90 percent usable (72 GiB), 7B model in 16-bit (about 13 GiB of weights), 32 layers, head_dim 128, 4,096-token requests.

LayoutPer tokenPer 4,096-token requestKV pool (72−13=5972 - 13 = 59 GiB)
32 KV-heads2×32×32×128×2=524,2882 \times 32 \times 32 \times 128 \times 2 = 524{,}288 B (0.5 MiB)2 GiB592=29.5\dfrac{59}{2} = 29.5, so 29 requests
8 KV-heads (GQA)2×32×8×128×2=131,0722 \times 32 \times 8 \times 128 \times 2 = 131{,}072 B (0.125 MiB)0.5 GiB590.5=118\dfrac{59}{0.5} = 118 requests
  • Same GPU, same weights, four times the concurrency, from one architecture choice.
  • When the pool is full, new requests queue. The vLLM guide says it may also preempt and recompute running requests, which can hurt end-to-end latency.
  • So “how many users fit on one GPU” is mostly a KV-cache question.

Source2 Optimization and Tuning

Check yourself

Check: how long a context can you afford?

A 40 GiB GPU is 90 percent usable and holds 10 GiB of weights. The model has 24 layers, 8 KV-heads, head_dim 128 and 16-bit values. Product wants 100 requests in flight at once. What is the longest context per request the KV pool allows? And how many 16,384-token requests fit?

Answer

Per token: 2×24×8×128×2=98,3042 \times 24 \times 8 \times 128 \times 2 = 98{,}304 bytes. The pool is 40×0.9−10=2640 \times 0.9 - 10 = 26 GiB. For 100 requests each gets 0.26 GiB, which is 0.26×23098,304≈2,839\dfrac{0.26 \times 2^{30}}{98{,}304} \approx 2{,}839 tokens. A 16,384-token request holds 1.5 GiB, so 261.5=17.3\dfrac{26}{1.5} = 17.3, which is 17 requests. Concurrency and context length trade directly against each other.

Compare

Four metrics, four questions

MetricQuestion it answersWhat moves it
TTFTHow long until the first token?Queueing plus prefill; prompt length and load
Inter-token latency (ITL, time per output token)How smooth is the stream?Decode speed, memory bandwidth, batch pressure
ThroughputHow many tokens per second across all users?Batching, utilization. A cost metric
GoodputHow much work meets the promised targets?Throughput minus the requests that miss TTFT or ITL limits
  • A common definition of goodput is the rate of requests that meet your latency targets.
  • DistServe’s stricter version: the highest request rate a GPU can sustain while a target share of requests meets both the first-token limit and the per-output-token limit. Its abstract reports staying within the limits for more than 90 percent of requests.

Source3 DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving

Worked example

Worked example: more traffic is not more goodput

Using the simple definition, goodput=request rate×share that meets both targets\text{goodput} = \text{request rate} \times \text{share that meets both targets}. One illustrative server under rising load:

Load (requests/s)Share meeting both targetsGoodput
598%5×0.98=4.905 \times 0.98 = 4.90
1092%10×0.92=9.2010 \times 0.92 = 9.20
1570%15×0.70=10.5015 \times 0.70 = 10.50
2045%20×0.45=9.0020 \times 0.45 = 9.00
  • Throughput keeps rising with load, but goodput peaks at 15 requests per second and then falls.
  • Past the peak you serve more requests and more of them miss the promise.
  • Goodput is how you tune: raise load until the share meeting the targets starts to fall, and stop near the peak.

Source3 DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving

Diagram

From symptom to cause

Diagram: Check time to first token first and fix queueing or long prompts.

yes

no

yes

no

Serving too slow or costly?

TTFT high?

Queueing or long prompts

ITL high?

Bandwidth or batch pressure

Throughput or cost: batch better

Diagram summary: Check time to first token first and fix queueing or long prompts. If that is fine, check inter-token latency and fix memory bandwidth or batch pressure. If both are fine but cost is high, improve batching and memory use.
  • Typical fixes. High TTFT: prefix cache, chunked prefill, more replicas. High ITL: quantize, speculative decoding, smaller model. High cost: continuous batching, paged KV, route easy traffic to a small model.
  • The vLLM guide describes a chunked-prefill budget as a trade: smaller values give better ITL, larger values give better TTFT.

Source2 Optimization and Tuning

Check yourself

Check: fast but costly

A self-hosted deployment meets its TTFT and ITL targets at every hour. Yet cost per million tokens is far above plan, and GPU utilization sits near 25 percent because requests arrive one or two at a time. Which branch of the triage tree are you on, and what do you try?

Answer

Both latency checks pass, so you are on the throughput-and-cost branch. The GPU is mostly idle, so the batch is small and the fixed hourly price is spread over few tokens. Options: send several models or tenants to shared replicas so batches fill, scale down to fewer GPUs, or move the low-volume traffic to a hosted API. More decode speed-ups would not help, because latency is not the problem.

Worked example

Continuous batching: toy timeline

Three slots. Requests A, B, C need 2, 5, 3 decode steps. D needs 2 steps and is waiting. A dot is an idle slot.

StepStatic: slot 1slot 2slot 3Continuous: slot 1slot 2slot 3
1ABCABC
2ABCABC
3·BCDBC
4·B·DB·
5·B··B·
6D··
7D··
  • Static batching holds the group until the longest request (B) finishes, so D completes at step 7.
  • Continuous (in-flight) batching rebuilds the batch at every step, so D takes A’s freed slot and completes at step 4.
  • The Anyscale post reports, against naive batching on OPT-13B and one A100 40GB in 2023, up to 23x for vLLM (continuous batching plus its own memory optimizations) and 8x for continuous batching in Ray Serve and text-generation-inference. One benchmark in one setting.
  • Catch: under heavy load a request can wait longer for a slot.

Sources4 How continuous batching enables 23x throughput in LLM inference while reducing p50 latency1 Mastering LLM Techniques: Inference Optimization

Diagram

PagedAttention and prefix caching

Diagram: Each column reads top to bottom.

PagedAttention

Small blocks on demand

600 tokens of blocks, prefixes shared

Contiguous reservation

Reserve 4,096 tokens up front

Request uses 600, rest idle

Diagram summary: Each column reads top to bottom. Reserving a request’s maximum length up front wastes the unused part and caps the batch size. Paged allocation hands out small blocks as tokens arrive, so memory is used where it is needed and shared prefixes can reuse blocks. The 600 tokens is an illustrative request.
  • The vLLM paper’s abstract reports near-zero KV-cache waste and 2 to 4 times the throughput of the systems it compared with (FasterTransformer, Orca) at the same latency.
  • vLLM’s automatic prefix caching hashes full blocks, reuses matching leading blocks, and does not change model outputs. It saves prefill work, not decode.

Sources5 Efficient Memory Management for Large Language Model Serving with PagedAttention6 Automatic Prefix Caching

Worked example

Chunked prefill

A 12,000-token prompt can hold the GPU through one long prefill while other users’ decode steps wait.

Time sliceWithout chunking (one long pass)With chunked prefill
1Long prompt prefillPrefill chunk 1 plus others’ decode
2Prefill continues; others waitPrefill chunk 2 plus others’ decode
3Prefill ends; others finally get a tokenPrefill chunk 3 plus others’ decode
  • Others’ streams keep flowing on the right. The cost is a slightly later first token for the long prompt.
  • The vLLM guide says chunked prefill is on by default where possible in its V1 engine and prioritizes decode requests. A smaller per-step token budget favours ITL, a larger one favours TTFT.

Source2 Optimization and Tuning

Concept

Quantization: smaller numbers, smaller reads

  • Store weights (sometimes activations too) in 8-bit or 4-bit formats.
  • A 13B model’s weights go from about 26 GB at 16-bit to about 13 GB or 6.5 GB (plus some overhead for scaling factors). Decode reads fewer bytes, and more memory is free for KV-cache.
  • Cost: NVIDIA’s post names two error sources, rounding and clipping, as the price of fewer bits.
  • Weights are easier to quantize than activations, which tend to contain outliers.
  • Speed-up depends on kernels and hardware. Choose the format by testing on your own evaluation set, not by default.

Source1 Mastering LLM Techniques: Inference Optimization

Diagram

Speculative decoding

Diagram: Reading downward, a cheap draft guesses several tokens ahead and the large model checks them in one pass.

Cheap draft proposes 4 tokens

Large model verifies all 4 in one pass

Keeps the matching prefix: 3 accepted

Large model supplies the 4th token

Diagram summary: Reading downward, a cheap draft guesses several tokens ahead and the large model checks them in one pass. The matching prefix is kept, here three of four, and the large model supplies the correct next token before the loop repeats. The counts are illustrative.
  • Leviathan et al. report 2x to 3x faster decoding on T5-XXL compared with the standard T5X implementation, with identical outputs (ICML 2023).
  • With the standard sampler, vLLM’s page calls the method theoretically lossless up to hardware numeric precision (a variant that relaxes verification is not), and recommends measuring on your own traffic.
  • The speed-up depends on how often the draft is right.

Sources7 Fast Inference from Transformers via Speculative Decoding8 Speculative Decoding

Compare

Speculative decoding and load

The vLLM page rates methods by traffic level (page viewed 2026-10-23). Three rows:

MethodLow QPS (latency focused)High QPS (throughput focused)
Draft modelHigh gainMedium gain
EAGLEHigh gainMedium to high gain
N-gramLow to medium gainMedium gain
  • The page positions it as a latency tool for memory-bound serving at lighter to moderate load.
  • For the model-based methods in the full table (EAGLE, MTP, draft models) the rating at high QPS is lower than at low QPS. The simpler n-gram and suffix methods are rated Medium at high QPS, and the page describes their speedups as modest but without extra work at peak load.
  • Model-based methods also add a second component to run.

Source8 Speculative Decoding

Compare

Three more levers

AspectFlashAttentionParallelismPrefill and decode disaggregation
AttacksMemory traffic inside attentionA model too big for one GPU; throughputInterference between phases
HowTiles stay in fast on-chip memory, fewer reads and writes of main GPU memoryTensor parallelism shards each layer; data parallel replicas add throughputRun prefill and decode on separate pools
OutputExact, not an approximationUnchangedUnchanged
CostBenefit depends on the implementation you runTensor parallelism needs fast links between GPUsMore machines, KV transfer, scheduling
  • DistServe reports serving up to 7.4x more requests, or meeting up to 12.6x tighter latency targets, than the systems it compared against, in its own tests. Do not quote it as a general speed-up.

Sources9 FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness3 DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving2 Optimization and Tuning

Compare

Technique to bottleneck to cost

TechniqueAttacksCost or catch
Continuous batchingIdle slots, low throughputPer-request latency can rise at high load
PagedAttentionKV fragmentation, small batchesEngine complexity
Prefix cachingRepeated prefill of shared promptsOnly identical prefixes; cache memory
Chunked prefillLong prompts stalling others’ decodeSlightly slower first token for the long prompt
QuantizationMemory size and bandwidthSome quality loss; kernel and hardware support vary
Speculative decodingDecode latency at low to medium loadExtra component; for model-based methods the vLLM rating drops at high load
FlashAttentionAttention memory trafficNone on output
DisaggregationPhase interferenceMore machines, KV transfer

Sources1 Mastering LLM Techniques: Inference Optimization2 Optimization and Tuning6 Automatic Prefix Caching8 Speculative Decoding

Check yourself

Check: pick two techniques

A self-hosted assistant serves a few users at a time. Single-stream speed is the complaint: time between tokens is high even on short prompts. Name two techniques that attack this, and say which of them risks changing answers.

Answer

Quantization shrinks the bytes read per decode step and raises the bandwidth ceiling, but rounding and clipping can change answers, so test it on your own tasks. Speculative decoding targets decode latency at low to medium load and, with the standard sampler, keeps the large model’s output distribution. Continuous batching or a bigger batch would not help here, because with few users there is little to share.

Worked example

Self-host or API: it is about utilization

Illustrative: a GPU costs 2 dollars per hour and your engine sustains 1,000 output tokens per second across users.

tokens per hour at full load=1,000×3,600=3,600,000\text{tokens per hour at full load} = 1{,}000 \times 3{,}600 = 3{,}600{,}000cost per million tokens=hourly pricemillion tokens per hour×utilization\text{cost per million tokens} = \frac{\text{hourly price}}{\text{million tokens per hour} \times \text{utilization}}
GPU useTokens per hourCost per million tokens
100%3,600,00023.6≈$0.56\dfrac{2}{3.6} \approx \$0.56
30%1,080,00021.08≈$1.85\dfrac{2}{1.08} \approx \$1.85
  • Break-even against an API priced at $1.00 per million (invented): 0.5556u=1.00\dfrac{0.5556}{u} = 1.00, so utilization uu must reach about 56 percent.
  • An idle GPU still costs money. An API bill follows usage.
  • This leaves out failover capacity, engineers’ time and the quality gap between an open model and a frontier one.

Check yourself

Check: how fast must the GPU be?

A GPU costs 4.00 dollars per hour. A hosted API offers a comparable model at 2.50 dollars per million tokens. You expect 50 percent utilization. What full-load throughput, in output tokens per second, must the engine sustain for self-hosting to cost no more than the API?

Answer

To tie, the GPU must deliver 4.002.50=1.6\dfrac{4.00}{2.50} = 1.6 million tokens in an hour at the price of that hour. At 50 percent utilization the actual tokens equal half of full-load tokens, so full load must be 3.2 million tokens an hour, which is 3,200,0003,600≈889\dfrac{3{,}200{,}000}{3{,}600} \approx 889 tokens per second. Below that throughput, or at lower utilization, the API is cheaper on this arithmetic alone (failover capacity and engineering time not included).

Compare

Decision factors

FactorFavours self-hostingFavours a hosted API
VolumeSteady and highSpiky or low
UtilizationCan keep GPUs busyOften idle
Data residencyStrict rulesNo rule that blocks a provider
ControlNeed to fine-tune or control the modelPrompting is enough
TeamCan run a serving stackSmall team
CapabilityAn open model is good enoughNeed the strongest available model
  • A common hybrid: self-host the bulk, keep an API fallback for overflow and hard cases.
  • Before committing, estimate break-even with your own prices and measured throughput.

Concept

Common mistakes

  • “A bigger batch always lowers latency.” It raises throughput; per-request latency can get worse.
  • “Quantization is free.” It trades quality for memory and speed.
  • Confusing a response cache with the KV-cache. One skips the model; the other stores keys and values inside it.
  • Claiming speculative decoding changes outputs. Done correctly, it does not.
  • Comparing a self-hosted price at full load with an API price. Use the utilization you will really see.

Summary

Recap

  • Prefill sets TTFT. Decode sets inter-token latency and is memory-bandwidth-bound.
  • KV-cache memory caps concurrency. GQA shrinks it. A full pool means queueing or preemption.
  • Continuous batching and PagedAttention raise throughput; prefix caching cuts repeated prefill work (and so TTFT), while chunked prefill smooths other users’ streams at a small first-token cost for the long prompt.
  • Quantization trades quality for speed and memory. Speculative decoding, with the standard sampler, keeps the output distribution. Measure both on your own traffic.
  • Self-hosting wins on utilization and loses on idle time and operations.

References

References & Sources (1 of 2)

  1. Mastering LLM Techniques: Inference Optimization (opens in a new tab)

    Shashank Verma, Neal Vaidya2023Article

    Used for Decode is memory-bound; KV-cache size formula and linear growth; MQA and GQA reduce key-value heads; in-flight batching; quantization costs (rounding and clipping) and why weights are easier than activations.

  2. Optimization and Tuning (opens in a new tab)

    vLLM project2026Documentation

    Used for KV-cache shortage can trigger preemption and recomputation that hurts latency; chunked prefill budget trades ITL against TTFT; tensor, pipeline and data parallelism.

  3. DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving (opens in a new tab)

    Yinmin Zhong, Shengyu Liu, Junda Chen, Jianbo Hu, et al.2024OSDI 2024Paper

    Used for Goodput as the rate served within both TTFT and time-per-output-token limits; disaggregating prefill and decode, with its reported 7.4x and 12.6x results.

  4. How continuous batching enables 23x throughput in LLM inference while reducing p50 latency (opens in a new tab)

    Cade Daniel, Chen Shen, Eric Liang, Richard Liaw2023Article

    Used for Reported results versus naive batching in one 2023 setting (OPT-13B, one A100 40GB): up to 23x for vLLM, which pairs continuous batching with its own memory optimizations, and 8x for continuous batching in Ray Serve and text-generation-inference; iteration-level scheduling.

  5. Efficient Memory Management for Large Language Model Serving with PagedAttention (opens in a new tab)

    Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, et al.2023Preprint

    Used for PagedAttention and vLLM: near-zero KV-cache waste and 2 to 4 times throughput versus FasterTransformer and Orca at the same latency.

References

References & Sources (2 of 2)

  1. Automatic Prefix Caching (opens in a new tab)

    vLLM project2026Documentation

    Used for Automatic prefix caching hashes full KV blocks, reuses matching prefixes, and does not change model outputs.

  2. Fast Inference from Transformers via Speculative Decoding (opens in a new tab)

    Yaniv Leviathan, Matan Kalman, Yossi Matias2023ICML 2023 (PMLR 202)Paper

    Used for Speculative decoding gives 2x to 3x acceleration on T5-XXL with identical outputs.

  3. Speculative Decoding (opens in a new tab)

    vLLM project2026Documentation

    Used for Speculative decoding targets medium-to-low QPS, memory-bound workloads; method-by-load rating table; lossless up to hardware numerics; advice to measure on your own traffic.

  4. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (opens in a new tab)

    Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, et al.2022NeurIPS 2022Paper

    Used for FlashAttention is an exact attention algorithm that uses tiling to cut reads and writes between GPU main memory and on-chip memory.