Pidoku

Tuning and Benchmarking

Module 19 Lesson 19.d 50 min Difficulty 4/5

Prerequisites 22.g, 17.b, 17.h, 19.c


Before you start: words you need#

WordPlain meaning
SLOService-level objective: a target such as “p95 time to first token under 500 ms” (23.a).
Open-loop loadRequests arrive on a schedule (say 20 per second) whatever the server is doing, like real users.
Closed-loop loadA fixed number of clients; each sends its next request only when the last one finishes.
KneeThe load at which latency stops being flat and starts climbing steeply.
Token budget--max-num-batched-tokens: how many tokens one engine step may process (17.b).
Coordinated omissionA benchmarking error where the load generator slows down with the server and so never records the waiting real users would have done.
GoodputRequests per second that meet the SLO, rather than all requests per second.

1. What is it?#

vLLM has hundreds of flags and perhaps a dozen that matter for performance. Tuning is not trying them at random. It is:

  1. deciding what you are optimising for;
  2. measuring with a load that looks like yours;
  3. finding the mechanism that limits you, from the metrics (19.c); and
  4. changing the one setting that controls that mechanism, then measuring again.

The earlier lessons gave you the mechanisms. This one gives the measurement method, vLLM’s built-in vllm bench tools, the single most common benchmarking mistake, and a table from symptom to flag. The general method of benchmarking inference is 22.g; this lesson is the vLLM side. Facts checked on 12 November 2026 against vLLM v0.32.0.

flowchart LR
  G[":i-scale: <b>1. Choose the goal</b><br/><small>latency SLO, throughput, or cost</small>"] --> W[":i-file-text: <b>2. Describe the workload</b><br/><small>length distributions,<br/>arrival rate, shared prefixes</small>"]
  W --> B[":i-gauge: <b>3. Measure</b><br/><small>open-loop load at several rates</small>"]
  B --> K[":i-search: <b>4. Find the bottleneck</b><br/><small>queue, cache, step time, CPU</small>"]
  K --> F[":i-wrench: <b>5. Change one setting</b>"]
  F --> B
  class G,W neutral
  class B compute
  class K queue
  class F warn

2. Why does it matter?#

GPUs are the largest cost of an inference service (23.c). A well-tuned server can carry two or three times the traffic of a default one at the same latency, or the same traffic on fewer GPUs. And a badly designed benchmark is worse than none: it gives you a confident number that is wrong, and you size a fleet on it.


3. Simple analogy#

Testing a restaurant kitchen. A closed-loop test is ten diners who each order again only after their last plate arrives: if the kitchen slows, they slow too, and the queue never grows. An open-loop test is customers walking in off the street at a fixed rate: if the kitchen cannot keep up, the queue at the door grows without limit. Only the second tells you how many customers per hour the kitchen can actually take.


4. Tiny example: one benchmark run#

Shell
vllm bench serve \
  --model <model> --endpoint /v1/chat/completions \
  --dataset-name random --random-input-len 1024 --random-output-len 256 \
  --num-prompts 2000 --request-rate 20

It reports, measured at the client (shortened from the documentation’s example):

Request throughput (req/s):              1.73
Output token throughput (tok/s):         382.89
Mean TTFT (ms):                          71.54     P99 TTFT (ms):   79.49
Mean TPOT (ms):                          7.91      P99 TPOT (ms):   8.03
Mean ITL (ms):                           7.74      P99 ITL (ms):    8.39

One run is one point. Tuning needs a curve: the same run at several request rates.


5. Technical explanation#

Three goals that pull apart#

GoalYou care aboutTypical workloadDirection of the main knobs
InteractivityTime to first token, smooth streamingChat, coding assistantsSmaller token budget, fine-grained CUDA graphs, headroom in the cache
ThroughputTokens per second per GPUBatch jobs, evaluation, offline agentsLarger token budget and max_num_seqs, full cache
Cost under an SLORequests per GPU that still meet the targetMost production servicesTune for throughput until the SLO breaks, then back off

vLLM exposes the first two as a starting point:

Shell
vllm serve <model> --performance-mode interactivity   # or: throughput; default: balanced

What the code does in v0.32.0:

  • throughput doubles the default max_num_batched_tokens and max_num_seqs (values you set yourself are left alone). Larger max_num_seqs also raises the largest CUDA graph captured.
  • interactivity captures a CUDA graph for every batch size from 1 to 32, instead of 1, 2, 4, 8, 16, 24, …, so small batches are not padded up (18.d).

The docstring also speaks of latency- or throughput-oriented kernels; we found no other code path that reads the mode in v0.32.0, so treat it as these two effects. Start from the mode that matches your goal and adjust.

