← Inference From First Principles

Prefill/Decode Disaggregation

A real prefill process and a real decode process joined by a socket, exact to the token and worse than one engine on a single shared GPU; the simulator that explains why, and what it says about the hardware, the workload and the prefill-to-decode ratio that would make the split pay.

At an offered rate of six requests per second, the co-located GPT-2 engine on this machine’s single GPU met both latency objectives for 184 of 230 requests. A second implementation separated prefill and decode into two processes on that same GPU, sending each prompt’s KV state over a loopback TCP socket. It met both objectives for 75 of the same 230 offered requests. Both implementations produced the same greedy token sequences in the separately recorded correctness comparison. In this single-GPU live workload, the split was worse—not because its outputs changed, but because it paid for an extra hand-off without gaining an independent accelerator.

That result is not a refutation of prefill/decode disaggregation. The independent-device simulator, calibrated with stage costs measured on this machine, predicts 217 of those 230 requests would meet the objectives if prefill and decode had separate, non-contending devices. That is a modelled counterfactual, not a measured two-GPU result. The comparison is particularly instructive because the live alternatives share one GPU whereas the counterfactual changes the resource allocation. The chapter later makes the fairer two-device comparison: two co-located replicas versus one dedicated prefill worker and one dedicated decode worker. The real question is when reduced interference exceeds the added KV export, transmission, import and scheduling costs.

The chapter keeps three evidence levels separate. First, a real two-process KV hand-off is implemented and checked against single-engine greedy outputs. Second, the co-located and split implementations are compared on the same arrival traces while sharing one RTX 2060; their measured stage costs, queueing and variability remain visible. Third, a discrete-event simulator uses fitted costs to explore independent devices, different P:D ratios and hypothetical interconnects. The last group is useful for formulating a hardware experiment, but no modelled outcome is presented as a multi-GPU measurement. The strongest conclusion is conditional: disaggregation is worth testing when the extra resources and phase isolation are worth more than the hand-off.

The question

A co-located batched engine interleaves prompt prefill with decode iterations. In the Chapter 27 design, an iteration that admits a new prompt can also advance existing sequences, so those sequences must wait through the additional prefill work. The earlier experiment reported a 56–73 ms prefill-related stall against an approximately 11 ms decode step. This is interference within a step, not a claim that every co-located scheduler must process full prefills without chunking: Chapter 15 already examined scheduling choices that change how much prefill is included in an iteration. Disaggregation changes the resource boundary by putting the two phases on separate workers, with a KV transfer between them.

Four questions organise the experiment. Does export, transport and import preserve the generated greedy tokens? Which parts of a hand-off cost time, and at what point does the caller see that cost? On one shared GPU, how do a batched co-located engine and a two-process split compare on exactly the same offered traffic? Finally, in a separate-device simulation, how do phase demand, the interconnect and the number of workers in each phase affect attainment? A positive answer to the last question is a testable prediction, not validation of the corresponding real hardware.

The two latency objectives, chosen for this GPT-2 laboratory, are time to first token (TTFT) no greater than 250 ms and mean time per output token after the first (TPOT) no greater than 20 ms. A request is good only if it completes and meets both objectives; attainment is good requests divided by all offered requests. The chapter’s simulated capacity is the largest tested arrival rate whose mean attainment over two seeded traces reaches at least 90%. DistServe uses goodput for the achieved rate of requests satisfying their latency objectives; attainment, good requests per second at a fixed offered load, and the maximum load at a 90% target are related but are not the same quantity. The chapter reports them distinctly.

Where this sits

Chapter 9 separated prefill from decode and defined TTFT, TPOT and goodput. Chapters 14 and 15 built the paged KV cache and iteration-level batching; Chapter 27 exposed a step-driven engine and checked block release on cancellation. Chapter 24 established how attention architecture sets the KV bytes per token. Chapter 26 supplied admission-control vocabulary, which matters because disaggregated serving introduces at least a prefill queue, a transfer queue and decode admission. Chapter 28 measured a host-device copy path and introduced an alpha–beta link model. Here those building blocks meet, but the Chapter 29 two-process harness is not a production service: it does not implement the Chapter 26 deadline gate across both phases, retransmission after a failed hand-off, or a distributed KV-cache allocator.

Chapter 30 takes up what happens when one of several workers fails, which a design with two kinds of worker and a connection between them makes more pressing.

Where the starter was wrong

The starter compared a co-located total latency of 106 with a disaggregated total of 38 plus a transfer cost of 8. Its co-located baseline completed one request at a time; the split baseline overlapped stages. That conflated benefits from ordinary batching and overlap with benefits from separating the phases. It also used a fixed transfer cost regardless of prompt length. This revision holds the traffic and batching idea constant wherever it can and prices the actual KV bytes. The starter’s toy script and tests remain in the repository for historical comparison and provide none of the measurements in this chapter. Splitwise’s hardware-heterogeneity proposal and DistServe’s separate-GPU objective are related research claims, not properties verified by running this laboratory on one GPU.

Why the phases interfere, and what splitting moves

Why prefill and decode interfere

For a co-located step, the time to advance an existing sequence can include the cost of prefill admitted in that step. In the local mixed-step measurement, one 900-token prompt joining eight active decoders produced a 76.3 ms step. A decode-only step for eight sequences took roughly 12–18 ms over the measured context range of 64–900 tokens. This is direct evidence of interference in this unchunked step loop. The difference is a useful indication of extra delay, but it is not an isolated causal estimate of prefill compute: step composition, cache state and the machine’s noise also matter. A co-located scheduler using chunked prefill or priority rules could change the result and is an important missing comparison.

