SP

Building InferenceX without trusting the first benchmark

inferencemeasurement

I built InferenceX one optimization at a time. The difficult part was deciding which measurements deserved to survive the experiment log.

InferenceX is a language model inference server written in PyTorch around a hand-written Qwen2.5-0.5B-Instruct forward pass. RMSNorm, rotary embeddings, SwiGLU, grouped-query attention and tied embeddings are implemented from the checkpoint up, with no dependency on Hugging Face modeling code. I used an RTX 4050 laptop GPU with 6 GB of memory under WSL2. A small model made it practical to test a change, inspect the result and try again without turning each experiment into an overnight job.

Every stage has an entry in the repository’s progress log with its mechanism, the exact command, the baseline and the result. Regressions are logged as prominently as wins. That log is now about 1,800 lines long. Most of it is not about making things faster. It records the times a benchmark reported a speedup that did not exist or called a real speedup a regression.

This article adapts my original benchmarking write-up and the two follow-up articles. The measurements come from those write-ups and the public repository. They have not been rerun for this site adaptation. [1]

The harness changed the first result

The first 37-token prompt took 333 ms to produce its first token. After warmup and a leading CUDA synchronization, the same no-cache model path took 39.9 ms. The difference came from initialization and timing boundaries. It was not a model optimization.

CUDA work is asynchronous. A timer started before earlier work finishes can charge that work to the operation being measured. The first forward pass also pays for initialization such as library handles and kernel loading. Those costs need their own accounting if the question is steady-state inference.

A short warmup still left the first timed run slower. I initially suspected cold matrix multiplication shapes. Warming the real shapes helped stability but did not explain the gap. Instrumenting the GPU showed memory clocks rising from 7001 MHz at idle to 8201 MHz under sustained load. Holding decode load for three seconds before timing addressed that effect.

Heat caused the opposite problem later. After about 20 minutes of tests, a path read 22.76 ms where an earlier result was around 18.6 ms. Repeating the measurement on an idle card removed the apparent regression. A fixed clock reading had not made the hardware state identical. These observations motivated alternating A/B arms within one process and keeping other timed jobs off the GPU.

The resulting single-sequence scoreboard is small. Each row uses the same 37-token prompt, 64 new tokens and greedy decoding. All figures are medians.

Reported single-sequence results by stage
StageChangeTime to first tokenInter-token latencyDecode
0No cache, harness fixed39.9 ms27.78 ms36.0 tok/s
1Naive KV cache33.8 ms23.05 ms43.4 tok/s
3lm_head on the last position only26.8 ms18.07 ms55.4 tok/s
7CUDA graphs for decoden/a8.65 ms115.7 tok/s

Most serving optimizations do not appear in that table. Batching, paging and grouped-query attention only matter with several requests in flight, so each has its own controlled harness. Those results follow in their own sections with their own baselines.

A workload that could show the cache

My first KV-cache comparison reported a slowdown. The baseline was a lucky sample, individual timings varied widely and the prompt was too short to expose much repeated work.

A KV cache saves the keys and values already computed for the prefix. The next decode step computes projections for the new token while attention still reads the cached context. The attention work grows with context length. Caching does not make the entire decode step constant in context.

Reported controlled prompt sweep from the original experiment
Prompt tokensNo cacheKV cacheRatio
3735.0 tok/s39.1 tok/s1.12x
51223.4 tok/s45.0 tok/s1.92x
20482.5 tok/s38.7 tok/s15.5x

The larger contexts made the benefit visible. Cached latency was relatively flat over this measured range because other costs dominated. That is an observation about this workload and hardware, not an asymptotic claim.

The summary statistic mattered too. With only 63 inter-token observations, the harness computed its p99 as sorted(itl)[int(.99 * 63)]. That is index 62, the maximum sample, reported under a percentile’s name. Outliers also pulled the mean enough to reverse the apparent direction of a change. On the stage 1 data, the mean said decode was 17% slower while the median said it was 17% faster. I used repeated-run medians for the headline comparisons while keeping the raw variation relevant to any latency claim.

Estimate the size of the win

The naive cache appended with torch.cat. Replacing repeated allocation and copying with a pre-allocated buffer looked like an obvious speed improvement. Across three prompt lengths, its measured ratios were 1.09x, 0.97x and 0.96x. There was no convincing throughput gain.

At about 2035 context tokens, the history copy accounted for 23.8 MiB per decode step. Streaming model weights accounted for roughly 940 MiB. Removing a copy that represented about 2% of traffic was unlikely to stand out against the observed noise. Pre-allocation remained useful later because CUDA graph replay needs stable buffer addresses. Its value was not the speedup I had first expected.