The flags that matter#

FlagMechanismRaise it to…Cost of raising it
--max-num-batched-tokensTokens per stepSpeed up prefill, raise throughputLonger steps: worse inter-token latency; more activation memory
--max-num-seqsRunning requests per engineAdmit more concurrencyBigger batches, more preemption risk, more graph memory
--long-prefill-token-thresholdPer-request share of a step(lower it) to protect short promptsLong prompts take more steps
--gpu-memory-utilizationSize of the block poolAdd cache capacityLess safety margin
--max-model-lenLongest requestAccept longer requestsFewer worst-case concurrent requests; may not start
--kv-cache-dtype fp8Bytes per cached token(set it) to double cache capacitySmall quality risk (13.h)
--watermarkAdmission headroomReduce preemptionSlightly lower concurrency
--max-num-queued-reqs, --max-num-queued-tokensAdmission control(set them) to bound latency under overloadExcess requests get HTTP 503
--stream-intervalTokens per streamed eventCut per-token CPU overheadChunkier streaming
--api-server-countFrontend processesRemove a tokenising or media bottleneckCPU cores
-O0 … -O3, --performance-modeCompilation and graph ladder (default -O2)—Startup time and memory
-tp, -dp, --enable-expert-parallelGPU layout—See 19.a

The built-in tools#

CommandUse
vllm bench serveLoad a running server. Datasets include random, ShareGPT, BurstGPT, prefix repetition, random multimodal, many Hugging Face sets and your own JSONL.
vllm bench throughputOffline: the LLM class with no server. An upper bound, not a prediction of serving performance.
vllm bench latencyOffline: one batch at a time, for step latency.
vllm bench startupCold and warm start-up time.
vllm bench sweep serveStarts the server and runs bench serve over a grid of server and client parameters, resetting caches between runs.
vllm bench sweep serve_workloadFinds the latency–throughput trade-off by sweeping request rate or concurrency between “one at a time” and “everything at once”.
vllm bench sweep plot, plot_paretoCharts from sweep results.

The documentation recommends GuideLLM (a separate vLLM-organisation project, v0.8.1 in October 2026) for benchmarking production servers, and describes vllm bench as mainly for feature evaluation and regression testing. v0.32.0 removed the old sonnet dataset and vllm bench throughput --dataset.

Load-shaping options decide whether results mean anything:

  • --request-rate R: open loop. Requests arrive at R per second regardless of how the server is doing; inf sends everything at once.
  • --max-concurrency C: closed loop. At most C requests in flight.
  • --burstiness B: with a rate, 1.0 gives Poisson arrivals; lower values are burstier.
  • --ramp-up-strategy: raise the rate gradually during one run.
  • --goodput ttft:500 tpot:50: also report the request rate that met those per-request limits (in milliseconds).

The mistake: closed-loop benchmarks hide overload#

With only --max-concurrency 64, sixty-four clients each send a request, wait for the answer, and send the next. If the server slows, the clients slow with it: the arrival rate adapts to the server. The queue can never exceed 64, so latency looks stable at any “load”, because you are not controlling load at all.

Real users do not wait for each other. If their arrival rate exceeds what the server can do, the queue grows without bound and TTFT climbs every second. A closed-loop test cannot show that.

The fix: drive load with --request-rate at several values and plot latency against rate. The curve is flat, then bends sharply. The rate just before the bend is your capacity for that SLO. --max-concurrency may be added as a safety cap.

The sources disagree on emphasis. The vLLM sweep documentation notes that --workload-var max_concurrency gives more reliable (repeatable) results because it directly controls the load on the engine. Both are true: concurrency is good for comparing two engine settings like-for-like; rate is what tells you where a real service falls over.

Other ways to fool yourself#

  • Warm caches. The documentation warns that repeating vllm bench serve against the same server “can reuse prompts left in the prefix cache and inflate throughput”. The random dataset is reproducible for a fixed --seed (default 0). Vary the seed, restart, or use the sweep tool.
  • The wrong length distribution. Fixed 1,024-in, 256-out traffic has no long prompts to disturb decoders and no variance to cause preemption. Sample lengths from your logs; the request-shape histograms in 19.c give them.
  • No shared prefixes, or too many. A random dataset has a 0% hit rate; a dataset that repeats one prompt has 100%. Neither is your workload.
  • Offline numbers for an online service. The LLM class gets a larger default token budget and has no HTTP, tokenising-under-load or streaming cost.
  • A saturated client. A Python load generator on one core can saturate before a fast server. Watch the client’s CPU.
  • Averages and short runs. Report p50, p95, p99. Run long enough to reach steady state, and check num_requests_waiting is not still rising when you stop.