Disaggregation separates a prefill worker, which evaluates the prompt and produces its first token and prompt KV state, from a decode worker, which installs that state and generates subsequent tokens. In the laboratory, the prefill worker has completed an export to pinned host memory before it reports the first token to the parent; the socket send happens afterwards, and the decoder imports the state before producing token two. Thus the socket transfer and installation chiefly affect the gap after token one, but KV export can already increase the measured TTFT. The hand-off removes same-step prefill interference only if the workers have independent execution resources; two processes sharing one GPU can still contend for that device.

The logical KV payload for a dense, full-context cache without compression, sharing or padding is proportional to prompt length:

bytes = 2 × layers × KV heads × head dimension × bytes per value × tokens

For GPT-2 small in float32, each prompt position contributes \(2 \times 12 \times 12 \times 64 \times 4 = 73{,}728\) bytes of keys and values. Therefore 64 positions produce 4,718,592 bytes (4.72 MB decimal, 4.50 MiB), and 900 positions produce 66,355,200 bytes (66.36 MB, 63.28 MiB). The table later uses decimal MB; MiB and MB should not be interchanged. This is the logical tensor payload, not a complete transfer-protocol cost or a bound on allocated memory. Page rounding, temporary gather buffers, pinned staging buffers and the two model copies add other memory. Three consequences follow.

First, under a throughput-dominated linear approximation, the payload and the dominant prefill work both grow with prompt length. Let \(k\) be KV bytes per prompt token, \(r\) the sustained prefill rate in prompt tokens/s and \(\beta\) the effective transfer bandwidth. The approximate ratio of bandwidth-only transfer time to prefill time is \(rk/\beta\). It is independent of prompt length only within that approximation. The real fitted costs include fixed prefill and export intercepts, the link has latency, attention work can grow faster than linearly with sequence length, and queues introduce further delay. For a short prompt the fixed terms can dominate; for long prompts a single \(r\) need not describe all lengths.

bytes of KV per second  =  r × (bytes per token)
required link bandwidth =  r × (bytes per token)
transfer time / prefill time  =  r × (bytes per token) / β     (latency aside)

If \(rk > \beta\), a single such link cannot sustainably carry the KV output of a prefill worker running at the assumed rate without additional buffering or backpressure. If \(rk\) is much smaller than \(\beta\), transmission bandwidth is a smaller component of the hand-off, but this does not guarantee a particular TTFT, TPOT or overall attainment. Export, installation, link latency, competing traffic and queueing can still matter. The ratio above is a sizing screen, not a substitute for an end-to-end serving measurement.

Second, the ratio depends on the model and attention layout, not just on how many tokens are generated. DistServe reports an OPT-66B example with approximately 1.13 GB of KV state for a 512-token prompt, or roughly 2.2 MB per prompt token, and an aggregate transfer requirement of approximately 11.3 GB/s at ten such requests per second. Those are the authors’ assumptions and figures, not local measurements. Compared with GPT-2’s 73.7 kB of KV per position, the payload per token is about thirty times larger, but the compute associated with prefill also differs greatly; payload alone does not determine whether a hand-off is worthwhile.

Third, grouped-query and multi-query attention can reduce KV payload independently of the number of query heads: the formula uses KV heads, not query heads. Larger dense models can also do much more prefill arithmetic per stored KV byte. Neither observation proves that every larger model has a cheaper hand-off—layer count, head dimensions, attention FLOPs, context length, bandwidth and achieved prefill efficiency all matter. The eight-configuration table later is an illustrative roofline calculation with a fixed assumed efficiency, not eight implementations of the split.

Building the split

Building the split: stages and hand-off

The laboratory implementation is examples/ch29/disagg_lab.py, extending the Chapter 27 paged, step-driven GPT-2 engine with export and import methods. It uses the same model family and greedy decoding in the correctness run; it does not implement cross-architecture cache conversion, speculative-state transfer or a version-negotiated KV protocol.

prefill_export(prompt_ids, buf) evaluates a prompt through the paged cache, selects the first greedy token, and gathers each layer’s prompt keys and values into a pinned host tensor with logical layout [token, layer, K/V, head, dim]. It synchronises CUDA work before recording prefill and export timings, frees the temporary prompt block table and returns the first token and the two times. Export time includes block gathering and device-to-host copying, not just raw PCIe transfer. The first-token message is sent to the parent only after this method returns; consequently, this implementation’s observed TTFT includes export work.

submit_prefilled(prompt_len, first_token, kv, max_new, ...) creates a pending decode-side import. On a step it can reserve a batch slot and the request’s future KV blocks, write the received cache layer by layer, and continue from the first token. Pending imports retain FIFO order when resources are unavailable. The function requires max_new >= 2; a request needing only one token is completed on the prefill side and does not send its KV state. The CPU tests cover a waiting import, cancellation before installation and block accounting. This is not yet a transactional distributed ownership protocol: there is no explicit version/shape handshake, checksum, durable transfer acknowledgment, retry or crash recovery across workers. Those omissions become central in Chapter 30.

The live prefill and decode workers are separate operating-system processes connected by loopback TCP. A transfer consists of a four-byte network-order JSON-header length, a JSON header holding the request id, prompt length, first token, maximum new tokens and byte count, and then a raw tensor payload. Both workers implicitly assume compatible GPT-2 layer, head, dtype and layout conventions; the wire header does not certify or negotiate them. The prefill worker rotates through pinned host buffers and sends a buffer from a separate thread while starting later prefills. sendall completing means the sender submitted the bytes to the socket path; it is not an application-level acknowledgment that the decoder installed them. A production protocol needs bounded header and payload validation, manifest identity, checksums or other integrity protection, explicit buffer ownership, cancellation and error handling. The parent process collects token events from both workers.