The vocabulary projection offered a larger target during prefill. Generation needed the last position’s logits, yet lm_head projected every position into a vocabulary of 151,936 entries. At 2035 tokens, the write-up estimated about 554 GFLOP for the full projection. Slicing before it reduced the work to the row generation actually needed. The predicted saving was 24.8 ms. The measured saving was 25.1 ms with 529 MiB less peak memory.

Those two results came from the same habit. Before each run I wrote down the mechanism, the expected traffic or FLOP change and the ratio that would follow. The lm_head prediction landed within a few percent. The pre-allocation prediction was wrong. The byte count explained why before I spent more time tuning it.

Check which kernel actually ran

Qwen2.5-0.5B uses grouped-query attention. Its 14 query heads share 2 key and value heads. My first implementation used repeat_interleave to copy each KV head seven times so the shapes matched. At long context that cost about 167 MiB of extra memory traffic per step.

PyTorch’s scaled_dot_product_attention accepts enable_gqa=True to handle mismatched head counts. I switched to it, confirmed with a quick probe that the call worked and closed the item. The later A/B result was slower, not faster.

Reported decode latency at batch 16
Contextrepeat_interleaveenable_gqa=True
322 tokens26.13 ms36.86 ms (0.71x)
2035 tokens62.27 ms145.11 ms (0.43x)

Passing keys and values with a different head count from the queries disqualified both fused attention kernels on the masked decode path. The call fell back to the MATH backend, which builds the full attention matrix from generic kernels. PyTorch emits a warning about this case. My probe had shown that the call executed. It never showed which kernel ran.

Forcing one backend at a time made the selection explicit. With a mask, FLASH rejected both layouts. EFFICIENT accepted the repeat_interleave layout but rejected enable_gqa. Only MATH accepted both.

The fix copies nothing. A decode step has exactly one query token, so the seven query heads that share a KV head can be relabeled as seven query positions of that head. That is a reshape, which PyTorch can express as a view:

o = F.scaled_dot_product_attention(
    q.reshape(B, nkv, rep, d), k, v, attn_mask=m)
return o.reshape(B, nh, 1, d)

The output was bit-exact against the reference path. At batch 16 with 2035 tokens of context, peak attention memory fell from 136.9 MiB to 24.9 MiB. Decode latency improved 2.22x over repeat_interleave. On the attention operation alone the folded path was 5.16x faster than the enable_gqa fallback.

Two batching experiments

Eight resident sequences reached 259.3 tok/s against 40.9 tok/s for serial service. I initially called the 6.34x ratio a continuous batching result. The workload generated 64 tokens per sequence with greedy decoding across eight requests. The harness used three rounds with alternating arm order. Equal-length requests arrived together into eight slots. It did not exercise replacement of completed requests.

Experiment ASerial service → resident sequences

Same eight requests
Batching can share each weight read.

Experiment BStatic groups → continuous admission

Ragged request lengths
Completed slots can accept waiting work.

Figure 1. The comparisons change different parts of service. Their ratios must retain their own baselines.

To test scheduling, I used 32 requests through eight slots with output lengths drawn from a lognormal distribution. The lengths ranged from 8 to 271 tokens with a median of 66. In the static arm, a finished sequence’s slot stayed reserved until its group completed. The continuous arm could refill it. Before running it, I predicted the static arm would average about 3.3 of 8 busy slots, giving continuous scheduling a 1.6x to 2.0x advantage.

Reported scheduling comparison with ragged outputs
ArmThroughputMean live batchSteps
Static110.7 tok/s3.29 of 8785
Continuous231.1 tok/s7.22 of 8369

Occupancy matched the prediction closely. The 2.09x ratio answers the scheduling question for that ragged workload. It does not multiply with the earlier 6.34x result. Equal output lengths remove the opportunity this scheduling comparison was designed to measure, so the same comparison would read 1.0x on the first workload.

The general lesson was about labels. A wrong number usually gets caught. A right number with the wrong name can survive review much longer, because nothing about the number itself looks suspicious.

Where the decode time went

A bandwidth estimate put batch-1 decode near a 6.5 ms floor for streaming weights. The measured step took 22 to 30 ms. Profiling a short-context step showed about 6.67 ms of GPU kernel work inside 22.80 ms of elapsed time, with 1023 launches per step. The gap pointed to work submission overhead.

Removing a per-step host synchronization helped by about 1.2x in the reported comparison. CUDA graphs addressed the repeated launch sequence itself. A graph records the kernels of one decode step once. Each replay then submits the whole sequence in a single driver call. The kernels are identical. Only the CPU submission cost and the handoffs between CPU and GPU go away.

A replay runs the recorded kernels against the same memory addresses with the same shapes. That required three changes. Persistent input buffers hold changing token IDs, positions and context lengths. The caller copies new values into them before each replay:

def replay(self, ids, positions, write_pos, ctx_lens):
    # copy_() into the captured tensors. Rebinding the attribute
    # would leave the graph replaying against stale inputs.
    self.ids.copy_(ids)
    self.positions.copy_(positions)
    ...

A fixed context bucket of 128, 256 or 512 key slots supplies a stable shape. A mask computed inside the graph from device data decides which slots are live, so one graph serves every step until a sequence outgrows its bucket. Sampling with argmax also runs inside the graph, so one decode step is one replay with no host round trip. The pre-allocated cache from the earlier stage made this possible because its buffers never move.

Reported graph harness results, all arms interleaved in one process
ConfigurationEager with syncEager, pipelinedGraph, pipelinedRatio
Batch 1, 37 tokens25.35 ms20.89 ms8.65 ms2.93x
Batch 1, 2022 tokens26.59 ms21.02 ms11.06 ms2.40x
Batch 16, 37 tokens25.32 ms21.21 ms9.80 ms2.58x
Batch 16, 2022 tokens28.40 ms24.47 ms18.90 ms1.50x

At batch 1 with a short prompt, that is 39.4 to 115.7 tok/s. At batch 16 it is 632 to 1,633 tok/s. These are graph-harness results rather than a general serving speedup. Batch-1 decode now sits at 8.65 ms against the 6.5 ms floor, so the step is no longer dominated by launches.

Two results contradicted my predictions. The synchronization win and the graph win did not stack. Once the step was graphed, removing the sync was worth only 1.03x to 1.05x, because one launch per step leaves almost no submission work to overlap. The total was 2.93x, not 1.2 times 2.4. Batch 16 also beat its predicted 1.5x to 2x at short context. Weight streaming dominates a short-context step whether it decodes one token or sixteen, so launch overhead stays the same share of the step. Only at long context does attention do enough real work to shrink the ratio to 1.50x.

The graph path also had traps that produced no error. Warmup before capture runs the step for real. A decode step writes KV. If capture happens mid-generation when a sequence crosses a bucket edge, warmup could overwrite live history and the output would be fluent but wrong. Loading the real upcoming write position before capture keeps warmup writes in the slot the next replay overwrites anyway. Python slices also clamp: a bucket wider than the cache truncated self.k[slots, :, :max_ctx] silently. The error surfaced much later as a broadcast mismatch inside attention. The graph runner now checks the bucket against cache capacity before capture.

The decode deep dive follows the synchronization experiment, graph timing arms and fused kernel in more detail. [2]

Decode had never run FlashAttention

With launch overhead reduced, attention was the next target. Forcing one backend at a time again showed which kernel each call site used. Prefill without a mask ran the flash kernel. Batched decode with a boolean mask ran the memory-efficient CUTLASS kernel. The same decode shapes with the mask removed were accepted by flash.

The FLASH backend refuses any non-null mask. Batched decode needs one because each row has a different number of live key slots. The mask had ruled out FlashAttention for decode since batching landed. The controlled check with the mask deleted showed that the mask alone was responsible.

Before writing a kernel, I estimated the most a perfect one could deliver by profiling a real paged decode step and asking how fast it would be if attention took zero time.

Reported GPU time per step and the ceiling if attention were free
CaseGPU time nowIf attention were freeMaximum speedup
Batch 1, context 1767.57 ms7.25 ms1.04x
Batch 1, context 21769.73 ms7.20 ms1.35x
Batch 16, context 1768.54 ms7.97 ms1.07x
Batch 16, context 217614.71 ms8.72 ms1.69x

At short context the matrix multiplications take about 6 ms in every row, so attention is worth almost nothing. At long context with batch 16 the ceiling is 1.69x. More than half of that attention cost was not attention math. It was gather() copying paged keys and values into a contiguous tensor, writing it to memory and reading it straight back.

The mask and the gather had the same cause. Context lengths and the block table were expressed as tensor shapes when they should have been kernel arguments. A fused paged Triton kernel takes the block table and context lengths directly. It is about 90 lines in engine/paged_attn.py, with one program per sequence and KV head looping over context in tiles of 64 positions. Each tile looks up which physical block holds each position and loads keys and values straight from the pool. Liveness becomes a predicate that assigns negative infinity to dead slots instead of adding a mask tensor. An online softmax rescales the running sum as each tile arrives, so neither the score matrix nor a gathered copy is ever written to memory. The seven query heads that share a KV head are rows of one tile, so each key and value block is loaded once and used seven times.

Reported fused kernel results against the ceiling written down beforehand
CaseCeiling (GPU)Median wall-clock speedup
Batch 1, context 371.04x1.01x
Batch 1, context 20351.35x1.14x
Batch 16, context 371.07x1.05x
Batch 16, context 20351.69x1.21x

