Education › Inference Engineering › Guided project

Inference benchmark lab and write-up

Rent one GPU, serve an open-weight model with vLLM, build a small measurement harness, and run a disciplined series of experiments: a baseline concurrency sweep, then one variable at a time (batch limits, KV-cache precision, context length, prefix caching). Watch the engine and GPU metrics while you do it, then turn the results into a short public write-up that names the bottleneck, the trade-off and the result. It is the exercise the whole Inference Engineering track builds towards, and the write-up is portfolio proof.

Intermediate about 6 hours 7 phases · 30 steps 0 / 30 done
What you will have at the end

A public repository with a reproducible serve/ setup, a bench/ harness and raw results for every run, plots of throughput against latency percentiles, and a REPORT.md that states your operating point (concurrency and settings that meet a latency target), the evidence for the bottleneck at each step, the cost per million tokens it implies, and what you would test next.

Before you start
  • Comfortable with Linux, Docker and Python
  • The stage 2 to 4 lessons of this track (lifecycle, KV cache, metrics, profiling, batching and benchmarking)
  • A cloud account that can rent a single NVIDIA GPU instance for a few hours, or a local NVIDIA GPU
Tools you will install
  • vLLM — the serving engine under test, run from its official container image ↗
  • Docker + NVIDIA Container Toolkit — run the engine and monitoring with GPU access ↗
  • Prometheus — scrape vLLM's metrics during the experiments ↗
  • Python (httpx, pandas, matplotlib) — the measurement harness and the plots ↗
  • nvidia-smi — GPU memory, utilisation and power during runs ↗
Repository layout at the end
inference-bench-lab/
├── serve/
│   ├── run-vllm.sh             # the exact engine command for each experiment
│   └── prometheus.yml          # scrapes vLLM /metrics
├── bench/
│   ├── harness.py              # streaming client: TTFT, TPOT, ITL per request
│   ├── sweep.sh                # concurrency sweep with vllm bench serve
│   └── analyse.py              # tables and plots from results/
├── results/
│   ├── baseline/               # raw JSON per run
│   ├── exp-max-num-seqs/
│   ├── exp-fp8-kv/
│   └── exp-prefix-cache/
├── plots/
└── REPORT.md                   # question, setup, results, bottleneck, trade-off, next test

Tick each step as you finish it — your progress is saved in this browser only (back up or restore on the hub). Every code block has a copy button. If something goes wrong, the troubleshooting section at the end covers the usual suspects.

Phase 1

Provision a GPU and check the stack

A GPU machine where Docker containers can see the GPU, with the facts you will need for sizing written down.

  1. Create a public repository for the lab and clone it onto the GPU machine. Rent a single-GPU instance with a recent NVIDIA driver image; a mid-range datacenter GPU with 24 GB or more is plenty for a small model.
    bash
    gh repo create inference-bench-lab --public --clone
    cd inference-bench-lab
    mkdir -p serve bench results plots
  2. Record the GPU model, memory, driver version and the highest CUDA version the driver supports. These go in the setup section of your report.
    bash
    nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv
    nvidia-smi | head -5
    Check: You see your GPU and its total memory.
  3. Install the NVIDIA Container Toolkit if the image does not include it, wire it into Docker and prove a container can see the GPU.
    bash
    sudo nvidia-ctk runtime configure --runtime=docker
    sudo systemctl restart docker
    docker run --rm --gpus all ubuntu nvidia-smi
    Check: The container prints the same GPU table.
  4. Pick a small open-weight instruct model (a few billion parameters) and compute, before running anything, its FP16 weight size and its KV bytes per token from its config.json. Write both into a notes file.
    KV bytes per token = 2 x num_hidden_layers x num_key_value_heads x head_dim x 2. This prediction is what you will check against the engine's own log.
Phase 2

Serve the model

vLLM serving the model in a pinned container, with weights cached on local disk and metrics exposed.

  1. Write the engine command into a script so every experiment is reproducible. Pin the image version, mount the Hugging Face cache so weights download once, run detached, and wait until the server is healthy before returning.
    bash
    cat > serve/run-vllm.sh <<'SCRIPT'
    #!/usr/bin/env bash
    set -euo pipefail
    MODEL_ID="${MODEL_ID:?set MODEL_ID}"
    docker rm -f vllm >/dev/null 2>&1 || true
    docker run -d --name vllm --gpus all --ipc=host -p 8000:8000 \
      -v "$HOME/.cache/huggingface:/root/.cache/huggingface" \
      -e HF_TOKEN \
      vllm/vllm-openai:v0.30.0 "$MODEL_ID" --max-model-len 8192 "$@"
    until curl -sf localhost:8000/health >/dev/null; do sleep 5; done
    echo "vLLM ready with extra args: $*"
    SCRIPT
    chmod +x serve/run-vllm.sh
  2. Start the baseline server. The script returns once the engine is healthy; follow its log with docker logs -f vllm in another terminal.
    bash
    export MODEL_ID=YOUR_ORG/YOUR_MODEL
    ./serve/run-vllm.sh
    If the model is gated, export HF_TOKEN first. The first start downloads weights; later starts reuse the cache.
    Check: curl -s localhost:8000/health returns HTTP 200.
  3. Find the line in the engine log that reports KV-cache capacity (in tokens or blocks) and compare it with your prediction from phase 1.
    If they differ a lot, check head_dim and num_key_value_heads in config.json, and the memory-utilisation default.
  4. Send one chat request to confirm the OpenAI-compatible API works end to end.
    bash
    curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
      -d "{\"model\": \"$MODEL_ID\", \"messages\": [{\"role\": \"user\", \"content\": \"Hi\"}], \"max_tokens\": 20}"
    Check: You get a JSON response with a short answer.
Phase 3

Build the measurement harness

A streaming client that records TTFT, TPOT and every inter-token gap per request, plus the engine's own benchmark for sweeps.

  1. Install the client libraries in a virtual environment.
    bash
    python3 -m venv .venv && source .venv/bin/activate
    pip install httpx pandas matplotlib vllm
    Installing vllm locally gives you vllm bench serve; it does not need to run the engine on this machine.
  2. Write a streaming harness that measures from the client side, where users feel latency.
    python
    # bench/harness.py
    import asyncio, json, os, sys, time
    import httpx
    
    URL = "http://localhost:8000/v1/chat/completions"
    MODEL = os.environ["MODEL_ID"]
    
    
    async def one(client, prompt, max_tokens):
        body = {"model": MODEL, "stream": True, "max_tokens": max_tokens,
                "messages": [{"role": "user", "content": prompt}]}
        t0, times = time.perf_counter(), []
        async with client.stream("POST", URL, json=body, timeout=600) as r:
            async for line in r.aiter_lines():
                if line.startswith("data: ") and line != "data: [DONE]":
                    if json.loads(line[6:])["choices"][0]["delta"].get("content"):
                        times.append(time.perf_counter())
        ttft = times[0] - t0
        tpot = (times[-1] - times[0]) / max(len(times) - 1, 1)
        gaps = [b - a for a, b in zip(times, times[1:])]
        return {"ttft": ttft, "tpot": tpot, "n": len(times), "max_gap": max(gaps, default=0)}
    
    
    async def main(concurrency, prompt_words, max_tokens, n):
        prompt = "word " * prompt_words + "\nSummarise the text above in detail."
        sem = asyncio.Semaphore(concurrency)
        async with httpx.AsyncClient() as client:
            async def guarded():
                async with sem:
                    return await one(client, prompt, max_tokens)
            results = await asyncio.gather(*[guarded() for _ in range(n)])
        print(json.dumps(results))
    
    
    if __name__ == "__main__":
        c, words, out, n = map(int, sys.argv[1:5])
        asyncio.run(main(c, words, out, n))
    The harness counts streamed chunks with content as tokens; engines usually send one token per chunk, which is close enough for latency work. Use the engine's benchmark for exact token throughput.
  3. Run it once at low load to check the numbers look sane.
    bash
    python bench/harness.py 1 500 200 5 > results/smoke.json
    python -c "import json;r=json.load(open('results/smoke.json'));print(r[0])"
    Check: TTFT is well under a second and TPOT is tens of milliseconds on a single request.
  4. Write the sweep script around vLLM's benchmark so every run uses the same workload and saves raw results.
    bash
    cat > bench/sweep.sh <<'EOF'
    #!/usr/bin/env bash
    set -euo pipefail
    OUT="results/${1:?experiment name}"
    mkdir -p "$OUT"
    for c in 1 4 8 16 32 64; do
      vllm bench serve --base-url http://localhost:8000 --model "$MODEL_ID" \
        --dataset-name random --random-input-len 1500 --random-output-len 300 \
        --num-prompts 300 --max-concurrency "$c" \
        --percentile-metrics ttft,tpot,itl --metric-percentiles 50,99 \
        --save-result --result-dir "$OUT" --result-filename "c${c}.json"
    done
    EOF
    chmod +x bench/sweep.sh
Phase 4

Watch while you measure

Engine and GPU metrics visible during every run, so you can attribute each result to a bottleneck.

  1. Start Prometheus scraping the engine's metrics endpoint.
    yaml
    # serve/prometheus.yml
    global:
      scrape_interval: 5s
    scrape_configs:
      - job_name: vllm
        static_configs:
          - targets: ["localhost:8000"]
  2. Run Prometheus with host networking so it can reach the engine on localhost.
    bash
    docker run -d --name prom --network host \
      -v "$PWD/serve/prometheus.yml:/etc/prometheus/prometheus.yml:ro" \
      prom/prometheus:v3.15.0
    Check: http://localhost:9090/targets shows the vllm target as UP (use an SSH tunnel if the instance has no public UI access).
  3. In a separate terminal, log GPU memory, utilisation and power once a second during runs.
    bash
    nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw \
      --format=csv -l 1 > results/gpu-log.csv
  4. Bookmark four queries in the Prometheus UI: waiting and running requests, KV-cache usage, preemptions, and p99 TTFT.
    promql
    vllm:num_requests_waiting
    vllm:num_requests_running
    vllm:kv_cache_usage_perc
    rate(vllm:num_preemptions_total[1m])
    histogram_quantile(0.99, sum by (le) (rate(vllm:time_to_first_token_seconds_bucket[1m])))
Phase 5

Baseline sweep

The throughput-versus-latency curve of the default configuration, and your operating point against a latency target.

  1. Choose and write down your latency targets before you look at results, for example p99 TTFT under 1 s and p99 TPOT under 50 ms.
    Deciding afterwards invites picking whatever looks good.
  2. Run two warm-up requests, then the baseline sweep.
    bash
    python bench/harness.py 2 200 50 4 > /dev/null
    ./bench/sweep.sh baseline
    Check: results/baseline/ contains c1.json to c64.json.
  3. While the high-concurrency runs execute, watch the four Prometheus queries and note at which concurrency waiting requests appear and whether KV-cache usage approaches 1.0.
  4. Write the analysis script that turns result files into a table and a throughput-versus-latency plot.
    python
    # bench/analyse.py
    import glob, json, re, sys
    import matplotlib.pyplot as plt
    import pandas as pd
    
    rows = []
    for exp in sys.argv[1:]:
        for f in glob.glob(f"results/{exp}/c*.json"):
            r = json.load(open(f))
            rows.append({"exp": exp, "concurrency": int(re.search(r"c(\d+)", f).group(1)),
                         "tok_s": r["output_throughput"],
                         "p99_ttft_ms": r["p99_ttft_ms"], "p99_tpot_ms": r["p99_tpot_ms"]})
    df = pd.DataFrame(rows).sort_values(["exp", "concurrency"])
    print(df.to_markdown(index=False))
    for exp, g in df.groupby("exp"):
        plt.plot(g["p99_tpot_ms"], g["tok_s"], marker="o", label=exp)
    plt.xlabel("p99 TPOT (ms)")
    plt.ylabel("output tokens/s")
    plt.legend()
    plt.savefig("plots/throughput_vs_tpot.png", dpi=150)
    Field names in the result JSON can change between vLLM versions; open one file and adjust the keys if needed. to_markdown needs the tabulate package (pip install tabulate).
  5. Run it for the baseline and mark the highest concurrency that meets both targets. That is your baseline operating point.
    bash
    pip install tabulate
    python bench/analyse.py baseline
Phase 6

One variable at a time

Three controlled experiments, each changing exactly one setting from the baseline, with the bottleneck identified for each.

  1. Experiment 1, batch limit: restart the engine with a lower sequence cap (the script replaces the running container) and rerun the sweep.
    bash
    ./serve/run-vllm.sh --max-num-seqs 16
    ./bench/sweep.sh exp-max-num-seqs
    Expect better per-user TPOT at high concurrency but more queueing (TTFT) once requests exceed the cap.
  2. Experiment 2, KV-cache precision: restart with an FP8 cache (default sequence cap) and rerun.
    bash
    ./serve/run-vllm.sh --kv-cache-dtype fp8
    ./bench/sweep.sh exp-fp8-kv
    Check the startup log: KV capacity in tokens should roughly double. FP8 cache needs GPU and model support; if it is rejected, record that as a finding.
  3. Spot-check quality for experiment 2: ask the FP8-cache server and the baseline the same ten questions and compare answers.
    Precision changes can affect output. A table of ten prompts with both answers side by side is enough for a write-up; serious deployments run a proper evaluation set.
  4. Experiment 3, prefix caching: keep the baseline engine but change the workload to share a long system prompt, and compare TTFT with prefix caching on (default) and off.
    bash
    ./serve/run-vllm.sh --no-enable-prefix-caching
    python bench/harness.py 8 2000 100 80 > results/prefix-off.json
    ./serve/run-vllm.sh
    python bench/harness.py 8 2000 100 80 > results/prefix-on.json
    The harness sends the same long prompt every time, which is exactly the case prefix caching helps.
  5. Plot all sweeps on one chart and tabulate the operating point for each experiment.
    bash
    python bench/analyse.py baseline exp-max-num-seqs exp-fp8-kv
    Check: plots/throughput_vs_tpot.png shows three curves.
Phase 7

Write it up and publish

A short, honest report someone else can reproduce, and a clean shutdown.

  1. Write REPORT.md with a fixed structure: question; setup (GPU, driver, image tag, model, precision, flags, workload); targets; results table and plot; for each experiment the bottleneck with evidence, the trade-off and the result; cost per million tokens at your best operating point; what you would test next.
    text
    ## Experiment 2: FP8 KV cache
    Bottleneck (baseline): KV cache full above c=32 (kv_cache_usage_perc ~1.0, preemptions rising).
    Change: --kv-cache-dtype fp8 (only change).
    Result: KV capacity roughly doubled; operating point moved from c=24 to c=40 at p99 TPOT < 50 ms.
    Trade-off: small answer differences on 2 of 10 spot-check prompts; needs a real eval before production.
    Next: repeat with 4,000-token prompts, where cache pressure is higher.
    The numbers above are a template, not expected results; write what you measured.
  2. Compute cost per million output tokens at your best operating point: hourly GPU price divided by output tokens per hour, then at a realistic utilisation such as 40%.
  3. Commit the scripts, raw results, plots and report, and push. Add the repository link to your CV or portfolio.
    bash
    git add serve bench results plots REPORT.md
    git commit -m "Inference benchmark lab: baseline + 3 controlled experiments"
    git push -u origin HEAD
  4. Tear everything down so the GPU stops costing money: stop the containers and terminate the cloud instance.
    bash
    docker rm -f vllm prom || true
    Check: The instance shows as terminated in your cloud console and no GPU hours are accruing.
Help

Troubleshooting

The container starts but reports no CUDA device
Check that docker run --rm --gpus all ubuntu nvidia-smi works; if not, reconfigure the NVIDIA Container Toolkit. If it does, the host driver may be too old for the image's CUDA version; use a newer driver image.
The engine exits with an out-of-memory error at startup
Lower --max-model-len, choose a smaller model, or lower --gpu-memory-utilization if other processes hold GPU memory (check nvidia-smi).
vllm bench serve fails with connection refused
The engine is still loading; wait until /health returns 200. Also confirm the --base-url and that port 8000 is published.
Results vary a lot between identical runs
Make sure warm-up requests ran, nothing else uses the GPU, and the run is long enough (raise --num-prompts). Repeat each point and report the spread.
--kv-cache-dtype fp8 is rejected
Not every GPU and model combination supports an FP8 cache. Record it as a finding and try a different variable, such as --max-num-batched-tokens.
Prometheus shows the target as DOWN
Prometheus runs with host networking and scrapes localhost:8000; confirm the engine is up and that the metrics path /metrics responds with curl.
Next

Where to go from here

Did a step fail or feel unclear? Tell me which one →