Chapter 43
Distributed Inference and Stateful Placement
On this page
- Replication first
- Tensor-parallel decode
- Pipeline inference
- KV ownership under model parallelism
- Phase-specific context parallelism
- KV transfer and remote memory
- Specify a KV handoff as a commit protocol
- Replica routing with distributed state
- Expert-parallel serving
- Streaming failure semantics
- SLO-constrained scaling
- Design Exercises
- Worked Solutions
Distributed inference repeats communication for every generated token while carrying request-specific KV state. A layout that scales training throughput can fail interactive latency because decode has small local work and a strict serial cadence.
Replication first¶
If a model and its working-state reserve fit on one device or node, independent replicas usually scale serving capacity most simply. Replicas run separate batches, isolate failures, and avoid per-layer cross-replica synchronization.
Model parallelism is needed when the model or KV does not fit, or when one request's latency benefits from multiple devices enough to offset communication. Use the smallest model-parallel group that satisfies fit and SLO; spend remaining devices on replicas.
The fastest single request plan can lower fleet goodput if it consumes more devices per replica and creates longer queues. Evaluate the full arrival process and failure reserve.
Tensor-parallel decode¶
Tensor parallelism shards weights and compute but adds reductions or gathers in many layers. Decode local matrix height is approximately active batch size, so high TP degree produces small per-rank GEMMs and latency-bound collectives.
A simplified step decomposition, with local compute excluding the separately counted KV-attention time, is:
Quantization reduces local weight traffic and compute, which can make collectives a larger fraction. Batching raises local GEMM efficiency and amortizes communication, but lengthens each iteration and consumes more KV. Choose TP jointly with the scheduler's latency budget.
Collective fusion across operations is constrained by dependencies and residual paths. CUDA graph capture or persistent scheduling can reduce host gaps, but the distributed launch order and communicator buffers must remain stable.
Pipeline inference¶
Pipeline stages reduce per-device weight memory. For one request, first-token and token latency include traversal across all stages. With many requests, stages can process different microbatches and improve throughput.
Continuous batching creates dynamic microbatches and output lengths. A stage may receive a different active set each iteration, so sequence IDs and KV ownership must be explicit. Pipeline bubbles arise from too few microbatches, stage imbalance, and pauses for long prefills.
Chunked prefill can create more uniform stage work. Separate prefill and decode pipelines can specialize schedules but introduce KV handoff, as Part III discusses. This chapter focuses on how the chosen parallel groups carry that state.
KV ownership under model parallelism¶
KV layout follows attention partitioning:
- head-sharded TP stores only local KV heads when compatible;
- replicated KV simplifies access but multiplies capacity cost;
- context or sequence partitioning stores token ranges on different ranks;
- pipeline stages store KV only for their layers;
- expert parallelism normally does not own attention KV directly.
Grouped-query and multi-query attention may have fewer KV heads than TP ranks. Replicating a KV head across a subgroup can avoid empty shards but increases bytes. Alternatively, ranks can share or exchange K/V, adding latency. The best mapping depends on head count, context, and fabric.
Block tables and prefix references must use the same distributed ownership. A request is not admitted until every required rank can reserve its shard; otherwise one rank can OOM after peers have advanced.
Phase-specific context parallelism¶
Prefill partitions query rows; the contiguous split shown explains ownership, not balanced causal work. Decode partitions historical KV tokens, merges the per-rank maximum m, denominator l, and weighted numerator o, then normalizes. A transfer between separate prefill and decode pools is a different boundary.
“Context parallelism” is not one inference plan. Prefill applies many queries to an expanding context and is usually optimized for time to first token. Decode applies one new query per active sequence to a large paged history and is usually optimized for inter-token latency, KV capacity, or batch goodput. A system can use different degrees and even different algorithms for these phases.
Prefill context parallelism¶
Prefill context parallelism (PCP) divides newly processed prompt tokens across PCP ranks. Each rank projects and attends for a subset of query positions, reducing the local attention work and activation footprint. It primarily targets long-prompt time to first token and contexts whose attention working set does not fit conveniently on one rank.
Two implementation families make different memory-communication trades:
- partial query, full KV: ranks keep local query chunks but exchange or gather the keys and values needed by those queries;
- partial query, partial KV: ranks keep both query and KV partitions and circulate blocks, often with ring attention and an online softmax merge.
The first is simpler but can reproduce the full-KV memory cost. The second bounds local KV working memory but introduces ordered communication and causal-load-balancing work. Contiguous causal partitions are imbalanced because late query blocks see more history; zigzag or interleaved mappings distribute early and late positions more evenly.
PCP is normally an additional process-group dimension. In the vLLM revision cited below, PCP is separate from tensor parallelism and therefore increases the world size for a fixed tensor-parallel group. Support remains version- and attention-backend-dependent, so a deployment must validate the exact release and kernel path rather than assuming that every context-parallel prefill algorithm is production-ready.
Decode context parallelism¶
Decode context parallelism (DCP) instead partitions the historical KV cache along the sequence dimension. Every rank evaluates the new query against its local history, then the ranks merge compact partial-attention state. For a shard r, let m_r be its maximum score, l_r its shifted exponential sum, and o_r its shifted weighted-value sum. The exact global result is:
The global maximum provides a common numerical reference across history shards.
Shifted local normalizers combine into the exact global softmax denominator.
Only compact statistics need to be reduced; the historical KV tensors need not be gathered.
Each history shard must first receive the query heads whose KV it owns, by replication or exchange according to the TP layout. The merge then needs a common maximum before rescaling and summing denominators and output numerators, or a collective that directly combines these states. An empty or fully masked shard contributes zero mass and a zero numerator; handle it explicitly so exp(-inf - -inf) is never evaluated. If every shard is empty, apply the declared fully masked-row policy instead of dividing by zero. The compact reduction saves historical-KV transfer, but it does not eliminate query exchange, collective latency, or local KV reads.
The repository's examples/attention.py and the attention-test command in examples/README.md exercise this merge, including masked shards and rejected numerical overflow. They check single-head CPU semantics, not distributed execution or DCP performance.
Interleaving token blocks across DCP ranks spreads future cache growth and attention work more evenly than assigning each rank one permanently contiguous interval.
In the vLLM layout with PCP disabled, DCP reuses ranks inside each tensor-parallel group, and the tensor-parallel degree must be divisible by the DCP degree. This matters most for grouped-query and multi-query attention. With equal head partitions and a compatible TP degree, ordinary TP first shards KV heads; when the tensor-parallel degree T exceeds the number of KV heads H_{kv}, each head is repeated across T / H_{kv} ranks. DCP can use those otherwise duplicate-bearing ranks to shard each head's token history instead.
Replication-removal sizing for compatible GQA layouts with PCP disabled and T at least H_kv; not a universal DCP limit.
For example, with four KV heads and TP=8, each head has two copies before DCP. Choosing DCP=2 lets each copy-bearing pair store complementary token blocks. There are still eight GPUs, but the pair stores one logical history instead of two full copies. This is sequence sharding inside the allocated model group, not a TP=8 prefill pool handing off to a TP=2 decode pool.
Increasing DCP reduces duplicated KV capacity and may admit a larger decode batch, but it adds communication to every attention layer and generated token. It is therefore not automatically a token-latency optimization. The gain often appears first as more cache headroom, fewer evictions, or higher SLO-compliant fleet goodput.
Group geometry and mixed phases¶
For vLLM's model-worker rank space, excluding API processes and independently launched pools, the layout can be summarized as:
DCP reuses this rank space rather than adding another multiplier; the product does not imply every combination is supported.
The implementation is evolving. In vLLM's parallel configuration at revision 252ed876, checked September 7, 2026:
- with PCP=1, DCP must divide TP;
- with PCP greater than one, the accepted DCP sizes are 1, PCP, or TP multiplied by PCP;
- PCP greater than one cannot yet be combined with DP greater than one.
Thus “DCP is always nested inside TP” is too broad: combined layouts can span the PCP axis or the full TP-by-PCP block. These are configuration constraints in the cited revision, not a guarantee that every model or attention backend supports each accepted combination. The older replication-removal bound above explains the no-PCP case; it must not be applied to every combined layout.
| Mechanism | Primary shard | Adds ranks for fixed TP? | Main serving objective | Recurring cost |
|---|---|---|---|---|
| TP | weights, activations, and usually KV heads | yes | model fit and layer compute | per-layer reductions or gathers |
| PCP | prompt query positions; optionally KV blocks | yes | long-prompt TTFT and working-set fit | KV exchange or ring traffic during prefill |
| DCP | historical KV tokens across existing ranks | no | remove KV duplication, enlarge batch or context | partial-attention merge during decode |
Chunked prefill blurs the phase boundary. A request may already have DCP-sharded history while a new prompt chunk supplies many query positions. Prefix-cache hits create the same condition. The engine must combine the new chunk with distributed historical state; the label “prefill” alone does not determine which communication appears in the kernel.
A sound selection sequence is:
- choose the smallest TP degree that fits weights and meets layer latency;
- add PCP only when long-prompt TTFT or prefill attention memory remains limiting;
- add DCP when TP has created KV-head duplication or decode capacity is history-bound;
- measure phase-specific latency, cache occupancy, communication, batch size, and fleet replica count together;
- verify the current runtime's model, attention-backend, chunked-prefill, speculative-decoding, and multi-token-prediction compatibility.
Do not copy a training CP degree into serving by precedent. PCP and DCP solve different bottlenecks, have different process-group geometry, and can move opposite SLOs.
Phase-specific sharding ledger¶
The word sharding is incomplete unless it names the tensor axis, phase, and communication. The following ledger separates mechanisms that are often conflated:
| Mechanism | Prefill ownership | Decode ownership | Recurring communication |
|---|---|---|---|
| TP | Weight/output channels and attention heads; every rank processes the active prompt rows | The same model shards plus local KV heads or latent state | Per-layer reductions or gathers in both phases |
| PCP | Prompt query positions; K/V may be gathered in full or circulated as partial sequence shards | Normally not the decode-history mechanism | K/V all-gather or ring/stream exchange during long prefill |
| DCP | A prefill chunk may attend to DCP-sharded history; backend-specific prefill modes need their own group and weight plan | Historical token blocks within each owned KV head or latent cache | Merge compact partial-attention states for each layer and new token |
| P/D disaggregation | Whole requests execute in a separately sized prefill pool with its own TP/PP/PCP plan | Decode uses a separately sized pool with its own TP/PP/DCP plan | One logical KV handoff per admitted boundary, plus any resharding |
| Serving DP | Different replicas own different requests and cache namespaces | Different replicas advance independent batches | Routing and cache-state publication, not a per-layer model collective |
The current vLLM context-parallel design describes two prefill cases—partial queries with full K/V and partial queries with partial K/V—and uses token-history sharding for decode. Dynamo's disaggregated-serving contract permits the two pools to choose different parallel plans and then transfers KV through a backend-specific connector. These mechanisms compose, but their degrees are not interchangeable: TP=8, DCP=8 inside one decode group is not the same topology as eight prefill workers feeding eight decode workers.
The SDK-scoped Neuron example in Model Portability and Compiled State also has distinct prefill and decode group rules: a shared DCP flag name does not establish identical weight placement or execution geometry.
KV transfer and remote memory¶
Migration or prefill-decode disaggregation transfers state between model-parallel groups. A complete transfer plan specifies:
- logical token/layer/head ranges;
- source and destination rank mapping;
- packed page layout, dtype, and scales;
- direct versus staged network path;
- chunk order and overlap;
- integrity, idempotency, and ownership transfer.
If source TP and destination TP degrees differ, the transfer includes resharding. Avoid collecting the entire KV on one coordinator. Each source sends the intersections of its logical shards with destination ownership.
Remote KV memory is useful for inactive sessions or pooled capacity when transfer/recompute cost is below holding scarce device memory. Fetching remote pages on every token makes the network part of the attention critical path and requires a much stronger availability and tail-latency contract.
Modern reference stacks split this path into independently observable components. Dynamo's documented disaggregated path routes a request through a prefill worker, transfers KV directly between accelerator memories through NIXL, and continues on a decode worker without blocking unrelated forward passes. llm-d's cache-index architecture describes prefix-aware scoring from cache events, including GPU and CPU tier locations. This replacement source was checked October 12, 2026; the index describes where blocks reside and does not itself transfer them. The decomposition is more important than either product name: the router's belief can lag the allocator, the transfer can succeed after the destination loses admission, and transport completion is not ownership publication. Instrument and test those boundaries independently.
Specify a KV handoff as a commit protocol¶
Identify a transferable prefix by (request_id, model_revision, cache_format, committed_token_count, generation). For migration, first reserve destination storage and copy the payload for that generation. Next verify completion and metadata compatibility. Only then publish destination ownership to the scheduler. Release source pages after readers admitted under the previous ownership have completed.
Appending while copying requires a defined cut: either freeze append at the committed token count or transmit a subsequent delta with an explicit ordering edge. A destination that combines old K pages with new V pages is not a valid snapshot. Include positional state, quantization scales, and any sliding-window eviction metadata in the same logical cut.
An ownership generation prevents a delayed completion from an earlier migration from authorizing a later reuse of the same page ID. Retries must be idempotent with respect to that generation. A network transfer acknowledgment proves delivery at its stated boundary; it does not by itself prove the receiving GPU can safely consume the cache or that the scheduler has committed ownership.
Replica routing with distributed state¶
Route on estimated completion, not request count. Inputs include queue delay, model/adapter residency, prefix locality, KV capacity on every rank, transfer or recompute time, topology health, and deadline.
State affinity should be bounded. Prefer the owner while saved work exceeds its extra queue delay; otherwise migrate, recompute, or start cold. A tensor-parallel group's capacity is the minimum admissible shard across its ranks, not the sum of free bytes.
Hot prefixes can be replicated across complete model groups. Partial replication is useful only if every consumer has a defined way to access the missing shards without creating a worse network dependency.
Expert-parallel serving¶
An MoE inference group adds token dispatch to attention and tensor communication. Small decode batches make expert GEMMs inefficient. Replicate popular experts, co-batch compatible tokens, or keep EP within fast links where memory permits.
The router and scheduler can cooperate: predicted expert affinity may improve placement, but future routes are input-dependent and exposing or storing them can raise complexity. Always keep a capacity-safe fallback for unexpected hot experts.
Streaming failure semantics¶
A failure of any rank generally invalidates the model-parallel replica. A replacement group can resume only with compatible weights, KV shards, sampling state, constraint state, and the exact emitted-token commit point.
Replication supplies spare groups, not automatic state replication. Recomputing KV from prompt and accepted output is often the simplest recovery before the first token; after streaming begins it may exceed latency and must avoid duplicate visible bytes.
Use request IDs and token sequence numbers. If exact resume cannot be proven, terminate the partial stream clearly rather than emitting a divergent continuation. Part III defines the product contract; the distributed layer must preserve it across all ranks.
SLO-constrained scaling¶
Report:
- first-token and inter-token latency by group layout;
- input and output goodput per accelerator;
- collective and KV-transfer tail time;
- queueing under complete replica count;
- memory headroom on the most constrained rank;
- performance after one group or network path fails.
Strong-scaling efficiency is secondary to good requests per fleet cost. A plan that halves kernel time but doubles devices and queueing is not an inference win.
Design Exercises¶
- Why is tensor parallelism more latency-sensitive in decode than in training?
- Design distributed KV ownership for TP, PP, and GQA.
- Compare PCP and DCP: what does each shard, when does it add ranks, and which serving bottleneck does it address?
- How do you reshard KV during migration without a central bottleneck?
- Design state-aware routing to a model-parallel group.
- Specify safe recovery after one rank fails during streaming generation.
Worked Solutions¶
1. Decode sensitivity¶
Decode has a small token dimension and repeats a serial step for every output token. TP shrinks already-small local GEMMs while collectives remain inside many layers, so latency and launch overhead are exposed. Training has larger microbatches and long backward compute that better amortize or overlap communication. Quantization can worsen the ratio by accelerating compute without reducing collective latency.
2. KV ownership¶
PP stages own KV only for their layers. Within a stage, TP ranks own compatible attention heads when KV-head count permits. If GQA has fewer KV heads than TP ranks, either form KV-sharing subgroups, replicate selected heads, or lower attention TP; document the added bytes or exchange. Block tables and reservations are sharded identically, and admission succeeds only when every stage/rank reserves its required pages.
3. Prefill versus decode context parallelism¶
PCP shards prompt query positions across a separate process-group dimension and may also partition the KV working set. It can reduce long-prompt TTFT or make the prefill attention working set fit, but it usually consumes additional ranks and communicates KV blocks or online-attention state. DCP shards historical KV tokens among already allocated ranks: inside TP when PCP is disabled, or across supported PCP/TP layouts when it is enabled. In vLLM it does not increase world size. Removing duplicated GQA or MQA KV heads is one important use case. DCP can recover cache capacity and raise decode batch goodput, but adds a partial-attention merge at every layer and token. Benchmark PCP on prompt length and TTFT; benchmark DCP on context, cache occupancy, batch size, inter-token latency, and SLO-constrained goodput.
4. KV resharding¶
Describe KV in logical layer, token, head, and feature ranges independent of source layout. Each source rank intersects its owned ranges with destination ranges and sends chunks directly to the corresponding destination ranks. Pre-reserve destination pages, include version/dtype/scale metadata and checksums, and commit ownership after all chunks are visible. Avoid assembling full KV on a coordinator; distribute metadata planning separately from data movement.
5. Group routing¶
Treat a model-parallel group as one service unit whose admissible memory is constrained by its tightest rank. Estimate queue plus cache miss/recompute or transfer plus execution, adjusted for adapter, topology health, and SLO. Prefer state locality only while it reduces completion time, replicate hot immutable prefixes to whole groups, and retain cold-start fallback. Monitor prediction error and rank-level imbalance.
6. Rank failure during streaming¶
Abort and quarantine the whole synchronized group. Identify the last token committed by the model and acknowledged by the transport. Resume on a compatible spare only if prompt, accepted tokens, distributed KV or deterministic recompute, RNG, adapter, constraints, and model version reconstruct exactly, with duplicate suppression by token sequence. Otherwise end the stream with a clear partial-response failure and release all sharded state idempotently.