For the measured live comparison, the co-located alternative is the Chapter 27-style batched engine in one process, driven by the same scheduled arrivals. This controls for the basic presence of batching, but not every resource variable: the co-located engine uses 900 KV blocks while each split worker uses 700, and the split runs maintain an extra full model copy and transfer buffers on the shared GPU. Both paths are real applications on one device; the independent-device cases appear only in the simulator.

What the stages cost

These values are the median of repeated local measurements of stage costs with the engine otherwise idle, using GPT-2 float32 on the shared RTX 2060. The prefill time is the forward pass, export includes page gathering plus copy to pinned host memory, and install includes writing the received KV to the paged GPU cache. Values are decimal MB for logical KV payload and milliseconds for the measured operations; they do not include scheduling delay or a full network round trip.

prompt tokens prefill export install KV size
16 17.6 ms 1.5 ms 1.2 ms 1.2 MB
64 18.8 ms 3.2 ms 1.6 ms 4.7 MB
256 17.8 ms 7.2 ms 4.0 ms 18.9 MB
512 31.5 ms 12.1 ms 5.2 ms 37.7 MB
1,000 76.0 ms 22.5 ms 9.2 ms 73.7 MB

Measured prefill stayed around 17–19 ms for prompts of 16–256 tokens and then grew markedly. A least-squares line across the measured lengths gives about 10.1 ms + 57.8 µs × prompt tokens, but it misses both ends: about 13.8 ms predicted versus 18.8 ms observed at 64 tokens, and about 67.9 versus 76.0 ms at 1,000. That residual matters because the simulator uses this line for individual requests. Similarly, export is fitted as roughly 1.76 ms + 20.1 µs per prompt token, and install as 1.24 ms + 8.0 µs per token. These are useful interpolation inputs, not universal linear scaling laws, and the run-to-run device contention is not represented in them.

The 1,000-token KV payload is 73.728 MB (decimal). A contiguous device-to-host copy of that size took 5.6 ms (about 13.1 GB/s), and the reverse copy took 5.9 ms. The actual paged-cache export took 22.5 ms, roughly four times the raw copy because the implementation gathers cache blocks layer by layer and synchronises the resulting work. Thus using only a theoretical link bandwidth substantially understates the end-to-end hand-off in this laboratory. A more direct block-aware export or a different cache layout is a concrete optimisation to benchmark; its benefit has not been measured here.

In the local socket microbenchmark, 64 KiB took 32 µs median, 1 MiB 181 µs (about 5.8 GB/s), 8 MiB 2.5 ms (about 3.4 GB/s), 32 MiB 10.2 ms (about 3.3 GB/s), and 74 MiB 29.1 ms (about 2.7 GB/s). This benchmark waits for the receiver to consume the bytes and acknowledge receipt; it is not the same metric as the live prefill worker’s sendall duration. The fitted line implies about 2.68 GB/s and a negative intercept near −0.6 ms. A negative fitted intercept is not physically meaningful latency, so the simulator clamps that link latency to zero. The estimates describe loopback on this Windows host; they cannot be carried across unchanged to RDMA, NVLink, PCIe peer access or a real network.

For a 900-token prompt, plugging length into the fitted curves gives roughly 62 ms prefill, 20 ms export, 25 ms transfer and 8 ms install. This decomposes a modelled hand-off into about 53 ms beyond prefill, before queueing and other overheads; it is not the measured end-to-end time for an individual live request. The sequence’s first token is selected during prefill, but the live first-token event is emitted only after export, so export can worsen TTFT. The socket transfer and decode-side install happen after that event and can greatly lengthen the gap to token two, which contributes to TPOT. Claiming that the whole hand-off is invisible to TTFT would contradict the code’s timestamps.

Decode-step cost is modelled separately because the Chapter 14 paged gather pads shorter sequences to the longest current context. Measurements covered batches of 1, 4, 8 and 16 and contexts of 64, 256, 512 and 900 tokens: about 8.4 ms for one 64-token sequence, 11.2 ms for 16 at 64, 8.9 ms for one at 900, and 29.6 ms for 16 at 900. Least squares gives \(T_{step} \approx 9.48\text{ ms} + 0.036\text{ ms}\,B + 0.00123\text{ ms}\,B C\), with batch \(B\) and longest context \(C\); at \(B=16,C=900\) it predicts approximately 27.8 ms. The grid is noisy—for example, batch 4 at context 64 was slower than batch 8—and this fit captures neither transitions between kernels nor resource contention between processes. The simulator charges an entire batch for its longest context; the tests cover this policy, but not the performance of every heterogeneous real batch.

Is the moved state exact?

The hand-off: KV transfer between workers

The small CPU test constructs two tiny GPT-2 engines, exports KV state from one and imports it into the other, compares the transferred cache values with the source, and checks the resulting token sequence against unsplit generation. This demonstrates value-preserving transfer for that tensor layout and test input, not a general equivalence theorem for every model, dtype, attention variant or conversion format.

The real-size exactness run sent 26 requests through both live designs: 64- and 900-token prompts, 32- and 64-token greedy completions, and a seeded arrival process nominally at four requests per second for eight seconds. All 26/26 split token-id sequences matched their co-located counterparts; neither run timed out. This is strong implementation evidence for GPT-2 float32 at the tested lengths, not a claim about bitwise-identical hidden states, stochastic sampling, half precision or other attention layouts. In particular, the GPU exactness result is a token comparison; full imported-cache equality was checked in the smaller CPU test.

One GPU, two designs

The offered traffic is a seeded, open-loop Poisson trace lasting 40 seconds: approximately 70% chat requests (64 prompt tokens, 64 generated) and 30% retrieval-style requests (900 prompt tokens, 32 generated). For each rate, both live designs receive the same scheduled arrivals and lengths. The generator supplies synthetic token-id prompts rather than a corpus of human requests. The co-located process has 900 cache blocks; the split has 700 blocks in each process and a configurable ring of pinned host buffers. The decode batch limit is 16. A different block allocation, model residency, scheduler or prompt distribution could change the comparison, so these are the tested conditions rather than a general serving-capacity estimate.