From symptom to setting#

Symptom (with the metric)MechanismChange
High TTFT, high request_queue_time, running = max_num_seqsSequence limitRaise --max-num-seqs
High TTFT, high queue time, kv_cache_usage_perc ≈ 1MemoryFP8 cache, quantised weights, lower --max-model-len, more GPUs
num_preemptions risingOver-admissionLower --max-num-seqs, set --watermark 0.05
High TTFT, low queue time, long promptsPrefill speedRaise --max-num-batched-tokens; reorder prompts for cache hits
High TTFT, low queue and prefill timeFrontend CPUMore --api-server-count, more cores; check media loading
p99 inter-token latency ≫ p50Prefill chunks in decode stepsLower --max-num-batched-tokens; --long-prefill-token-threshold; disaggregate (19.b)
Short prompts wait behind long onesBudget monopolised--long-prefill-token-threshold 2048
All inter-token latency high, GPU not fullCPU-bound engine coreDedicated physical core; --stream-interval; fewer structured-output requests per engine
Slow at 1–4 users, fine at 64Padding and launch overhead--performance-mode interactivity
Latency grows without bound under loadNo admission control--max-num-queued-reqs or --max-num-queued-tokens
Throughput flat while adding concurrencyCompute-saturatedAdd replicas; quantise; this GPU is full
Startup takes minutesCompile and capturePersist ~/.cache/vllm; -O1; vllm preload (19.e)

A tuning session, in order#

  1. Fit. Make the model start with the max_model_len your traffic needs. Read the GPU KV cache size line; check that capacity ÷ p95 request tokens comfortably exceeds max_num_seqs (17.h).
  2. Baseline. Default flags, your length distribution, open-loop load at a low rate. Record p50/p95/p99 TTFT and inter-token latency.
  3. Find the knee. Raise the rate in steps until p95 TTFT or p99 ITL breaks the SLO. Note what the metrics say is binding there.
  4. Move the binding constraint. One flag, from the table. Re-run step 3.
  5. Stop when the constraint is the GPU’s compute, or when remaining changes only trade one SLO for another.
  6. Protect it. Set admission limits a little above the knee, so overload produces fast 503s instead of slow timeouts, and autoscale on queue signals rather than GPU utilisation (19.e).

6. Under the hood: why a closed loop cannot find the knee#

The same simulated server measured two ways: a fixed number of clients, and a fixed arrival rate. It can run 64 requests at once, but only 32 at full speed, and each needs 2 seconds of work: a capacity of 16 requests per second.

Go
// loadshape.go — the same server measured closed-loop and open-loop.
package main

import "fmt"

// The server: it can work on up to maxRunning requests at once, each needing
// serviceSeconds of attention when running alone; with n running, each
// progresses at min(1, capacity/n) of full speed.
const (
	maxRunning     = 64
	capacity       = 32.0 // requests that can run at full speed simultaneously
	serviceSeconds = 2.0
	dt             = 0.01
	duration       = 300.0
)

type req struct {
	arrived, started float64
	left             float64
}

func simulate(arrivalRate float64, closedClients int) (throughput, meanLatency, worstQueueWait float64) {
	var waiting, running []*req
	done, totalLatency, carry := 0, 0.0, 0.0

	if closedClients > 0 {
		for i := 0; i < closedClients; i++ {
			waiting = append(waiting, &req{left: serviceSeconds})
		}
	}
	for t := 0.0; t < duration; t += dt {
		if closedClients == 0 { // open loop: arrivals do not care how the server is doing
			carry += arrivalRate * dt
			for ; carry >= 1; carry-- {
				waiting = append(waiting, &req{arrived: t, left: serviceSeconds})
			}
		}
		for len(waiting) > 0 && len(running) < maxRunning {
			r := waiting[0]
			waiting = waiting[1:]
			r.started = t
			worstQueueWait = max(worstQueueWait, t-r.arrived)
			running = append(running, r)
		}
		speed := min(1.0, capacity/float64(max(len(running), 1)))
		keep := running[:0]
		for _, r := range running {
			if r.left -= speed * dt; r.left > 0 {
				keep = append(keep, r)
				continue
			}
			done++
			totalLatency += t - r.arrived
			if closedClients > 0 { // closed loop: the client sends its next request only now
				waiting = append(waiting, &req{arrived: t, left: serviceSeconds})
			}
		}
		running = keep
	}
	return float64(done) / duration, totalLatency / float64(max(done, 1)), worstQueueWait
}

