Phase 04/Measure and tune/Latency and throughput engineering
PHASE 04 · Measure and tune

Latency and throughput engineering

0%
8 h6 subtopics2 lessons · 2 required
In plain English

Two different things can be meant by "fast". Latency is how long one person waits for their answer; throughput is how many answers the whole system produces per second. They pull against each other. A bus that waits to fill every seat moves more people per hour but each rider waits longer at the stop; a taxi leaves immediately but moves fewer people. Serving a model is the same: batching more requests together raises throughput but makes each token arrive a little later. Engineers split latency into the wait for the first word (time to first token) and the pause between later words (inter-token latency), because different parts of the system cause each, and then tune batch size and scheduling to hit a target like "95 percent of users see their first word within half a second" at the lowest cost.

Why it matters

Every inference optimization is judged by its effect on TTFT, ITL and throughput at a given cost, and most production incidents are a latency SLO breach. Knowing the roofline for prefill and decode lets you predict the best achievable numbers before you benchmark and recognize when an engine is far from them.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Cursor, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Define TTFT, ITL, TPOT, end-to-end latency, goodput and tokens per second and compute them from raw request timestamps.
  • Build a roofline model that predicts prefill and decode time from model size, batch size, GPU bandwidth and peak FLOPs.
  • Run a load sweep and locate the knee where throughput saturates and latency climbs.
  • Decide a batch size and max-num-seqs setting for a given latency SLO using measured data.
  • Explain why GPU utilization as reported by nvidia-smi can be 100 percent while the GPU is mostly idle.

Key concepts

Time to first token (TTFT)
Time from request arrival to the first output token; dominated by queueing plus prefill.
Inter-token latency (ITL)
Time between consecutive output tokens for one request; dominated by decode step time, which grows with batch size.
Time per output token (TPOT)
Average ITL over a request; used interchangeably with ITL in many reports.
Throughput
Output (or total) tokens per second across all requests; rises with batch size until compute saturates.
Goodput
Throughput counting only requests that met their latency SLO.
Roofline
Time is max(bytes / bandwidth, FLOPs / peak); decode sits on the bandwidth roof, prefill on the compute roof.
Arithmetic intensity of a batch
For a matmul with batch B tokens, roughly B FLOPs per weight byte; the crossover batch is peak_flops / bandwidth, a few hundred on modern GPUs.
SM utilization versus GPU-Util
nvidia-smi GPU-Util only says a kernel was running sometime in the sample window; Nsight's SM throughput shows how busy the cores really were.
Chunked prefill
Splitting long prefills into chunks interleaved with decode steps so one long prompt does not spike everyone's ITL.

Subtopics

  1. 1. Metric definitions and measurement

    Collect per-token timestamps from a streaming client and derive TTFT, ITL, E2E, tokens/s and percentiles; avoid common mistakes like averaging percentiles.

  2. 2. Roofline for prefill and decode

    Decode step time is about weight_bytes / bandwidth plus KV reads; prefill is about 2 * params * tokens / peak_flops; derive the crossover batch size.

  3. 3. The latency-throughput curve

    Sweep concurrency, plot throughput and p50/p99 latency, find the knee; relate it to max-num-seqs and max-num-batched-tokens.

  4. 4. Optimizing TTFT

    Scheduling priority for new requests, chunked prefill, prefix caching, and prompt-length-aware admission.

  5. 5. Optimizing ITL

    Batch size caps, CUDA Graphs, quantization, speculative decoding; which help at which batch sizes.

  6. 6. GPU utilization that means something

    Why GPU-Util is misleading, what SM throughput and DRAM throughput in Nsight tell you, and how to compute achieved versus roofline bandwidth.

Resources

Hands-on lessons

L1

Build a roofline calculator and check it against real numbers

CPU · your Macnotebook90 minrequired

Goal · Predict prefill time, decode step time and the crossover batch size for three models on a T4, A100 and H100 and compare with published benchmark figures.

  1. 1Enter specs for T4, A100-80GB and H100-SXM (HBM bandwidth, FP16 dense tensor-core TFLOPs) from the NVIDIA datasheets.
  2. 2For Llama-2-7B, Llama-3-8B and a 70B model compute weight bytes in FP16 and FP8 and KV bytes per token from config.json.
  3. 3Write decode_step_time(batch, context) = max(weight_bytes + batch*context*kv_bytes_per_token, ...) / bandwidth versus 2*params*batch / peak_flops, taking the max.
  4. 4Write prefill_time(prompt_len) using the same roofline and compute TTFT for prompts of 128, 1024 and 8192 tokens.
  5. 5Plot decode tokens/s versus batch size for each GPU and mark the crossover batch where it bends.
  6. 6Compare your A100 Llama-2-7B batch-1 decode prediction with a published vLLM or TensorRT-LLM number and explain the gap in percent.
Deliverable
A notebook with the calculator, the tokens/s-versus-batch plot and a short comparison with published numbers.
Check
Your batch-1 FP16 decode prediction for Llama-2-7B on A100 is in the 7-10 ms per token range, and the crossover batch is in the hundreds.
L2

Load sweep and SLO-based tuning on a real engine

Colab T4 · freeexperiment120 minrequired