rate design requests good attainment TTFT p50 / p99 TPOT p50 / p99
3/s one engine 120 118 98% 25 / 122 ms 12.5 / 20.4 ms
3/s split 120 104 87% 51 / 301 ms 13.7 / 32.4 ms
4.5/s one engine 171 159 93% 29 / 110 ms 14.3 / 24.7 ms
4.5/s split 171 129 75% 88 / 371 ms 15.3 / 37.6 ms
6/s one engine 230 184 80% 29 / 136 ms 15.4 / 29.1 ms
6/s split 230 75 33% 115 / 546 ms 25.8 / 70.2 ms
8/s one engine 288 62 22% 81 / 963 ms 29.9 / 42.7 ms
8/s split 288 9 3% 2,172 / 3,754 ms 75.5 / 128.3 ms

The final split series used six pinned export buffers. At 6/s an earlier three-buffer split run completed 89/230 requests within objectives, while the final six-buffer run completed 75/230; this does not demonstrate that adding buffers hurts throughput, because the two experiments also differed in time and device state. At 10/s both designs recorded one good request of 366 in their respective runs. The buffer wait metric in the reported live run was very small, suggesting the pinned-buffer ring was not the observed bottleneck there, but this is not a controlled buffer-count sweep.

Each live rate/design cell is one 40-second trace. The earlier 6/s comparison ran hours before the final series and used an earlier harness configuration: 149/230 good for the co-located engine versus 184/230 later; 43/230 for the three-buffer split earlier versus 89/230 in a later three-buffer comparison and 75/230 with six buffers. The same broad ordering survives, but the absolute numbers are not repeatable to a few percentage points on a GPU shared with other workloads. Confidence intervals, paired repetitions under controlled occupancy and a fixed hardware-speed baseline are still missing. The table should be read as evidence of a large local effect, not precise capacity forecasting.

At 6/s the type of miss is more informative than any single attainment percentage. In the co-located run 46 of the 230 offered requests missed only TPOT; none missed TTFT. In the six-buffer split run, 126 missed TPOT only, 2 TTFT only and 27 both, totalling 155 misses. The co-located engine met both objectives for 86% of its 158 short requests and 67% of its 72 long ones; the split met them for 39% and 19%. The 99th percentile, across requests, of each request’s longest inter-token gap was 146 ms for co-location and 1,190 ms for the split. This tail-gap statistic is not identical to the mean TPOT objective; both are needed to interpret stalls.

Why the split lost on one GPU

At 4.5/s, the split prefill worker’s measured median forward time for a 64-token prompt was 26.7 ms (p90 33.5), compared with 18.8 ms in the separate low-contention stage experiment. A 900-token prompt took 138 ms median (p90 154), versus roughly 62 ms from the idle fitted curve and measured 768- and 1,000-token points around 51.6–76.0 ms. Thus the live split’s prefill work was considerably slower than its calibration, especially for long prompts. These observations are consistent with contention on one GPU, but timings alone do not identify whether GPU context scheduling, memory pressure, kernel queuing or other shared work caused it.

For the split’s live 4.5/s measurements, export took median 4.9 ms for short prompts and 24.6 ms for long ones, above the idle fitted predictions of about 3.1 and 19.9 ms. Median sendall duration was 1.7 ms and 12.2 ms respectively (p90 9.3 and 22.8 ms), but this measures the sender’s call—not transfer completion or import. The decode receiver recorded a median payload-receive time of 5.0 ms across the mix and a p90 of 38.8 ms. The prefill-side wait for an available pinned buffer was approximately 7 µs. These intervals overlap or run in different workers and must not simply be added as though they were consecutive critical-path timings for one request.

The co-located design and the split were both executing on one RTX 2060. Moving prefill into a second process therefore did not create a second GPU compute resource. The measured split added host staging and a socket hand-off, and live prefill slowed under contention; median TPOT at 6/s rose from 15.4 to 25.8 ms, and the p99 per-request maximum token gap grew from 146 to 1,190 ms. A plausible mechanism is kernel or memory-resource interference between the two GPU processes, but the experiment has no profiler trace identifying a GPU scheduling cause. The defensible result is the measured slowdown on a shared GPU, not a proof that all one-GPU process splits fail or a measurement of what an independent device would achieve.

A simulator, and how far to trust it

The discrete-event simulator is parameterised by the fitted local stage costs, a decode-step model, an alpha–beta link, the workload and a cluster layout. In co-location, each worker executes an iteration that may include new prefills plus a decode step. In disaggregation, each prefill worker serially processes prompts, exports their KV, uses a per-worker serialized link for transfers, and hands requests to decode workers that install them and advance a batch. The router favours lower reported load with a least-recently-assigned tie break. The model assumes deterministic stage costs for a given input shape, complete requests, a simple FIFO transfer path and no independent admission controller or memory-exhaustion effect. It does not reproduce GPU contention, protocol failure, cancellation, retry, prompt-dependent compute or bandwidth sharing across multiple simultaneous transfers.

Validation has two layers. Unit tests check conservation and exact scheduling arithmetic in small constructed cases: one request’s stage sum, an arrival interrupting a decode batch, a serialized link, longest-context decode cost and a slow link making the split worse. Separately, saved simulator outputs are compared with live single-GPU traces. The synthetic tests validate implemented event logic; agreement with live counts is an imperfect empirical cross-check, not proof of the assumed independent-device performance. In particular, a simulator can reproduce a shared-GPU result after a new contention rule has been fitted to that result and still predict a different two-GPU outcome incorrectly.

For the co-located runs, the simulator predicted 114/120 good at 3/s (live 118), 153/171 at 4.5/s (live 159), 149/230 at 6/s (live 184 in the final series and 149 earlier) and 47/288 at 8/s (live 62). Agreement is closer at low load; at 6/s the final live result exceeds the model by 35 requests, or 15.2 percentage points of the offered 230, and at 8/s by 15 requests, or 5.2 percentage points of 288. Those are percentage-point differences in attainment, not relative percentage errors on the model’s prediction. Device variability and the simple step-cost fit are plausible contributors but have not been separately measured.

An independent-device simulation of the split counted 120/120, 171/171, 217/230 and 180/288 good at 3, 4.5, 6 and 8 requests/s. The live split on one GPU counted 104, 129, 75 and 9 at the corresponding rates. The gap is expected because the simulator’s independent-device case deliberately removes GPU contention, so it cannot be validated by those live runs. A shared-device mode added after inspecting the live disagreement counted 105, 129, 100 and 12: close in two cells, 25 optimistic at 6/s, and close again at 8/s. That fit is explanatory and partly post hoc. A fresh held-out shared-GPU trace and, more importantly, a real two-GPU experiment are needed to test either mode predictively.

If each phase had a device

For the counterfactual comparison, the simulator gives two device budgets to both choices: two independent co-located workers versus one dedicated prefill and one dedicated decode worker. It searches for the largest offered rate at which mean attainment across two seeded Poisson traces is at least 90%, using a finite-duration simulation and geometric bisection. This procedure presumes attainable load behaves sufficiently monotonically for bisection, which was not established in every row; neighbouring results can be noisy. The prefill weight multiplies the measured GPT-2 prefill cost by 1, 4 or 16 to mimic increased prefill demand while keeping the decode cost and KV payload fixed. TTFT objectives scale from 250 ms to 1 s and 4 s, while the TPOT objective stays at 20 ms. These are synthetic workloads (chat 64/64, retrieval 900/32, summarisation 900/8, and a 70/30 mix), not measured large models. Numbers in the table are modelled requests per second at the nominal 90% criterion and should not be presented with more precision than two traces support.

workload prefill weight two co-located engines one prefill + one decode ratio
chat 1 29.0 18.6 0.64
chat 4 13.3 17.4 1.31
chat 16 2.7 4.7 1.75
retrieval 1 6.8 6.6 0.96
retrieval 4 1.9 2.5 1.32
retrieval 16 0 0.7
summarise 1 4.2 7.1 1.68
summarise 4 1.6 2.5 1.54
summarise 16 0 0.7
mixed 1 9.7 6.1 0.63
mixed 4 3.8 6.3 1.64
mixed 16 1.1 2.0 1.79

A reported zero means the search’s minimum offered rate of 0.5 requests/s already fell below 90% attainment; it does not imply zero physical serving capacity. The similar 0.7 and 2.5 rates for retrieval and summarisation follow from their common 900-token prefill demand in this particular deterministic stage model, not from a measured universal prefill limit. For high prefill weights the single prefill worker is often the bottleneck even though the two workloads have different generation lengths. A different prefill cost curve, admission policy or longer simulation could move these thresholds.

At prefill weight 1, the simulated split trails two co-located workers for chat (0.64×) and the mixed workload (0.63×), is near parity for retrieval (0.96×) and leads for short-output summarisation (1.68×). At weight 4 the split leads in the displayed workloads, about 1.3–1.6×; at weight 16 the reported ratios are 1.75–1.79× only in rows where both layouts met the search’s minimum rate. This is a coherent model prediction: heavy prefills cause interference in co-location, while separated devices pay their transfer cost outside the decode critical path. It is not evidence that changing an actual model from GPT-2 to one four or sixteen times larger produces those gains. Such a model would also change weights, KV size, prefill scaling, decode kernels, memory capacity and often batching.

The simulated link sensitivity depends on prompt KV size and the short-output TPOT definition. Substituting the host-copy estimate (20 µs, 6.2 GB/s) or an assumed high-bandwidth scale-up link (10 µs, 300 GB/s) moved most displayed capacity estimates little. A slower assumed link (100 µs, 0.5 GB/s) reduced retrieval at weight 1 from 6.6 to 2.5 req/s and hurt summarisation especially sharply. A 900-token GPT-2 float32 KV block is about 66.4 MB; at 0.5 GB/s the bandwidth-only time is about 133 ms. If only seven token gaps follow the first token, that transfer by itself contributes about 19 ms to their average, before decode or install, enough to threaten the 20 ms TPOT target. In the implemented protocol, TTFT may still include export before the first-token report; only the subsequent transfer/install is excluded from that event’s timestamp. These sensitivity rows are modelled using one serialized-transfer assumption and do not establish real-network behaviour.

Which ratio of workers

At four modelled devices, the possible placements are four co-located workers or partitions of the four into dedicated prefill and decode roles: 1P+3D, 2P+2D and 3P+1D. Each design is simulated under the same workload family, fitted stage costs and measured loopback-model parameters, but in the disaggregated cases the workers are still assumed to execute independently. Link contention between workers and physical device-memory constraints are not verified. As above, the reported thresholds are based on only two seeded traces per tested rate.

workload prefill weight 4 co-located 1P + 3D 2P + 2D 3P + 1D
chat 1 60.3 56.0 38.4 18.6
chat 4 29.8 17.4 34.3 18.6
retrieval 1 17.0 7.1 17.2 6.7
retrieval 4 5.4 2.5 6.5 8.3
summarise 1 15.0 7.1 19.3 7.1
summarise 4 5.7 2.5 6.5 10.8
mixed 1 22.0 20.6 14.0 6.1
mixed 4 9.4 7.4 14.6 6.2