func main() {
	fmt.Printf("server capacity: %.0f requests/s at full speed\n\n", capacity/serviceSeconds)

	fmt.Println("closed loop (--max-concurrency only)")
	fmt.Printf("  %8s %12s %14s %18s\n", "clients", "req/s", "mean latency", "worst queue wait")
	for _, c := range []int{8, 32, 64, 128, 256} {
		tp, lat, q := simulate(0, c)
		fmt.Printf("  %8d %12.1f %12.2f s %16.2f s\n", c, tp, lat, q)
	}

	fmt.Println("\nopen loop (--request-rate)")
	fmt.Printf("  %8s %12s %14s %18s\n", "rate", "req/s", "mean latency", "worst queue wait")
	for _, r := range []float64{4, 8, 12, 15, 17, 20, 24} {
		tp, lat, q := simulate(r, 0)
		fmt.Printf("  %8.0f %12.1f %12.2f s %16.2f s\n", r, tp, lat, q)
	}
}

Output:

server capacity: 16 requests/s at full speed

closed loop (--max-concurrency only)
   clients        req/s   mean latency   worst queue wait
         8          4.0         2.00 s             0.01 s
        32         16.0         2.00 s             0.01 s
        64         15.8         4.01 s             0.01 s
       128         15.8         7.97 s             4.02 s
       256         15.8        15.71 s            12.04 s

open loop (--request-rate)
      rate        req/s   mean latency   worst queue wait
         4          4.0         1.99 s             0.00 s
         8          7.9         1.99 s             0.00 s
        12         11.9         1.99 s             0.00 s
        15         14.9         1.99 s             0.00 s
        17         15.8        11.98 s            17.36 s
        20         15.8        32.79 s            59.68 s
        24         15.8        52.50 s            99.41 s

How to read it:

  • Closed loop: every row is a steady, finite number, and throughput sits at capacity. 256 clients look like a slower but stable server. Queue wait appears only once clients exceed the 64 running slots, and it is bounded by the client count.
  • Open loop: flat at 1.99 s up to 15 requests per second. At 17 the queue starts growing, and the worst queue wait grows with the length of the test: run twice as long and it doubles. That is overload, and only this table shows where it begins.

7. Performance implications#

  • Token budget is the main latency–throughput dial. Bigger steps raise throughput and lengthen every decoder’s wait.
  • max_num_seqs past the knee only adds latency. When the GPU is compute-saturated, more running requests share the same work (exercise 1).
  • FP8 KV cache and quantised weights buy cache capacity, which turns memory-bound queueing back into compute-bound throughput.
  • CPU matters. The engine core and API servers are Python. A throttled or shared core shows as an idle GPU and uneven ITL.

8. Production implications#

  • Benchmark the deployment you run: same image, flags, GPU, parallel layout, and a gateway in front if production has one.
  • Re-benchmark after upgrades. Defaults move between releases (19.h).
  • Store results with their configuration (vllm bench serve --save-result writes JSON) so a regression can be traced to a change.
  • Admission limits are part of the SLO. A 503 that a client retries elsewhere is better than a 60-second wait.

9. Common mistakes#

  1. Closed-loop only. It hides overload.
  2. Repeating runs against a warm prefix cache and reporting the inflated number.
  3. Fixed lengths instead of your real distribution.
  4. Using vllm bench throughput to size an online service.
  5. Changing several flags at once, so you cannot tell which helped.
  6. Reporting means. Users feel p99.

10. Hands-on exercise#

  1. Run loadshape.go. Raise maxRunning to 128 with the same capacity. What happens to closed-loop latency at 128 clients, and to open-loop latency just below the knee?
  2. Add admission control to the open-loop case: reject an arrival when more than 40 are waiting. Report the rejection rate and the worst queue wait at a rate of 20.
  3. Run vllm bench serve against a real server at five request rates with --goodput ttft:500. Plot p95 TTFT against rate, mark your SLO and read off the capacity.
  4. Run the same sweep with vllm bench sweep serve_workload --workload-var max_concurrency. Do the two methods agree on capacity?

11. Interview questions#

  1. Why does a benchmark using only --max-concurrency fail to reveal an overloaded server?
  2. p99 inter-token latency is six times the median while GPU utilisation is modest. Which mechanism is the likely cause, and which two flags address it?
  3. What exactly does --performance-mode throughput change in vLLM v0.32.0?
  4. Why can vllm bench throughput overstate what a server will deliver?
  5. Why is GPU utilisation a poor autoscaling signal for an inference server?

12. Further reading#

Checked on 12 November 2026 against vLLM v0.32.0.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in