On GPU time alone the kernel reached roughly 1.34x to 1.4x in the long-context batch-16 case with the gather removed entirely. In wall time it lost about a third of that, because these comparisons ran on the eager path where a step is about 22 ms of wall time for 9 to 13 ms of GPU work. The kernel removes 144 of about 1,126 launches, so its GPU saving is diluted by idle time it does not touch. 1.21x is the wall-clock number and about 1.4x is the GPU-time number. They are different claims.

The first profiler result had suggested 3.38x. An unchanged GEMM workload appeared to get dramatically faster between arms, which prompted a new interleaved profile. The result did not survive that check.

Memory that was not where I counted it

A batch-16 prefill completed with a reported peak of 10.9 GiB on a 6 GiB card. Under WSL2, the CUDA allocator does not fail when it runs out of device memory. It can spill to host memory and continue at PCIe speed. A run that does not raise an out-of-memory error has not shown that it fit.

Sizing the paged KV pool exposed the same gap. The CUDA context and cuBLAS workspaces took 1,096 MiB, about 18% of the card. None of it appears in torch.cuda.max_memory_allocated(). Budgeting from PyTorch’s number alone would have handed out about 5,700 KV blocks that did not exist. Pool sizing now starts from total device memory, subtracts measured non-PyTorch memory and reserves room for CUDA graph pools. Each captured graph kept about 17 MiB of private intermediates in my measurements. That is small at nine graphs and significant at the thirty or so batch buckets a larger server might capture.

The pool replaced per-slot reservations with fixed-size blocks and a block table per sequence. It raised token capacity from 32,768 to 272,768 on the same card. That is a capacity result. More resident tokens can enable more concurrency, but the ratio is not a throughput measurement.

The allocator had a quieter failure. Its ensure() call guarantees a sequence enough blocks for its next tokens. If a sequence needed six blocks and only four were free, the tempting implementation took four and then raised an out-of-memory error. The caller would then preempt the sequence or refuse admission. Nothing would ever free those four blocks. The pool would shrink a little each time memory ran tight. ensure() is now atomic: it takes every block it needs or none. Allocator unit tests in pure Python check round trips, atomic failure and boundary crossings in milliseconds on every push.

The scheduler had a related livelock. Admitting a sequence the pool cannot hold produces admit, preempt and re-admit forever with no progress. It now refuses admission while blocks are short unless nothing else is running, in which case it raises a clear OutOfKVMemory error.

Checks that exposed silent failures

Timing was only useful after the compared paths agreed on the result. Several failures returned plausible output or merely ran slower. A cache object was passed down but ignored by a decoder layer. An attention API call accepted a configuration but selected a slower backend. An additive mask did not stop non-finite values in unwritten cache memory from contaminating attention. That last case produced a string of exclamation marks instead of text, because torch.empty left garbage where a masked read could still touch it.

The checks needed to target those mechanisms. Prompt sweeps exposed repeated computation. Forcing each attention backend made unsupported fused paths explicit. Zero-initialized pools removed non-finite padding. Ragged lengths and a graph bucket crossing checked that replay used current positions without overwriting live history. Shuffled block tables kept a broken paged address calculation from passing by coincidence. A block size of 1 forced every position across a block boundary. The A/B harnesses compare generated tokens before they report any timing, so a silent divergence cannot appear as a performance win.

I describe those cases in the silent GPU failures article. The useful commonality is the check that made each failure observable. [3]

Rules I kept

Each of these was earned by being wrong first.

What is implemented

The public README distinguishes tested experimental components from the default serving path. CUDA graph decode is implemented but not wired into Engine. The fused Triton kernel is selected through an explicit mode switch. The paged-cache capacity result above is reported as capacity, not as an 8.32x throughput claim. [4]

The natural next step is wiring the graphed paged path into the engine so the fused kernel runs where launch overhead no longer dilutes it. That combination should be measured as its own comparison, with its own prediction, rather than estimated by multiplying the ratios above.

The habit I would keep is writing the prediction before the run. A result needs its mechanism, environment, workload, command and baseline. A failed prediction then has somewhere precise to send the next experiment.

Sources and deeper reading

  1. Original InferenceX benchmarking article, Shreyansh Pathak. Source of the experiment narrative and reported measurements.
  2. Decode and CUDA graph deep dive, Shreyansh Pathak. Source of the graph, backend and fused kernel measurements.
  3. Silent GPU failures, Shreyansh Pathak. Source of the GQA, memory and allocator cases.
  4. InferenceX repository: README, progress log, batching harness and graph harness. Reviewed 22 October 2026. Links track the current branch.