The preferred modelled P:D ratio changes strongly with the workload. At prefill weight 4, 3P+1D leads the tested split choices for retrieval (8.3 req/s) and summarisation (10.8), while it is comparatively poor for short-prompt chat and for the mixed workload at weight 1. At weight 1, 1P+3D is the strongest tested split for chat (56.0) and mixed (20.6). Comparing extreme placements within a row can give factors of roughly 2–4, including summarisation at weight 4 (10.8 versus 2.5). But the claim that the best split matches or beats four co-located engines in six of eight rows must be read carefully: some margins are tiny relative to the two-trace estimation procedure. At weight 1, co-location still wins for chat (60.3) and mixed (22.0) in this model. The ratio is a tuning variable and a fairness/capacity trade-off, not a constant tied to the model name.

These are single modelled search estimates using two seeded traces per rate, not confidence intervals. Adjacent entries can jump because a discrete change in offered load or a finite trace alters the batch and queue dynamics. Before selecting a hardware P:D ratio, repeat with independent traces, vary prompt and output lengths, check sensitivity to the arrival process and actual transfer concurrency, and test the selected placement on the intended devices. A 10% difference in this table alone is insufficient evidence for an expensive topology decision.

The next table is a separate fp16 roofline calculation, not a continuation of the GPT-2 float32 live experiment. For eight cached model configurations, KV bytes per prompt token come from model shapes and fp16 values. The assumed prefill rate is \(0.4 \times 31.4\,\mathrm{TFLOP/s} / (2 \times \mathrm{parameter\ count})\), ignoring attention FLOPs and treating the full parameter count as the dominant work per token. The 40% is an illustrative efficiency: the measured GPT-2 fp16 runs achieved roughly 29–39% of the locally observed peak over 256–1,000 tokens, while Llama-3.2-1B ranged roughly 40–60%. No single efficiency describes every architecture and length. Needed link is KV bytes/token × modelled prompt tokens/s at full use of one prefill worker; transfer/prefill is calculated for a 512-token prompt with the stated link latency. These values are sizing approximations, not measured throughput of the split for any model in the table.

model KV bytes / token modelled prefill tokens/s needed link transfer ÷ prefill at 1.2 GB/s (Chapter 28’s gloo loopback) at 6.2 GB/s (PCIe via host) at 12.5 GB/s (100 Gbit/s, 50 µs assumed)
GPT-2 36,864 50,466 1.86 GB/s 1.56 0.30 0.15
Llama-3.2-1B 32,768 5,082 0.17 GB/s 0.14 0.03 0.01
Qwen3-1.7B 114,688 3,650 0.42 GB/s 0.35 0.07 0.03
Llama-3.1-8B 131,072 782 0.10 GB/s 0.09 0.02 0.01
Phi-3-mini-4k 393,216 1,644 0.65 GB/s 0.54 0.10 0.05

Of the displayed models, GPT-2 has the largest modelled KV-to-compute ratio: about 1.48 × 10⁻⁴ KV bytes per assumed prefill FLOP, versus 8.16 × 10⁻⁶ for Llama-3.1-8B, a factor of approximately 18. At the table’s fp16 assumptions and an illustrative 1.2 GB/s link, GPT-2’s transfer time is 1.56× its modelled prefill time, versus 0.09× for the 8B configuration; Phi-3-mini is about 0.54×. These ratios exclude KV gathering/installing, memory contention, attention FLOPs, queueing, compression, retries and actual interconnect utilisation. They should not be conflated with the float32 73,728-byte GPT-2 payload or the 2.68 GB/s live loopback fit earlier in the chapter. A real larger-model experiment is required before drawing deployment conclusions.

What the published designs add

Three published systems help frame this design: they ask related questions about placement, phase-specific hardware and KV ownership. Their reported improvements belong to the authors and their evaluation workloads. The laboratory below is an independent small-scale demonstration and neither reproduces nor benchmarks their production systems.

DistServe (OSDI 2024; arXiv 2401.09670) frames prefill/decode placement around TTFT and TPOT objectives and the resulting goodput. It allocates separate resources and parallelism plans to the phases, and explicitly accounts for KV transfer bandwidth. Splitwise (ISCA 2024; arXiv 2311.18677) studies phase splitting and heterogeneous provisioning; its authors report up to 1.4× throughput at 20% lower cost or 2.35× under the same cost/power budgets. Mooncake (FAST 2025; arXiv 2407.00079) centres its architecture on a distributed KV store, cache reuse and workload-aware scheduling, including early rejection under overload; an extended account also appears in ACM Transactions on Storage. These venues can be verified from publisher or conference records; the earlier draft’s ‘venue not named’ and ‘preprint only’ descriptions were incomplete. All benefits in these papers are their authors’ reports, not measurements reproduced by this book. Nothing here establishes how an unrelated proprietary provider implements the same idea.

The DeepInfer README pinned by this book names prefill/decode disaggregation, a KV-cache system and data-parallel replica balancing among components needed for a complete service but not included in the released engine; it also describes a benchmark configuration using separate prefill and decode GPU groups. The chapter does not infer that its publicly released code implements the whole inter-worker transfer and serving protocol, and the DeepInfer benchmark was not reproduced here. The exact pinned commit is listed in the references.

The contribution of this chapter is deliberately bounded: an inspectable export/import path with a small correctness test and a 26-request live token-identity check; measured operation and loopback costs on one shared GPU; a same-traffic comparison where that split loses; and a simulator that states when independent phases might win. The combination exposes an important methodological trap: a simulator may tell a plausible two-device story while its strongest live validation used only one device. The next experiment should therefore validate the resource boundary, not simply add more modelled points.

How the harness hung, and what that taught

An initial unattended live chain deadlocked for almost three hours and yielded no usable result. The parent was sending requests through one bounded pipe while reading worker events from another; under load, a worker could block writing events while the parent blocked sending new requests that the worker could no longer read. That is a circular wait created by backpressure, not evidence about prefill/decode performance. The run was discarded and is excluded from all reported tables. The failure is part of the laboratory evidence because an inference benchmark that cannot drain its own events can manufacture missing requests or indefinite latency.

The harness was changed so a separate sender thread can enqueue requests while the parent continues reading worker events. It also gained bounded-run supervision and worker stack dumps to diagnose a stalled run. This avoids the observed circular wait in the subsequent completed experiments; it does not prove every failure path is safe. The parent still relies on a custom process protocol, and hard exit is a last-resort watchdog rather than graceful request cancellation. The lesson for the next chapter is to treat control-plane liveness, backpressure and worker failure as first-class invariants, with explicit ownership and bounded waits.

What the numbers do not show

  • No real independent-device validation. Live prefill and decode processes share one RTX 2060 with the desktop and other GPU work. Independent-device benefits are simulated, not measured. The simulated two-device comparison is more appropriate than extrapolating directly from the one-device live result, but it remains unvalidated on two GPUs.
  • No production interconnect. The measured KV socket is loopback TCP on Windows; the host-device copies are local. The assumed PCIe-through-host, 100 Gbit/s and high-bandwidth scale-up entries are not measurements of multi-worker end-to-end transfers on those fabrics.
  • One real split model and precision. Token identity is checked for GPT-2 small float32 with greedy decoding. The eight-configurations table is fp16 shape/roofline arithmetic; no other full model was run through the split.
  • Limited repetition and shared-GPU noise. One 40-second live trace per main cell, with an earlier 6/s comparison under changed conditions. The co-located good count changed from 149 to 184; the split result also moved widely. No live confidence intervals or controlled profiler attribution are supplied.
  • Simple cost fits and retrospective calibration. The simulator uses deterministic linear curves fitted to local measurements and a context-dependent batch-step fit. The shared-device option was introduced after observing the live mismatch and has not been held out. The independent-device case is a hypothesis.
  • Search precision and assumed monotonicity. The maximum-attainment-rate search uses bisection over two seeded finite traces and a 0.5 req/s floor. Reported two-decimal rates are computational outputs, not empirical precision bounds.
  • No complete capacity or cost model. The simulation omits full checkpoint residency, duplicate model weights on a shared GPU, all KV allocator constraints, staging buffers, failures and hardware/network pricing. Four workers in arithmetic are not a verified deployable four-device cluster.
  • No full hand-off contract. The socket header lacks versioned dtype/layout/model identity, checksums, authentication, bounded payload admission, acknowledgments and retry semantics. Cancellation, ownership transfer and idempotent recovery after a crash are not established.
  • No alternative policies. Prefix caching, chunked prefill, quantised or compressed KV, continuous admission control, multiple simultaneous transfers and client cancellations have not been combined and measured in this split.

Inference Lab increment

examples/ch29/disagg_lab.py adds:

  • Costs, Link, Mix and fit_line: measured stage-cost fits, a simple latency/bandwidth model and seeded synthetic workloads; required_link_Bps and transfer_over_prefill for KV sizing.
  • simulate, Cluster, Outcome and summarise: a discrete-event comparison of co-location and disaggregation, including an after-the-fact fitted shared-device mode; max_rate searches for a 90%-attainment threshold by geometric bisection.
  • DisaggEngine: Chapter 27’s paged engine extended with KV export/import and first-token continuation. Its pending imports are tested, but the implementation does not provide an atomic distributed transfer transaction.
  • The prefill, decode and co-located worker entry points, plus a loopback TCP wire format with a JSON header and raw KV payload.
  • run_live: an open-loop process harness with an independent sender thread, watchdog supervision and token event collection.
  • Commands costs, colocated, disagg, compare, sweep, requirements, efficiency and exactness, which separate actual runs from simulation and shape-based estimates.

To reproduce the measured local costs and the single-GPU split at 4.5 requests/s, run these commands from the Inference repository with the cached GPT-2 checkpoint and required Python dependencies. Both workers will attempt to use the selected local CUDA device; these commands do not test multi-GPU disaggregation. Capture the machine’s GPU occupancy and run the co-located baseline in the same conditions before comparing results:

python examples/ch29/disagg_lab.py costs
python examples/ch29/disagg_lab.py disagg --rate 4.5 --duration 40 --buffers 6

The operational rule is: disaggregation pays only when the phase isolation and resource placement outweigh the full KV hand-off and queueing costs. Record the model/cache layout, prompt and output distribution, prefill/export/link/import timings, TTFT and TPOT, and what resources each alternative actually receives. Compare equal-device co-located and split topologies, not a sequential baseline with a pipelined competitor. Confirm token identity after the hand-off and treat a fitted simulator as a hypothesis generator until its separate-device predictions survive a real held-out measurement.

What you should now be able to do

  • Compute logical KV bytes per prompt position from layers, KV heads, head dimension and dtype; distinguish MB from MiB and payload from allocated staging memory.
  • Derive a bandwidth-only hand-off ratio and explain when fixed latency, export cost, non-linear prefill and queueing make it depend on prompt length.
  • Trace when the first token is reported in this implementation and distinguish export’s effect on TTFT from transfer/install effects on subsequent token gaps and TPOT.
  • Compare the same request trace on one shared GPU without claiming that it validates a two-GPU outcome.
  • Evaluate 90%-attainment rate estimates while accounting for the finite-trace search, changed workload mix and unmeasured interconnect assumptions.
  • Describe the manifest, acknowledgment and idempotent recovery obligations that an actual inter-worker KV transfer needs.

Key terms

  • Prefill worker / decode worker: roles that evaluate prompts and continue generation from transferred KV, respectively; separate processes do not necessarily mean separate accelerators.
  • KV hand-off: exporting, transmitting, validating and installing a prompt’s keys and values before continuation.
  • Export / install: gathering state from a paged cache into a transfer buffer and populating a receiving paged cache.
  • TTFT / TPOT: latency to the first observed token and mean subsequent per-token interval; the chosen report point for the first token determines whether export enters TTFT.
  • Good request / attainment: a completed request meeting both stated objectives, and the fraction of offered requests that meet both.
  • Goodput: rate of completed requests that meet objectives; distinguished here from offered-load capacity at 90% attainment.
  • Prefill weight: a simulator multiplier on measured prefill time, not a measured larger model.
  • Shared-device simulation: a post hoc scheduling model in which two logical workers contend for one simulated execution resource.
  • P:D ratio: allocation of accelerator-backed workers to prefill versus decode roles.
  • Logical KV payload: KV bytes needed to represent positions, excluding page rounding, staging and protocol overhead.

Reader exercises

  1. Run the exact same seeded co-located and split traffic on two real GPUs. Compare two co-located replicas with a 1P+1D allocation and record achieved TTFT, TPOT, KV-transfer completion, memory and GPU utilisation. Does the independent-device simulation predict the observed attainment?
  2. Emit token one immediately after prefill but before export, or measure both timestamps. Quantify the difference in TTFT and in the first-to-second-token gap, including empty and single-token completions.
  3. Implement a versioned KV transfer header containing checkpoint/tokenizer identity, dtype, dimensions, positions, payload length and checksum. Refuse a mismatched import before allocating blocks; test malformed, oversized and truncated frames.
  4. Replace loopback TCP with an appropriate multi-device transport, then fit bandwidth and latency from end-to-end export-to-install measurements, not only sendall timings.
  5. Add chunked prefill to the co-located engine and repeat matched-load comparisons, so the baseline uses a reasonable alternative to a single long prefill step.
  6. Repeat the capacity sweep using held-out arrival traces and confidence intervals, test monotonicity of attainment, and bound errors of the bisection-derived thresholds.
  7. Integrate Chapter 26’s deadline-aware admission across prefill, transfer and decode queues, including capacity limits for KV blocks and pinned staging buffers.
  8. Inject worker crashes and socket truncation at each transfer stage; demonstrate idempotent release or recovery without duplicate tokens (the subject of Chapter 30).

References

Evidence in this chapter

Claim Category
26/26 real GPT-2 greedy outputs match between co-location and a two-process KV hand-off; tiny CPU test compares cache values Book result, narrow tested configurations
KV payload is 73,728 bytes per GPT-2 float32 prompt position; 64 and 900 prompts imply 4.72 and 66.36 decimal MB Arithmetic from measured configuration; excludes allocations and protocol overhead
Prefill, export and install times on this RTX 2060, plus 2.68 GB/s fitted local socket bandwidth Book result, single-host runs with stage-fit limitations
The first-token event follows prefill_export(), so export enters TTFT; socket transfer and installation delay later tokens Code-observed timing contract; performance magnitude measured only locally
At 6/s on the shared GPU the co-located engine had 184/230 good versus 75/230 for split; other rates show the same broad ordering Book result, single traces with substantial device-state variability
A 900-token live split prefill took 138 ms median versus about 62 ms fitted idle Book result; contention mechanism hypothesis, not profiled
Independent-device simulation gives 217/230 good at 6/s; post hoc shared-resource mode gives 100/230 Modelled, the independent-device prediction is not empirically validated
Two- and four-device topology sweeps, optimal P:D ratios and slow-link sensitivity Modelled, finite two-seed thresholds and deterministic fitted costs
Eight-model fp16 KV/link requirement table at 40% efficiency Modelled shape/roofline estimate; not eight split experiments
sendall time is not receive/install completion; transfer header does not validate shape, dtype or model identity Code-audited limitation
DistServe, Splitwise and Mooncake designs and published benefits External reported research, none reproduced
Two GPUs, actual cross-node transport, NCCL, RDMA, NVLink, failure recovery and larger split models NOT_RUN

Implementation status

  • Manuscript: content/books/inference/29-chapter.md.
  • Runnable examples: examples/ch29/disaggregation.py (original toy demonstration, unchanged) and examples/ch29/disagg_lab.py (measurement, simulator, GPT-2 KV export/import and two-process harness).
  • Tests: tests/test_ch29_disaggregation.py and tests/test_ch29_disagg_lab.py (33 recorded tests covering cost arithmetic, simulator event logic, slow links, export/import on tiny GPT-2, waiting/cancelled imports, framing and a two-process exactness run unless skipped). These do not establish distributed crash recovery or full cross-device compatibility.
  • Evidence: research/ch29/sources.md, research/ch29/results.json, research/ch29/costs.json, research/ch29/raw/ (compressed per-request rows), research/ch29/build_results.py and research/evidence-register.md.
  • Verification command from the repository: python -m unittest discover -s tests -v. GPU-dependent commands require a compatible runtime and locally available model weights; I have not rerun them as part of this editorial review.
  • Publication remaining work: two-GPU held-out qualification, chunked-prefill baseline, manifest-checked transfer framing, pinned-buffer ownership tests, failure injection, and confidence intervals around capacity estimates.

This chapter is still marked draft = false but should be treated as a technically reviewed candidate, not evidence of production or multi-GPU qualification. Its central local finding is the observed single-GPU disadvantage of adding a prefill/decode process boundary; its counterfactual benefit depends on separate-device assumptions not yet measured. Chapter 30 can now use the exposed hand-off contract as a concrete failure boundary: which worker owns an in-flight KV block, when the receiver is allowed to resume, and what happens to resources and client-visible tokens if either side disappears.