Unit 9 of 9
Serve, measure, and optimize the bottleneck
What you’ll learn
- Measure TTFT, inter-token latency, TPOT, end-to-end latency, and throughput from the client, with warm-up and percentiles.
- Choose between closed-loop and open-loop load, and explain why a closed loop can hide queueing.
- Read a request trace to decide whether queueing, prefill, decode, or the network is the bottleneck.
- Calculate the expected tokens per target pass and the speedup of speculative decoding from its acceptance rate and draft cost.
- Plan, measure, and defend one optimization for a Llama 3.1 8B service, using every lesson in this course.
What a streaming endpoint does
Your support assistant is live. The dashboard shows 3,000 output tokens per second, and users report that it “hangs before answering”. Both are true, and until you can measure the right numbers from the user’s side, you cannot tell which part of the system to fix. By the end of this lesson you will measure a streaming endpoint correctly, read a trace to find the slow stage, and judge whether an optimization such as speculative decoding will pay off.
You followed one request through the model in the first lesson. Here is the same request from the endpoint’s point of view. Every stage takes time, and some of it passes while the GPU does nothing for this request:
- Parse and validate the JSON body. Reject bad fields now, before any work starts, because once a stream begins you cannot change its HTTP status.
- Apply the chat template and tokenize.
- Queue until the scheduler admits the request into the running batch and gives it KV cache memory.
- Prefill the prompt and sample the first token.
- Decode one token per step, detokenize, and send each piece as a server-sent event.
- Finish on an end token, a stop string, the length limit, an error, or a client disconnect, and release the request’s cache on every one of those paths.
Streaming uses server-sent events (SSE): each event is a line starting with data: , followed by a blank line, and the stream ends with data: [DONE]. To practice measuring without a GPU, you need a server whose timing behaves like a real engine’s. The one below does no math at all. One background thread plays the GPU: it admits up to --max-batch requests, spends 0.1 ms per prompt token on prefill (during which every other request waits), then runs decode steps that each take 5 ms plus 1 ms per running request and give every running request one token. A word stands in for a token. Save it as mock_server.py; it needs only the standard library:
"""A mock LLM server that streams fake tokens over SSE with realistic timing.
One engine thread plays the GPU. It admits up to --max-batch requests, runs
each new request's prefill (which pauses everyone else's decode), then runs
decode steps that emit one token for every running request. A word stands in
for a token. Standard library only.
"""
import argparse
import json
import queue
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
WORDS = "your order ships from our warehouse within two business days".split()
def ms_since(moment):
return round((time.perf_counter() - moment) * 1000, 2)
class Request:
def __init__(self, prompt_tokens, max_tokens):
self.prompt_tokens, self.max_tokens = prompt_tokens, max_tokens
self.generated, self.done, self.cancelled = 0, False, False
self.tokens = queue.Queue() # engine to HTTP handler; None ends it
self.arrived = time.perf_counter()
self.trace = {}
class Engine:
def __init__(self, args):
self.args, self.waiting = args, queue.Queue()
def emit(self, req):
if not req.cancelled:
req.tokens.put(" " + WORDS[req.generated % len(WORDS)])
req.generated += 1
if req.cancelled or req.generated >= req.max_tokens:
req.trace["decode_ms"] = ms_since(req.first)
req.done = True # frees the batch slot on every exit path
req.tokens.put(None)
def run(self):
running = []
while True:
while len(running) < self.args.max_batch: # admit waiting requests
try:
req = self.waiting.get(block=not running)
except queue.Empty:
break
start = time.perf_counter()
req.trace["queue_ms"] = ms_since(req.arrived)
time.sleep(self.args.prefill_ms_per_token * req.prompt_tokens / 1000)
req.first = time.perf_counter()
req.trace["prefill_ms"] = ms_since(start)
self.emit(req) # prefill produces the first token
if not req.done:
running.append(req)
if running: # one decode step: longer when more requests share it
step = self.args.step_ms + self.args.step_ms_per_seq * len(running)
time.sleep(step / 1000)
for req in running:
self.emit(req)
running = [req for req in running if not req.done]
class Handler(BaseHTTPRequestHandler):
def send_event(self, payload):
self.wfile.write(b"data: " + payload.encode() + b"\n\n")
self.wfile.flush()
def do_POST(self):
try:
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
req = Request(len(str(body["prompt"]).split()), int(body["max_tokens"]))
except (TypeError, ValueError, KeyError):
self.send_error(400, "send JSON with prompt and max_tokens")
return # reject bad input before any work starts
ENGINE.waiting.put(req)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
try:
finished = False
while not finished:
pieces = [req.tokens.get()]
while not req.tokens.empty(): # tokens that piled up share an event
pieces.append(req.tokens.get())
finished = pieces[-1] is None
text = "".join(piece for piece in pieces if piece)
if text:
self.send_event(json.dumps({"choices": [{"text": text}]}))
usage = {"prompt_tokens": req.prompt_tokens,
"completion_tokens": req.generated}
self.send_event(json.dumps({"choices": [{"text": "",
"finish_reason": "length"}],
"usage": usage, "trace": req.trace}))
self.send_event("[DONE]")
except (BrokenPipeError, ConnectionResetError):
req.cancelled = True # the engine drops it at its next step
def log_message(self, *args):
pass # keep the terminal quiet
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--max-batch", type=int, default=4)
parser.add_argument("--prefill-ms-per-token", type=float, default=0.1)
parser.add_argument("--step-ms", type=float, default=5.0)
parser.add_argument("--step-ms-per-seq", type=float, default=1.0)
ENGINE = Engine(parser.parse_args())
threading.Thread(target=ENGINE.run, daemon=True).start()
server = ThreadingHTTPServer(("127.0.0.1", ENGINE.args.port), Handler)
print(f"mock server on http://127.0.0.1:{ENGINE.args.port}", flush=True)
server.serve_forever()Three details copy what real engines do. New requests join only between decode steps, so even an idle server makes a newcomer wait up to one step. The final event carries a usage field with the true token count and a trace with the time the request spent queued, in prefill, and in decode. And when a client disconnects, the next failed write marks the request cancelled, and the engine frees its batch slot at the next step instead of generating tokens nobody will read.
- Start the mock server
Run it in its own terminal and leave it running. It listens on
127.0.0.1:8000.python mock_server.py - Stream four tokens
Use a second terminal.
-Nstops curl from buffering, so you see events as they arrive.curl -sN http://127.0.0.1:8000/v1/completions \ -H 'Content-Type: application/json' \ -d '{"prompt":"Where is my order?","max_tokens":4,"stream":true}'
data: {"choices": [{"text": " your"}]}
data: {"choices": [{"text": " order"}]}
data: {"choices": [{"text": " ships"}]}
data: {"choices": [{"text": " from"}]}
data: {"choices": [{"text": "", "finish_reason": "length"}], "usage": {"prompt_tokens": 4, "completion_tokens": 4}, "trace": {"queue_ms": 0.43, "prefill_ms": 0.54, "decode_ms": 22.14}}
data: [DONE]The words are canned; the framing and the timing are what matter. Here every event carried one token, because the client kept up. The server’s handler, like a real one, puts tokens that piled up while it was busy into a single event, and engines running speculative decoding send several accepted tokens at once. So remember: events are not tokens. A benchmark that counts events miscounts output, which is why the final usage field exists.
Measure latency from the client
Measure where the user is: in the client, with a monotonic clock such as Python’s time.perf_counter(). Server metrics start when the server reads the request, so they miss the network, a load balancer’s queue, and any proxy that buffers the stream. Record one timestamp when you send the request and one each time an event arrives. Every metric comes from those timestamps:
| Metric | Starts | Stops |
|---|---|---|
| TTFT | Request sent | First content event arrives |
| Inter-token latency (ITL) | An event arrives | The next event arrives (one sample per gap) |
| TPOT | First event arrives | Last event arrives, divided by (output tokens − 1) |
| End-to-end latency (E2E) | Request sent | [DONE] or the last byte arrives |
| Output throughput | First request of the run sent | Last request of the run finishes; divide total output tokens by this time |
ITL and TPOT sound alike but answer different questions. TPOT is one average per request. ITL keeps every gap, so a single long pause stays visible. Here is a request whose stream stalls because another user’s long prompt ran its prefill on the same GPU:
Metrics for tokens arriving at 60, 80, 100, 250, 270, and 290 ms
- TTFT
60 ms - ITL samples (gaps between arrivals)
20, 20, 150, 20, 20 ms - Median ITL and largest ITL
20 ms and 150 ms - TPOT
(290 − 60) / (6 − 1) = 46 ms - E2E
290 ms - This request’s output rate
6 tokens / 0.29 s ≈ 20.7 tokens/s
ResultTPOT says 46 ms per token; the user saw steady 20 ms gaps and one 150 ms freeze
Neither number lies, but only ITL tells you there was a freeze. Across many requests, report percentiles, not means. The 50th percentile (p50, the median) is the typical experience; p95 and p99 are the slowest 5% and 1%. A user who sends 20 messages in a session is likely to hit your p95 at least once. For a stable p99 you need hundreds of samples: with 50 requests, p99 is essentially your single slowest one.
Two more rules keep numbers honest. Send a few warm-up requests and discard them, because the first requests pay for one-time costs such as compilation, memory allocation, and cold caches. And fix the workload: prompts, max_tokens, sampling settings, and stop rules. If one run’s answers are twice as long, its E2E doubles for reasons that have nothing to do with your change.
Here is a measurement client you can point at any server that streams OpenAI-style completions. It uses only the standard library and NumPy. It sends 3 warm-up requests, then runs either a closed loop (a fixed number of clients, --concurrency) or an open loop (a fixed arrival rate, --rate), explained in the next section. It counts output tokens from the final usage field, and when the server sends a trace, it also reports the server’s queue, prefill, and decode spans. Save it as measure_stream.py:
"""Measure a streaming completions endpoint from the client: TTFT, ITL, E2E."""
import argparse
import json
import random
import time
from concurrent.futures import ThreadPoolExecutor
from urllib.request import Request, urlopen
import numpy as np
def one_request(url, prompt, max_tokens, sent_at=None):
body = json.dumps({"prompt": prompt, "max_tokens": max_tokens,
"temperature": 0, "stream": True}).encode()
request = Request(url, data=body, headers={"Content-Type": "application/json"})
start = sent_at or time.perf_counter() # open loop: the scheduled send time
arrivals, last = [], {}
with urlopen(request, timeout=300) as response:
for line in response:
if line.startswith(b"data: [DONE]"):
break
if line.startswith(b"data: "):
last = json.loads(line[6:])
if last["choices"][0]["text"]: # a content event
arrivals.append(time.perf_counter())
return start, arrivals, time.perf_counter(), last
def report(name, values):
p50, p95, p99 = np.percentile(values, [50, 95, 99])
print(f"{name:<8} p50 {p50:8.1f} ms p95 {p95:8.1f} ms p99 {p99:8.1f} ms")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--url", default="http://127.0.0.1:8000/v1/completions")
parser.add_argument("--requests", type=int, default=50)
parser.add_argument("--concurrency", type=int, default=1)
parser.add_argument("--rate", type=float, default=0.0, help="open loop, req/s")
parser.add_argument("--prompt-words", type=int, default=200)
parser.add_argument("--max-tokens", type=int, default=32)
args = parser.parse_args()
prompt = " ".join(["policy"] * args.prompt_words)
def send(sent_at=None):
return one_request(args.url, prompt, args.max_tokens, sent_at)
for _ in range(3): # warm-up requests are sent but never recorded
send()
begin = time.perf_counter()
if args.rate: # open loop: Poisson arrivals, whatever the server is doing
rng, due, futures = random.Random(0), time.perf_counter(), []
with ThreadPoolExecutor(max_workers=512) as pool:
for _ in range(args.requests):
due += rng.expovariate(args.rate)
time.sleep(max(0.0, due - time.perf_counter()))
futures.append(pool.submit(send, due))
results = [future.result() for future in futures]
else: # closed loop: each client sends its next request when one finishes
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
results = list(pool.map(lambda _: send(), range(args.requests)))
wall = time.perf_counter() - begin
ms = 1000
report("TTFT", [(arr[0] - start) * ms for start, arr, _, _ in results])
report("ITL", [(b - a) * ms for _, arr, _, _ in results
for a, b in zip(arr, arr[1:])])
report("E2E", [(end - start) * ms for start, _, end, _ in results])
traces = [last["trace"] for *_, last in results if "trace" in last]
for span in ("queue_ms", "prefill_ms", "decode_ms") if traces else ():
report(span[:-3], [trace[span] for trace in traces])
events = sum(len(arr) for _, arr, _, _ in results)
tokens = sum(last.get("usage", {}).get("completion_tokens", 0)
for *_, last in results)
print(f"{len(results)} requests in {wall:.1f} s: {len(results) / wall:.1f} req/s,"
f" {tokens / wall:.0f} tokens/s, {tokens} tokens in {events} events")
if __name__ == "__main__":
main()With the mock server running, measure one client at a time. Each request sends a 200-word prompt and asks for 32 tokens:
python measure_stream.pyTTFT p50 26.2 ms p95 28.0 ms p99 28.3 ms
ITL p50 7.5 ms p95 7.7 ms p99 7.8 ms
E2E p50 255.0 ms p95 258.8 ms p99 260.7 ms
queue p50 0.2 ms p95 0.3 ms p99 0.3 ms
prefill p50 24.7 ms p95 25.1 ms p99 25.1 ms
decode p50 229.0 ms p95 233.2 ms p99 234.0 ms
50 requests in 12.7 s: 3.9 req/s, 126 tokens/s, 1600 tokens in 1600 eventsCheck that the numbers add up before you trust them. The server was told to spend 20 ms on prefill and 6 ms per decode step (5 ms plus 1 ms for one running request), but the trace shows 24.7 ms and the client sees 7.5 ms gaps: this laptop’s operating system wakes sleeping threads a millisecond or more late. On your machine the extra time will differ. TTFT (26.2 ms) is queue plus prefill plus about 1 ms of HTTP work, and E2E is close to TTFT plus 31 gaps: 26.2 + 31 × 7.5 ≈ 259 ms. If TTFT is larger than E2E or an ITL sample is negative, a timer started or stopped in the wrong place.
Generate load the way users arrive
A closed-loop load test runs a fixed number of clients, and each sends its next request only when the previous one finishes. An open-loop test sends requests on a schedule, typically random (Poisson) arrivals at a chosen rate, whether or not earlier requests have finished. Real users behave like an open loop: nobody waits for a stranger’s request to finish before pressing Enter.
The difference matters when the server slows down. A closed loop slows down with it, so the queue never grows and latency looks fine. This is called coordinated omission: the test stops sending exactly when the server struggles. Little’s law makes the limit precise: requests in the system = arrival rate × time each spends there. Eight clients whose requests take 0.87 s each can never offer more than 8 / 0.87 s ≈ 9.2 requests per second, however slow the server gets.
Here is what that looks like on the mock server with its default --max-batch 4, measured with measure_stream.py on one laptop. Closed loops ran 50 or 100 requests, open loops 200 (yours will differ):
| Load | TTFT p50 | TTFT p99 | Completed |
|---|---|---|---|
| Closed loop, 1 client | 26 ms | 28 ms | 3.9 req/s |
| Closed loop, 4 clients | 61 ms | 102 ms | 9.1 req/s |
| Closed loop, 8 clients | 491 ms | 541 ms | 9.2 req/s |
| Open loop, 4.5 req/s | 33 ms | 226 ms | 4.3 req/s |
| Open loop, 8 req/s | 69 ms | 731 ms | 7.4 req/s |
| Open loop, 12 req/s | 1,242 ms | 4,404 ms | 9.1 req/s |
python measure_stream.py --rate 12 --requests 200TTFT p50 1241.8 ms p95 4140.9 ms p99 4403.6 ms
ITL p50 11.3 ms p95 34.9 ms p99 36.6 ms
E2E p50 1648.8 ms p95 4549.6 ms p99 4745.4 ms
queue p50 1210.7 ms p95 4112.4 ms p99 4374.5 ms
prefill p50 24.9 ms p95 25.1 ms p99 25.1 ms
decode p50 410.6 ms p95 419.7 ms p99 422.1 ms
200 requests in 22.1 s: 9.1 req/s, 290 tokens/s, 6400 tokens in 6400 eventsRead the table from the top. Capacity is about 9 requests per second: four requests share each decode step, and each takes about 0.44 s (4 / 0.44 ≈ 9.1). The Completed column counts the whole run, including the last requests draining, so an open loop’s reads a little under its arrival rate. Eight closed-loop clients already wait in line (TTFT 491 ms), but the wait is capped, because the other four clients stop sending while they wait. The open loop at 12 per second has no such cap. Arrivals outpace completions by about 3 per second, so the queue grows for as long as the test runs: p99 TTFT reached 4.4 seconds, almost all of it queue time, while ITL stayed near 11 ms. A longer test would report a larger number. Only an open loop shows this.
Notice also that p99 rises long before the median does. At 4.5 requests per second, under half of capacity, the median TTFT is 33 ms but p99 is already 226 ms, because Poisson arrivals come in bursts. The p99 ITL of 35 ms has a cause you saw in the figure above: when newcomers are admitted, their 25 ms prefills pause every running stream.
Use both kinds of test. Sweep a closed loop over concurrency (1, 2, 4, 8, and so on) to learn the server’s capacity. Then run an open loop at rates below that capacity, such as 50%, 70%, and 90%, to see the latency users will get at realistic traffic. vLLM’s vllm bench serve does both: --request-rate sets Poisson arrivals, --max-concurrency caps requests in flight, and the default rate is inf, which sends every request at time 0.
Go deeperWhy latency rises sharply near capacity
Queueing theory gives the shape. In the simplest model (one server, random arrivals, random service times), the average time in the system is 1 / (μ − λ), where μ is the completion rate and λ the arrival rate. At λ = 0.5μ, requests spend 2 service times in the system; at 0.9μ, 10; at 0.99μ, 100. Latency grows slowly at low load and explodes near the limit. The measurements above follow the same shape: p99 TTFT went from 226 ms at 4.5 requests per second to 731 ms at 8.
An LLM server is not that simple model: continuous batching lets it serve more requests at once as load rises, until the KV cache or compute runs out. The lesson survives, though: plan to run at a clear margin below measured capacity, and look at p99, which rises long before the median does.
Read a trace to find the bottleneck
Client metrics tell you something is slow. A trace tells you where. It splits each request into timed spans: waiting in the queue, prefill, decode, and sending. Production engines export these per request, and vLLM’s metrics include histograms named vllm:request_queue_time_seconds, vllm:request_prefill_time_seconds, and vllm:request_decode_time_seconds, next to vllm:time_to_first_token_seconds and vllm:inter_token_latency_seconds.
Start with TTFT, because it is the sum of the stages before the first token. Split it, and the largest part names the bottleneck:
| Symptom | Trace shows | Likely cause | Next step |
|---|---|---|---|
| High TTFT, healthy ITL | Long queue time | More arrivals than capacity, or a full KV cache | Check vllm:num_requests_waiting and vllm:kv_cache_usage_perc; add capacity, cap concurrency, or lower max_tokens |
| High TTFT, healthy ITL | Short queue, long prefill | Long prompts | Reuse shared prefixes (prefix caching), trim prompts, or add compute |
| Healthy TTFT, high ITL everywhere | Long decode steps | Large batches or long contexts: too many bytes read per step | Smaller batches, an FP8 KV cache, quantized weights, or speculative decoding at low load |
| Periodic ITL spikes | Decode steps interrupted by other requests’ prefills | Long prefills scheduled between decode steps | Chunked prefill: split long prompts across several steps |
| Server TTFT fine, client TTFT high | Server spans short | Network, TLS setup, or a proxy buffering the stream | Measure at the proxy; disable response buffering for SSE |
The first two rows share a symptom, which is why you must split TTFT before acting. A faster attention kernel does nothing for a request that spent 1.2 s in a queue.
The mock server’s trace gives you the same spans, and measure_stream.py prints their percentiles. Run an open loop at 8 requests per second, about 87% of capacity, and split the slow TTFT:
python measure_stream.py --rate 8 --requests 200TTFT p50 69.4 ms p95 604.4 ms p99 731.1 ms
ITL p50 11.0 ms p95 33.7 ms p99 36.6 ms
E2E p50 452.9 ms p95 996.1 ms p99 1139.1 ms
queue p50 38.5 ms p95 573.4 ms p99 701.5 ms
prefill p50 24.3 ms p95 25.1 ms p99 25.1 ms
decode p50 399.5 ms p95 417.1 ms p99 419.3 ms
200 requests in 26.9 s: 7.4 req/s, 238 tokens/s, 6400 tokens in 6400 eventsOf the 604 ms p95 TTFT, 573 ms is queue and 25 ms is prefill. This is the queue-bound row of the table: requests wait for one of the four batch slots. So change one thing that targets the queue. Stop the server, restart it with python mock_server.py --max-batch 8, and run the same command:
python measure_stream.py --rate 8 --requests 200TTFT p50 35.4 ms p95 93.8 ms p99 300.6 ms
ITL p50 11.4 ms p95 37.5 ms p99 60.0 ms
E2E p50 459.5 ms p95 703.4 ms p99 795.2 ms
queue p50 5.6 ms p95 66.6 ms p99 269.5 ms
prefill p50 25.0 ms p95 25.1 ms p99 25.1 ms
decode p50 422.7 ms p95 643.5 ms p99 652.4 ms
200 requests in 26.3 s: 7.6 req/s, 243 tokens/s, 6400 tokens in 6400 eventsThe span you aimed at moved: p95 queue time fell from 573 to 67 ms, and p95 TTFT from 604 to 94 ms. Now check what else moved. Up to eight requests share each decode step, so steps are longer, p95 decode time rose from 417 to 644 ms, and p99 ITL rose from 37 to 60 ms because more newcomers’ prefills interrupt each stream. Whether that trade is worth it depends on your targets. That is the trace-reading habit: every optimization targets one span, so confirm it moved and look at the others before you keep it.
Speculative decoding: fewer passes for the same tokens
Suppose the trace says decode is the bottleneck and traffic is light: each user’s stream runs at the speed of one weight read per token. You saw in the first lesson that such a step leaves the compute units almost idle, and that a pass over up to about 295 tokens costs about the same as a pass over one. Speculative decoding turns that idle compute into speed.
- Draft
A cheap proposer guesses the next
ktokens. It can be a small model, extra prediction heads trained on the large model, or a lookup of repeated text in the prompt (n-gram matching). - Verify in one pass
The large target model processes the current token and all
kguesses in a single forward pass, which yields its own choice at each of thek + 1positions. - Accept the matching prefix
Guesses are accepted from left to right while they match the target. At the first mismatch, the target’s own token replaces the guess, and every later guess is discarded, because it was built on a wrong token.
- Take one token from the target
Every round ends with one token from the target: the correction at the first mismatch, or a bonus token after the last position when all
kguesses match. So a round yields between 1 andk + 1tokens.
With greedy decoding the output is identical to running the target alone, because every kept token is one the target would have chosen. With sampling, a rejection-sampling rule accepts each guess with probability min(1, p_target / p_draft) and resamples on rejection, which keeps the target’s output distribution exactly.
The script below runs greedy speculative decoding with the cheapest kind of draft, prompt lookup: find the last token earlier in the text and propose the tokens that followed it. The target is faked by a function that always continues one fixed sentence, which is all a greedy model does for a given context. Save it as spec_demo.py:
"""Greedy speculative decoding with a prompt-lookup (n-gram) draft."""
TEXT = ("the cat sat on the mat . the cat ran to the mat . "
"the dog sat on the mat .").split()
def target(context):
"""The expensive model, faked: its greedy next token for a context."""
return TEXT[len(context)]
def draft(context, k):
"""Find the last token earlier in the context and copy what followed it."""
for i in range(len(context) - 2, -1, -1):
if context[i] == context[-1]:
return context[i + 1:i + 1 + k]
return []
def speculate(prompt, new_tokens, k):
out, passes = list(prompt), 0
while len(out) < len(prompt) + new_tokens:
left = len(prompt) + new_tokens - len(out)
guesses = draft(out, min(k, left - 1))
passes += 1 # one target pass scores all the guesses at once
accepted = 0
while (accepted < len(guesses)
and guesses[accepted] == target(out + guesses[:accepted])):
accepted += 1
token = target(out + guesses[:accepted]) # correction or bonus token
out += guesses[:accepted] + [token]
print(f"pass {passes}: draft {' '.join(guesses) or '(none)':<11}"
f" accepted {accepted}, target adds {token!r}")
return out, passes
prompt = TEXT[:8]
out, passes = speculate(prompt, len(TEXT) - 8, k=3)
print("same output as the target alone:", out == TEXT)
print(f"{len(TEXT) - 8} new tokens in {passes} target passes instead of"
f" {len(TEXT) - 8}")pass 1: draft mat . the accepted 0, target adds 'cat'
pass 2: draft sat on the accepted 0, target adds 'ran'
pass 3: draft (none) accepted 0, target adds 'to'
pass 4: draft (none) accepted 0, target adds 'the'
pass 5: draft cat ran to accepted 0, target adds 'mat'
pass 6: draft . the cat accepted 2, target adds 'dog'
pass 7: draft (none) accepted 0, target adds 'sat'
pass 8: draft on the mat accepted 3, target adds '.'
same output as the target alone: True
13 new tokens in 8 target passes instead of 13Thirteen new tokens took 8 target passes instead of 13, with identical output. Most passes kept only the target’s own token, because the draft had nothing to copy (“ran”, “to”, and “dog” had not appeared before) or copied the wrong continuation. Pass 8 shows the best case: all three guesses matched, and the target still added a bonus token, 4 tokens for one pass. Prompt lookup shines on text that repeats its input, such as code edits or answers that quote the question, and does little on fresh prose. The demo also measures no time, which is where the real question lies: do fewer passes mean faster?
Let α be the probability that the target accepts a guess, and assume each guess is accepted independently. Leviathan and colleagues showed that one round then yields on average (1 − α^(k+1)) / (1 − α) tokens. If one draft pass costs a fraction c of a target pass, and verifying k + 1 positions costs about one target pass (true while decode is limited by reading weights), the expected speedup is that number divided by (k × c + 1).
Worked example: α = 0.8, k = 4, draft cost c = 0.05
- Tokens per round
(1 − 0.8^5) / (1 − 0.8) = (1 − 0.32768) / 0.2 = 3.36 - Cost of a round, in target passes
4 × 0.05 + 1 = 1.2 - Expected speedup
3.36 / 1.2 = 2.80 - Guesses accepted per round
3.36 − 1 = 2.36 of 4, or 59% of drafted tokens - Same draft at α = 0.3 and c = 0.2
(1 − 0.3^5) / 0.7 = 1.43 tokens; 1.43 / 1.8 = 0.79, a slowdown
ResultAt α = 0.8, k = 4, and c = 0.05, Llama 3.1 8B's 4.8 ms floor per token would fall to about 1.7 ms
The script below checks the formula against a simulation and prints the speedup for a few settings. Save it as spec_math.py:
import numpy as np
def expected_tokens(alpha, k):
"""Tokens per target pass: accepted drafts plus one corrected or bonus token."""
return (1 - alpha ** (k + 1)) / (1 - alpha)
def simulate(alpha, k, rounds, rng):
accepted = rng.random((rounds, k)) < alpha # each draft passes or fails
run = np.cumprod(accepted, axis=1).sum(axis=1) # stop at the first failure
return (run + 1).mean() # plus the target's token
rng = np.random.default_rng(0)
print("alpha k formula simulated speedup(c=0.05)")
for alpha, k in [(0.6, 4), (0.8, 2), (0.8, 4), (0.8, 8), (0.9, 4)]:
tokens = expected_tokens(alpha, k)
simulated = simulate(alpha, k, 100_000, rng)
speedup = tokens / (k * 0.05 + 1)
print(f"{alpha:5.1f} {k:2d} {tokens:8.2f} {simulated:10.2f} {speedup:16.2f}")
alpha, k = 0.8, 4
accepted = expected_tokens(alpha, k) - 1
print(f"alpha {alpha}, k {k}: {accepted:.2f} of {k} drafts accepted per round,"
f" a logged acceptance rate of {accepted / k:.0%}")alpha k formula simulated speedup(c=0.05)
0.6 4 2.31 2.31 1.92
0.8 2 2.44 2.44 2.22
0.8 4 3.36 3.36 2.80
0.8 8 4.33 4.33 3.09
0.9 4 4.10 4.09 3.41
alpha 0.8, k 4: 2.36 of 4 drafts accepted per round, a logged acceptance rate of 59%Read the k column at α = 0.8: going from 4 to 8 guesses adds only 0.97 tokens per round, because later guesses rarely survive. Larger k pays off only when α is high. Published results match this shape: in the original paper, a 77-million-parameter draft for an 11-billion-parameter target reached α = 0.75 and a 3.4× speedup at batch size 1, while a 10 times larger draft with α = 0.82 gave only 1.7×, because it cost more to run.
Go deeperWhere the tokens-per-round formula comes from
A round yields 1 token for sure (the target’s correction or bonus), plus 1 more for each guess accepted before the first rejection. Guess i survives only if guesses 1 to i are all accepted, which happens with probability α^i. So the expected yield is 1 + α + α^2 + ... + α^k, a geometric series equal to (1 − α^(k+1)) / (1 − α).
The independence assumption is optimistic in one way and pessimistic in another. Acceptance is higher on predictable text (code, JSON, repeated phrases from the prompt) and lower on creative text, so measure α on your own traffic. The walltime formula also ignores verification overhead and the work of rolling back rejected positions in the KV cache, which real engines must do.
In vLLM 0.28.0, you enable it with a JSON --speculative-config, for example {"method": "ngram", "num_speculative_tokens": 4, "prompt_lookup_max": 4}. Its documentation reports that model-based methods (EAGLE, MTP, draft models) cut latency the most, and that gains are largest at low request rates. Track vllm:spec_decode_num_accepted_tokens and vllm:spec_decode_num_draft_tokens alongside ITL, and keep speculation only if ITL improves at your real traffic.
Capstone: plan, measure, and improve one service
This exercise uses every lesson in the course. You are launching the support assistant on Llama 3.1 8B in BF16, one 80 GB H100, and must promise p95 TTFT under 500 ms and p95 ITL under 50 ms. Typical conversations hold 1,500 prompt tokens and 300 output tokens. Work through the steps, write your numbers down, then compare with the answers in the panel below.
- Describe the workload in tokens
Render one real conversation through the chat template and count its tokens, as in the tokens lesson. Confirm your prompt length includes the template’s 35 or so extra tokens.
- Size the memory
Using the KV cache lesson, calculate cache per conversation and how many fit in a 52 GB cache budget (80 GB × 0.9, a chosen setting, minus about 16 GB of weights and 4 GB of working memory). Repeat with an FP8 cache from the quantization lesson.
- Estimate latency floors
With the method from the first lesson and the batching lesson, estimate the prefill floor for 1,500 tokens and the decode step floor with 32 conversations running.
- Measure the mock server
Run
measure_stream.pyagainstmock_server.py: closed loop at 1, 2, 4, and 8 clients with at least 50 requests each, then open loop at 50%, 70%, and 90% of the capacity you found. Report p50, p95, and p99 for TTFT, ITL, and E2E. Then repeat one open-loop rate with--prompt-words 2000to see a prefill-bound service. - Find the bottleneck
Use the queue, prefill, and decode spans that
measure_stream.pyprints, and the trace table above, to decide which span dominates at your target load. - Choose one change and a rollback rule
Pick one optimization (batch limit, FP8 cache, prefix caching, chunked prefill, or speculative decoding), predict its effect in numbers, and write down the measurement that would make you undo it.
Go deeperCheck your numbers
Reference answers for the H100 plan (idealized floors, not measurements)
- KV cache per conversation
1,800 tokens × 128 KiB = 225 MiB (235,929,600 bytes) - Conversations that fit in 52 GB, BF16 cache
52,000,000,000 / 235,929,600 ≈ 220 - With an FP8 cache (64 KiB per token)
about 440 - Prefill floor, 1,500 tokens
1,500 × 16.06 GFLOP / 989 TFLOPS ≈ 24.4 ms - KV reads per decode step, 32 conversations
32 × 1,800 × 131,072 bytes ≈ 7.55 GB → 2.25 ms - Decode step floor
4.79 ms (weights) + 2.25 ms ≈ 7.05 ms, about 4,540 tokens/s in total - E2E floor per conversation
24.4 ms + 299 × 7.05 ms ≈ 2.13 s
ResultBoth targets have room at 32 conversations; the risk is queueing when bursts exceed capacity
A defensible recommendation reads like this: “Cap the running batch at 64 conversations and alert when vllm:num_requests_waiting stays above zero for a minute. Expected: p95 TTFT stays under 500 ms at 70% of measured capacity. Roll back if p95 ITL exceeds 50 ms in an open-loop test at that rate.” Speculative decoding is a weaker first choice here: at 32 conversations and k = 4, each pass already covers 160 tokens, more than half the way to the 295-token crossover, so its gain would be modest.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| TTFT looks great in the server’s metrics but users see seconds | The time before the server read the request (load balancer queue, TLS setup) was never measured. | Time from the client, and compare with server spans. |
| Tokens per second are too low or too high | SSE events were counted as tokens. | Count tokens with the tokenizer or the usage field. |
| The first run of every benchmark is slower | Warm-up costs landed in the measurements. | Send warm-up requests first and discard them. |
| Latency looks fine in testing, then explodes in production | A closed-loop test hid queueing. | Run an open-loop test at the real arrival rate. |
| p99 jumps between identical runs | Too few samples: p99 of 50 requests is the single slowest one. | Collect hundreds of requests per setting, and repeat the run. |
| An optimization improves the benchmark but not the service | It shrank a span that was not the bottleneck. | Split TTFT and ITL with a trace before and after the change. |
| The stream stalls behind a proxy | The proxy buffers the response until it completes. | Turn off response buffering for event streams and measure at the proxy. |
Cheat sheet
- Measure at the client with a monotonic clock: send, first event, every event,
[DONE]. - TTFT = first event − send; ITL = each gap; TPOT = (E2E − TTFT) / (tokens − 1); throughput = total tokens / wall time.
- Report p50, p95, and p99 after warm-up, with a fixed workload. Events are not tokens.
- Closed loops hide queueing; test with an open loop at the real arrival rate.
- Split TTFT into queue and prefill before fixing anything. Slow TTFT with healthy TPOT points to queueing and prefill.
- Speculative decoding: (1 − α^(k+1)) / (1 − α) tokens per target pass; speedup ≈ that / (k × c + 1).
- Speculation helps when decode is memory-bound and traffic is light; at large batches it can slow things down.
Walkthrough
Measure one request's lifecycle
Knowledge check