Goal · Sweep concurrency against vLLM on a T4, plot throughput and p50/p99 TTFT and ITL, and pick a max-num-seqs that meets a chosen SLO.

  1. 1Start vllm serve with a small instruct model on Colab; write or reuse an asyncio streaming client that records arrival, first-token and every-token timestamps per request.
  2. 2Generate a workload of 200 requests with prompt lengths sampled from 64-512 and max_tokens 128.
  3. 3Run at concurrency 1, 2, 4, 8, 16, 32 and compute throughput, p50 and p99 TTFT and ITL for each.
  4. 4Plot throughput versus concurrency and p99 latency versus concurrency on shared axes; mark the knee.
  5. 5Pick an SLO (e.g. p99 TTFT under 1 s and p99 ITL under 100 ms) and choose the highest concurrency that meets it; restart with --max-num-seqs at that value and confirm.
  6. 6Enable chunked prefill and repeat concurrency 16; record the ITL change.
Deliverable
The client script, the sweep CSV, the two plots and a one-paragraph tuning recommendation.
Check
Throughput saturates while p99 ITL keeps rising past the knee; the chosen max-num-seqs meets the SLO on a confirmation run.
Fallback
Run the same sweep against llama.cpp server or transformers on CPU with a tiny model and concurrency 1-8; the curve shape is the same even though the numbers are slower.

Build your own

Build your own latency/throughput explorer

PythonCPU · your Mac~8 h

A streaming load generator and analyser that produces TTFT and ITL percentiles, the latency-throughput curve, and goodput under an SLO for any OpenAI-compatible server, verified against a mock server with known timing.

The real thing: github.com/vllm-project/vllm/tree/main/benchmarks ↗

How you know a stage passes

Write tests/test_explorer.py first, together with tests/mock_server.py, an OpenAI-compatible mock that streams tokens on a configurable schedule (TTFT, per-token cadence, occasional slow tokens, a concurrency cap) so every metric has an exact expected value. Each stage adds a test against the mock; the final stages also run against a real CPU server (llama.cpp server with a small GGUF, or the Phase-3 server you built). `explore.py run|plot` is the CLI. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01a streaming client that timestamps every token
    An async client sends one chat completion with stream true and records request start, first-token time and every subsequent token's arrival.
    test · Against the mock configured for 100 ms TTFT and a 20 ms cadence, measured TTFT is within 100 plus or minus 10 ms and median ITL within 20 plus or minus 2 ms over 20 requests.
  2. 02closed-loop concurrency sweep
    For each concurrency level in 1, 2, 4, 8, 16, 32, keep exactly that many requests in flight for a fixed duration after warmup and write per-request rows to results.csv.
    test · The CSV has the expected columns and at least 20 rows per level; against the mock with a concurrency cap of 8, output tokens per second grows up to 8 and then stays flat within 10 percent while ITL rises.
  3. 03open-loop Poisson arrivals
    Requests arrive at a target rate from an exponential inter-arrival distribution regardless of how many are in flight, so queueing becomes visible.
    test · Mean inter-arrival time over 500 requests is within 5 percent of 1 / rate; at a rate above the mock's capacity the last-quartile TTFT exceeds the first-quartile TTFT, and below capacity it does not.
  4. 04percentiles and goodput
    p50, p90 and p99 for TTFT, ITL and end-to-end per level, and goodput defined as requests per second whose TTFT and p90 ITL both meet an SLO given on the command line.
    test · With the mock injecting a 300 ms stall into exactly 5 percent of requests, goodput under an SLO of TTFT 200 ms and p90 ITL 50 ms equals 95 percent of throughput within 1 percentage point.
  5. 05plots and the knee
    `explore.py plot results.csv` writes the latency-throughput curve, TTFT and ITL percentiles versus load, and goodput versus load, and prints the knee: the first level where p99 ITL exceeds twice its value at concurrency 1.
    test · Three PNG files are written; on the mock the knee equals the configured concurrency cap; the knee is also printed as a line in the CLI output that a test parses.
  6. 06a real server and a roofline overlay
    Run the full sweep against the real CPU server and overlay a predicted ITL from weight bytes divided by measured memory bandwidth and the batch size.
    test · The predicted and measured ITL at concurrency 1 agree within a factor of 2; the README has the three plots, the knee, and the model-bandwidth utilisation you achieved at the knee.

Knowledge check

QWhy does ITL grow with batch size while throughput also grows?

Each decode step reads the weights once for the whole batch, so a bigger batch produces more tokens per step (higher throughput) but each step takes slightly longer as compute and KV reads grow (higher ITL).

QWhat dominates TTFT for a long prompt, and what two techniques reduce it?

Prefill compute and queueing; chunked prefill and prefix caching, plus prioritizing new requests in the scheduler.

QWhy can nvidia-smi show 100 percent GPU-Util for a decode workload that is far below roofline?

GPU-Util only measures the fraction of time any kernel was resident, not how many SMs or how much bandwidth it used; tiny kernels back to back look fully busy.

QWhat is the roofline estimate for batch-1 decode step time?

Roughly total weight bytes divided by memory bandwidth, e.g. 13 GB / 2 TB/s is about 6.5 ms for a 7B FP16 model on an A100.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 deliverables saved and both checks pass.
  • Can sketch the latency-throughput curve and explain the knee in roofline terms.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →