# SGLang LLM Inference Serving Benchmark ## Overview Public edition with independent Git history. Personal filesystem provenance is sanitized; original experiment history remains private. [Public provenance](docs/public_provenance.md) maps original artifact hashes to this derived edition. Measurement values and anomalies are preserved. A controlled single-GPU serving study: deploy **Qwen2.5-0.5B-Instruct with SGLang on an NVIDIA RTX 4070**, then measure how concurrency, prompt length, output length, and verified prefix reuse affect request latency and aggregate throughput. ## Key Results - **Concurrency:** C8 reached 1,548 output tok/s versus 254 at C1, while TTFT rose from 17.8 to 68.0 ms. - **Prompt length:** 128→2048 input tokens increased median run-level TTFT from 10.5 to 45.1 ms. - **Generation length:** 32→256 output tokens increased E2E from 122 to 889 ms; new-session TTFT stayed near 16.5–16.6 ms. - **Prefix reuse:** verified 1,024-token reuse reduced paired TTFT by 57.8% using the median of three block medians. ![Request-latency cost across concurrency](figures/concurrency_latency.png) These are controlled single-GPU results. The length studies retain a reused cross-session baseline; the cache study retains an unexplained 4.19-second warm request. [Full results and methodology](#benchmark-methodology) · [Resume and interview assets](docs/portfolio.md) The engineering work includes a native streaming client, exact token-ID workloads, cache isolation, incremental SSE parsing, failure-aware validation, request-level evidence, and an offline analysis pipeline. The project demonstrates LLM serving, performance measurement, and systems reasoning relevant to ML engineering and AI infrastructure work. Its scope is a local, finite-workload experiment. ## Why This Project Serving performance is more than tokens per second. A configuration can complete more work while delaying each user's first output. Separating TTFT, decode pace, and full request time makes that tradeoff visible. Prefix-cache counters add a second question: did reuse happen, and did it actually reduce latency? ## Architecture ```mermaid flowchart TD A[Client Workload: exact token IDs] --> B[HTTP / Streaming API] subgraph Runtime[Conceptual SGLang runtime stages] B --> C[SGLang Runtime] C --> D[Scheduler / Continuous Batching] D --> E[Prefill] E --> F[KV / Radix Cache] F --> G[Decode] end G --> H[Streaming Output] H --> I[Request-Level Evidence] I --> J[Aggregation / Analysis] ``` Internal stages are a conceptual architecture, not a measured execution trace. Measurements are primarily client-observed, supplemented by exposed token/cache metadata. This study does not infer exact scheduling decisions or kernel times. ## Environment | Component | Validated setup | |---|---| | GPU | NVIDIA RTX 4070, 12 GB VRAM | | Host | Windows + WSL2, Ubuntu 26.04 | | Python | 3.12 (recorded runtime: 3.12.14) | | Serving runtime | SGLang 0.5.19 | | Model | Qwen/Qwen2.5-0.5B-Instruct | | Model revision | `7ae557604adf67be50417f59c2c2f167def9a775` | | API | Local HTTP, native `/generate`, streaming SSE, `input_ids` | | Cache | Radix cache enabled; explicit idle flushes | | Generation | Greedy deterministic settings, seed 42, forced output length | Recorded launch commands and effective settings are indexed in [results provenance](docs/results_index.md). Dependency files describe the client and plotting requirements; they are not a complete portable GPU environment lock. ## Benchmark Methodology Deterministic local text is tokenized into exact input-ID sequences without a chat template. `ignore_eos=true` forces the requested completion length. Server token counts must match the submitted contract. The streaming parser handles arbitrary transport splits and does not mistake network chunks for tokens. Each scaling configuration uses **40 measured requests and three repetitions**. Eight excluded runtime warmups precede each run; an acknowledged cache flush and distinct first-token IDs enforce zero reuse. A finite closed-loop client keeps at most C requests active. Waiting for a client concurrency slot is outside request timing. Metadata, warmups, cache resets, and serialization are outside scaling throughput duration. Failures remain in evidence; there are no automatic retries. Scaling tables report **medians of three run-level means or throughputs**. Figures retain all three run points; connecting lines join medians without smoothing. Ranges remain available in [analysis/final_summary.json](analysis/final_summary.json). They are observed min–max ranges, not confidence intervals. Prefix caching uses **10 matched pairs × 3 blocks**. A one-token primer and a 64-token target share 1024 IDs, then diverge at the first of 32 suffix IDs. Cold and warm conditions send the exact same B body. Each condition starts with its own verified flush; warm B waits for A to complete. Condition order is balanced. Primers and runtime warmups are excluded from primary latency summaries. No throughput estimate is made for this interleaved setup/measurement design. No measurements were rerun for presentation, and no anomalous samples were removed. See [methodology](docs/methodology.md) for validation boundaries and limitations. ## Metrics Let start be submission, first/last be observed cumulative-output-count growth, terminal be the end-of-stream signal, and N be completed output tokens. | Metric | Definition | |---|---| | TTFT | first − start | | TPOT | (last − first) / (N − 1); null for N = 1 | | Client E2E | terminal − start | | Output throughput | successful output tokens / measured workload duration | | Request throughput | successful requests / measured workload duration | These are serving-client measurements, not isolated GPU execution times. TPOT summarizes the observed output interval; it is not a per-token kernel trace. ## Experiment 1 — Concurrency Scaling 512 input tokens, 64 output tokens, C1/C4/C8, zero cache hits. | Concurrency | TTFT ms | TPOT ms/token | E2E ms | Output tok/s | Requests/s | | --- | --- | --- | --- | --- | --- | | 1 | 17.817 | 3.709 | 251.492 | 254.439 | 3.976 | | 4 | 42.171 | 3.899 | 287.845 | 888.743 | 13.887 | | 8 | 68.013 | 4.207 | 330.355 | 1548.431 | 24.194 | ![Concurrency versus output throughput](figures/concurrency_throughput.png) ![Concurrency versus TTFT and E2E](figures/concurrency_latency.png) Output throughput increased **3.49× from C1 to C4** and **1.74× from C4 to C8**. TTFT and E2E rose, while TPOT increased more modestly. Higher aggregate throughput traded against request latency. Marginal throughput gain per additional concurrency slot declined by C8. This does not establish GPU saturation or exact scheduler behavior. ## Experiment 2 — Prompt-Length Scaling 128/512/1024/2048 input tokens, 64 output tokens, concurrency 1, zero cache hits. | Input tokens | TTFT ms | | --- | --- | | 128 | 10.488 | | 512 | 17.817 | | 1024 | 26.051 | | 2048 | 45.114 | ![Prompt length versus TTFT](figures/prompt_ttft.png) A 16× increase in input length corresponded to **4.30× TTFT**. Longer prompts require more prefill work, but TTFT also includes request handling, scheduling, delivery, and runtime costs. The measurements do not establish quadratic scaling. **The 512-token point reuses Step 4 C1 evidence from another server session.** Behavioral compatibility was verified; that baseline showed greater variation. Orange diamonds identify it. Nearly coincident run markers remain plotted. ## Experiment 3 — Output-Length Scaling 512 input tokens, 32/64/128/256 forced output tokens, concurrency 1. | Output tokens | TTFT ms | TPOT ms/token | E2E ms | Output tok/s | | --- | --- | --- | --- | --- | | 32 | 16.634 | 3.411 | 122.399 | 261.351 | | 64 | 17.817 | 3.709 | 251.492 | 254.439 | | 128 | 16.547 | 3.413 | 450.042 | 284.391 | | 256 | 16.569 | 3.421 | 888.858 | 287.995 | ![Output length versus E2E](figures/output_e2e.png) ![Output length versus TTFT share](figures/output_ttft_share.png) New-session TTFT remained around 16.5–16.6 ms and TPOT around 3.41–3.42 ms/token. E2E and the decode window grew with generated length; request throughput fell. Output-token throughput increased somewhat, consistent with amortizing fixed request cost over more generated tokens. TTFT's share of E2E fell from **13.6% at O32 to 1.86% at O256**. The share is mean(TTFT)/mean(E2E) within each run, then summarized across runs. **O64 reuses the same cross-session Step 4 baseline.** Its variation is retained; no monotonic claim is forced through that point. ## Experiment 4 — Prefix Cache 1056 input tokens, 64 output tokens, concurrency 1, identical cold/warm B targets. All 30 cold targets reported zero cached tokens; all 30 warm targets reported 1024 cached tokens. TTFT improved in **29/30 pairs**, E2E in **25/30**. | Paired effect | Median [min–max] of block medians | | --- | --- | | TTFT reduction | 16.997 [16.795–28.781] ms | | TTFT reduction | 57.84 [56.98–66.61] % | | E2E reduction | 17.883 [17.044–28.708] ms | | E2E reduction | 7.10 [6.86–7.49] % | ![All cold/warm TTFT pairs, including the outlier](figures/prefix_paired_ttft.png) Verified reuse reduced median paired TTFT under this workload. The smaller E2E improvement reflects the generation that still follows first output; TPOT was broadly similar within each block. Primary effects are paired differences within blocks, then the median [min–max] of the three block medians, not pooled experiments. **One first-use warm-cache request experienced a ~4.19 s TTFT anomaly (4186.767 ms) despite a verified 1,024-token cache hit. The observation was retained and its cause was not established.** The log-scale plot shows it in full. A cache hit is not a guarantee of latency improvement. The full-input runtime warmups did not exercise this cached path, which limits a steady-state interpretation. ## Historical Experiment Recovery [results/historical/](results/historical/) preserves earlier exploratory aggregate records byte-for-byte. Prompt/output lengths varied, request counts differed, and request-level evidence was unavailable. That work motivated exact token contracts, repeated controlled runs, and explicit cache verification. Historical points never enter the controlled curves. Unsaved historical cache observations are motivation only, not reconstructed measurement evidence. ## Reproduction From the repository root, saved-data analysis needs no GPU or server: ```bash python -B analyze.py python -B plot_results.py python -B render_readme.py ``` Plotting requires `requirements-analysis.txt`; analysis itself uses the standard library. [Reproduction instructions](docs/reproduction.md) distinguish offline regeneration from future live experiments, list the actual benchmark modes, and explain the dedicated-server/provenance prerequisites. Reproducing the numeric results on different hardware or sessions is not guaranteed. ## Repository Structure ```text benchmark.py Native streaming client and scaling study modes prefix_cache.py Independently reset matched-pair runner prompts.py Deterministic exact token-ID workloads verify_prefix_cache.py Independent Step 7 evidence verification analyze.py Offline validation and final summaries analysis/ Evidence loader and derived data with source hashes plot_results.py Six PNG figures from validated analysis render_readme.py This README, with data-derived result tables figures/ PNGs and provenance manifest configs/ Saved manifests and server configurations results/ Controlled studies, raw runs, historical aggregates docs/ Methodology, experiment reports, reproduction, audit tests/ Client, contract, analysis, and publication checks ``` ## Testing **66 tests pass** in the recorded benchmark environment: ```bash python -B -m unittest discover -s tests -v ``` Coverage includes SSE framing, timing/count validation, concurrency dispatch, baseline compatibility, pair identity, failed reset/primer handling, missing evidence, outlier preservation, figure hashes, README numbers, and local links. Tests do not send inference traffic. Tokenizer tests require the pinned cached model tokenizer and client dependencies. Analysis-only tests can be selected with `python -B -m unittest discover -s tests -p 'test_analysis*.py'`. ## Limitations - One RTX 4070 and a 0.5B model in local WSL2; no distributed serving or production network. - Finite closed-loop workloads; no production arrival process, cache-hit distribution, or capacity claim. - Client-observed timing; no kernel-level profiling, GPU utilization attribution, or scheduler reconstruction. - Only three repetitions/blocks; min–max ranges are descriptive, not statistical confidence bounds. - Cross-session baseline reuse at 512/O64, despite verified behavioral compatibility. - An unexplained first-use cache anomaly and higher decode latency in the third cache block. - Synthetic forced-length generation measures serving behavior, not response quality. - The recorded GPU software stack is not a turnkey cross-platform installation lock. ## Key Lessons Throughput and request latency answer different questions. Prefill cost is most visible in TTFT; longer generations shift the latency budget toward decode. Verified prefix reuse can reduce first-output time while leaving decode pace largely unchanged, but cache counters alone do not establish performance benefit. Preserving exact workloads, individual runs, and anomalies makes those distinctions auditable rather than anecdotal.