Large Language ModelsInference & Performance Optimization
How do context parallelism and decode context parallelism scale long-context LLM inference across GPUs while balancing KV-cache capacity, attention compute, and communication?
Question 297 of 309 · Updated
On this page
- 1. The long-context inference problem
- 2. A simple numerical example
- 3. Distinguish context parallelism from other parallelism strategies
- 4. Prefill and decode are different CP problems
- 5. Prefill context parallelism: distribute the prompt
- 5.1 Partial query, full key/value
- 5.2 Partial query, partial key/value
- 5.3 When to use which prefill strategy
- 6. Decode context parallelism: shard the KV cache by token position
- 7. How distributed attention results are combined
- 8. Why tensor parallelism alone can waste KV memory
- Example: GQA
- Example: MLA
- 9. Worked capacity example
- 10. Communication cost: when DCP helps and when it hurts
- 11. Choosing the DCP degree
- 12. Interleaved KV-cache sharding and dynamic growth
- 13. Topology matters
- 14. Combining CP with TP, DP, and disaggregated serving
- 15. Benchmarking context parallelism correctly
- 16. Numerical decision example
- 17. Common mistakes
- 18. Production rollout checklist
- 19. Key takeaways
1. The long-context inference problem#
Long-context LLM serving stresses two resources at once:
- Attention computation and memory bandwidth: every new decode token must attend over the request's existing context.
- KV-cache capacity: keys and values for previous tokens must remain available while the request is active.
A model may fit comfortably on several GPUs and still struggle to serve long prompts at useful concurrency. The bottleneck is often not the model weights; it is the growing KV cache and the work required to read and attend over it.
Tensor parallelism (TP) distributes model computation and commonly shards attention heads across GPUs. But TP cannot always keep reducing KV-cache memory per GPU. Grouped-query attention (GQA) has fewer KV heads than query heads, and Multi-head Latent Attention (MLA) may have a single shared latent KV representation. Once the available KV-head dimension has been fully divided, additional TP ranks can hold duplicate KV data rather than unique portions.
Context parallelism (CP) addresses a different axis: it distributes the sequence or context dimension across GPUs. Instead of assigning only different heads to different GPUs, it assigns different token positions to different GPUs. Each rank stores or processes a portion of the context, and attention results are coordinated across ranks.
This lesson explains context parallelism for inference, with particular attention to prefill context parallelism and decode context parallelism (DCP). It is distinct from general KV-cache management, prefix caching, disaggregated prefill/decode, and the expert-parallel communication topic in Question 296.
2. A simple numerical example#
Imagine a request with a 200,000-token context. Assume the model's KV cache for this request occupies 40 GiB when stored on one GPU. This is an illustrative number; actual memory depends on layers, KV heads, head dimension, dtype, and architecture.
With four-way context sharding:
- GPU 0 stores token positions 0–49,999.
- GPU 1 stores token positions 50,000–99,999.
- GPU 2 stores token positions 100,000–149,999.
- GPU 3 stores token positions 150,000–199,999.
Ignoring metadata, temporary buffers, and replication, each GPU now stores approximately 10 GiB for this request instead of 40 GiB.
The benefit is not merely that the request fits. The freed memory can accommodate additional requests, increasing concurrency and potentially throughput.
But there is a cost: each GPU has only a partial history. To compute exact attention for a new query, the system must combine information from the shards. That requires communication and a numerically correct reduction.
The central trade-off is:
The best CP degree is therefore not automatically the maximum available GPU count. It is the degree that improves request-level performance after accounting for communication, synchronization, and the model's attention structure.
3. Distinguish context parallelism from other parallelism strategies#
These techniques split different dimensions:
- Tensor parallelism: splits model tensors or attention heads across GPUs within layers.
- Pipeline parallelism: assigns different model layers to different GPUs or stages.
- Data parallelism: replicates model execution and processes independent requests on different replicas.
- Expert parallelism: distributes MoE experts and routes tokens to their owners.
- Context parallelism: distributes token positions or context across GPUs.
They can be combined. A production deployment may use TP for model weights, CP for long-context attention, and DP for request-level scaling.
The important design question is not which parallelism is universally best. It is which dimension is limiting the workload.
For example:
- If the model weights do not fit, TP or PP may be required.
- If model weights fit but the KV cache limits long-context concurrency, CP or DCP may help.
- If each replica has adequate memory but request volume is high, DP may be more effective.
- If the model is MoE and expert execution dominates, EP is relevant.
Increasing TP to solve every memory problem can create duplicated KV storage when KV-head count is small. CP directly addresses the sequence dimension that remains available after head sharding is exhausted.
4. Prefill and decode are different CP problems#
A request has two major inference phases.
Prefill processes the prompt and builds the initial KV cache. It can involve thousands or hundreds of thousands of input tokens. The system must compute attention for many query positions.
Decode generates output autoregressively. At each step, the model processes a small number of new query tokens—often one per active sequence—against a potentially very large existing KV cache.
These phases have different performance goals:
- Prefill CP often targets time to first token (TTFT) and prompt-processing throughput.
- Decode CP often targets KV-cache capacity, active concurrency, inter-token latency (ITL), and output throughput.
The phrase “context parallelism” can refer to different execution strategies depending on the phase. Do not assume that a prefill strategy and a decode strategy have identical communication patterns or should use the same degree of parallelism.
5. Prefill context parallelism: distribute the prompt#
Suppose a prompt contains 128,000 tokens and four GPUs participate in prefill context parallelism. Each GPU can process a 32,000-token segment.
Each rank computes query, key, and value projections for its local token positions. The system then needs enough key/value information to compute attention for those query positions.
Two broad approaches are useful to understand.
5.1 Partial query, full key/value#
Each rank owns a subset of query positions but obtains the full key/value sequence. It computes attention for its local queries against the full context.
Conceptually:
- Split the query sequence across ranks.
- Compute local Q, K, and V projections.
- Gather K and V so each rank has the full key/value sequence.
- Each rank computes attention for its local query positions.
- The resulting output fragments are assembled in the correct token order.
This approach can be effective when the complete K/V tensors are small enough to fit and the objective is to distribute query-side computation. It can reduce the amount of query work per rank, but gathering full K/V creates communication and memory costs.
5.2 Partial query, partial key/value#
For extremely long contexts, materializing the full K/V sequence on every rank may be too expensive. Each rank keeps a local K/V chunk, and the attention computation proceeds by exchanging chunks.
Ring-style attention is one way to organize this:
- Each rank starts with its local K/V chunk.
- It computes attention contributions for its local queries against the currently available K/V chunk.
- K/V chunks are transferred to neighboring ranks.
- Each rank accumulates contributions as new chunks arrive.
- The process continues until every required context chunk has contributed.
The online softmax formulation allows partial attention results to be combined without storing the full attention matrix. This is important because the attention scores themselves can be enormous for long sequences.
The trade-off is that ring execution introduces repeated communication steps. Whether it wins depends on sequence length, GPU interconnect, kernel efficiency, and how well communication overlaps with attention computation.
5.3 When to use which prefill strategy#
Partial query/full K/V is attractive when:
- The K/V representation can be gathered within memory limits.
- Communication cost is acceptable.
- Query-side parallelism is the primary need.
Partial query/partial K/V is attractive when:
- Full K/V gathering would consume too much memory.
- The context is exceptionally long.
- The topology supports efficient repeated transfers.
- The attention implementation can overlap transfer and compute.
These are workload- and implementation-dependent choices. Measure TTFT, peak memory, communication time, and total prefill throughput rather than selecting solely from sequence length.
6. Decode context parallelism: shard the KV cache by token position#
During decode, each request adds a small number of query tokens but attends over its full history. The KV cache grows with sequence length.
DCP partitions the KV cache along the sequence dimension. Each rank stores a different range or interleaved subset of token positions. For a request with a 200,000-token history and four DCP ranks, each rank might own approximately one quarter of the cached positions.
The decode attention computation becomes distributed:
- Each rank obtains the query information needed for its local KV shard.
- Each rank computes partial attention against its local KV positions.
- Partial outputs and normalization information are exchanged.
- The partial results are merged into the exact attention result.
- The resulting output continues through the model.
The key is to combine partial attention correctly. Attention is not a simple average of per-shard outputs because each shard can have a different maximum score and softmax normalization.
7. How distributed attention results are combined#
For a query vector , attention over all keys is:
If the context is split into shards, each rank computes attention over only its local keys and values. Simply averaging these local outputs is incorrect because each shard has its own softmax denominator.
A stable online-softmax merge can represent each shard's partial result using:
- : the maximum attention score on shard .
- : the sum of exponentials after subtracting .
- : the corresponding weighted-value sum after the same normalization.
For two partial groups A and B, define:
The final output is:
The same merge can be applied hierarchically across more than two shards. Implementations often communicate log-sum-exp (LSE) or equivalent normalization information together with partial outputs.
This explains why a DCP communication phase may include gathering query data, computing local attention, and combining partial outputs with an all-gather/reduce-scatter or a related collective sequence.
Important: the merge is part of the attention algorithm, not an optional approximation. An incorrect reduction changes the model output.
8. Why tensor parallelism alone can waste KV memory#
TP usually partitions KV heads across ranks. This works while each rank can own a distinct subset of KV heads.
But the number of KV heads is finite. Consider a model with four KV heads and eight TP ranks.
A simple head-based split can give each head to two ranks, resulting in duplicated KV storage. Increasing TP beyond the KV-head count does not necessarily reduce the KV-cache footprint further.
DCP uses the otherwise duplicated ranks to hold different context positions. Instead of two ranks storing the same KV head for every token, the ranks can store different sequence slices.
Example: GQA#
Suppose:
- Number of KV heads = 4.
- TP size = 8.
- Each KV head would otherwise be duplicated across two TP ranks.
There are two potential sequence shards per KV-head group. A DCP size of 2 can use this duplication to partition the context.
The exact constraints depend on the runtime and backend. In the documented vLLM GQA path, DCP size is bounded by the TP-to-KV-head ratio and must divide that ratio.
Example: MLA#
MLA compresses keys and values into a shared latent representation. In configurations where the effective KV-head count is one, ordinary TP can replicate that latent cache across all TP ranks.
DCP can partition the latent cache along sequence positions, allowing each rank to retain only its own context slice. During attention, the relevant latent information is transformed or consumed by the supported MLA attention path.
For an MLA model, DCP can therefore recover a large amount of memory that head-based TP cannot eliminate.
9. Worked capacity example#
Assume a model uses eight TP ranks and the full KV cache for one long request would occupy 32 GiB across the logical full-cache representation.
For simplicity, suppose the TP layout replicates the relevant KV data eight times because the model has a single effective KV head.
- Without DCP, each rank may need to hold the full 32 GiB representation.
- With DCP size 4, each rank in a DCP group may hold roughly one quarter of the sequence positions, or 8 GiB.
- With DCP size 8, each rank may hold roughly one eighth, or 4 GiB.
These are conceptual capacity figures. Actual per-GPU memory also depends on TP grouping, model architecture, metadata, temporary attention buffers, and implementation details.
The memory savings can increase the number of active requests. But DCP requires query distribution and partial-result aggregation, so the latency of an individual decode step can rise if communication is expensive.
The best choice depends on whether the freed memory enables enough additional concurrency to outweigh the coordination cost.
10. Communication cost: when DCP helps and when it hurts#
DCP trades replicated cache storage for distributed attention.
Benefits:
- Less duplicated KV cache per GPU.
- More memory available for active requests.
- Potentially higher concurrency for long-context workloads.
- Better scaling when TP has reached the KV-head sharding limit.
Costs:
- Query exchange or replication coordination.
- Partial attention output and normalization exchange.
- Additional collective synchronization.
- More sensitivity to GPU-to-GPU and cross-node interconnect performance.
- Potentially higher single-request latency when the context is short.
The communication overhead matters most when the attention computation per rank is too small to amortize it. This can happen with short contexts or low concurrency.
For long contexts, each rank performs useful attention work over its local KV segment, and the saved memory may allow the system to run more requests concurrently. This can improve aggregate throughput even if an individual decode step performs more communication.
Do not equate lower memory use with lower latency. Measure both.
11. Choosing the DCP degree#
Increasing DCP degree generally reduces the amount of KV cache stored per rank, but it also increases the number of participants in distributed attention.
A practical tuning sequence is:
- Establish the TP configuration needed for model weights and attention heads.
- Measure KV-cache duplication and memory pressure.
- Determine whether long-context concurrency is limited by KV memory.
- Test DCP degrees allowed by the architecture and runtime.
- Measure per-token decode latency and aggregate throughput at realistic concurrency.
- Compare the memory freed against the communication overhead.
- Select the smallest DCP degree that achieves the target capacity and SLO, unless a larger degree clearly improves the objective.
A simple first-order model is:
where is the effective sequence-sharding degree. This is an approximation, not a universal guarantee. Replication, uneven partitions, metadata, and runtime layouts can change the actual value.
Similarly, a rough latency model is:
The local attention term may decrease as the context is divided, but communication and merge costs increase. The real optimum is measured, not inferred from these equations alone.
12. Interleaved KV-cache sharding and dynamic growth#
A decode KV cache grows one token at a time. A static partition of the initial prompt is not enough; future tokens must be assigned to ranks consistently.
A sharding strategy must define:
- Which rank owns each token position.
- How new KV blocks are assigned as the request grows.
- How block tables and cache metadata describe distributed ownership.
- How partial cache events and attention kernels interpret the global sequence.
- How requests with different lengths are handled.
An interleaved sharding strategy can distribute future token positions naturally across ranks, avoiding the need to move all newly appended positions to one contiguous owner. The exact layout is runtime-specific.
The physical block size and the effective attention block size can differ when context parallelism is enabled. For example, a physical block of 16 tokens distributed over four ranks can represent a larger logical sequence span. Monitoring and debugging tools must distinguish local physical allocation from the effective global token coverage.
When enabling DCP, verify the runtime's reported effective attention block size and confirm that cache events, block tables, and attention backends agree on the layout.
13. Topology matters#
Context sharding creates communication between the GPUs that own different sequence chunks. The performance depends heavily on where those GPUs are located.
Prefer, where practical:
- GPUs within the same NVLink/NVSwitch domain for latency-sensitive collective communication.
- A topology-aware grouping that avoids unnecessary cross-node transfers.
- Consistent rank placement across model layers and attention groups.
- Enough network bandwidth for the expected concurrent request volume.
A DCP group spanning multiple nodes may reduce KV memory further, but the added network latency and collective overhead can erase the benefit for interactive decode.
A useful experiment compares:
- DCP within one node.
- DCP across nodes.
- The same model and request trace.
- Identical concurrency and sampling parameters.
Measure p50, p95, and p99 ITL, not just aggregate tokens per second. A configuration that raises throughput but causes unacceptable tail latency is not a valid serving improvement for an interactive workload.
14. Combining CP with TP, DP, and disaggregated serving#
CP is not a replacement for every other scaling method.
A common design is:
- TP for weight and attention-head sharding.
- DCP for sequence-dimension KV-cache sharding.
- DP for independent request replicas.
- EP for expert layers in MoE models.
The groups and rank layout must be coordinated. Increasing one degree can change the available choices for another. For example, DCP constraints may depend on TP size and the number of KV heads.
Disaggregated prefill/decode is a separate architectural decision: it places the two inference phases on different worker pools and transfers KV state between them. CP or DCP can be used within one or both pools, but disaggregation does not itself shard the sequence dimension.
Do not confuse:
- Disaggregation: separates phases or services.
- Context parallelism: distributes context computation and/or KV ownership.
- Prefix caching: reuses previously computed KV blocks.
- KV offloading: moves cache data to another memory tier.
- DCP: specifically partitions decode-time KV context across GPUs.
These techniques may complement one another, but their costs and ownership semantics must be evaluated together.
15. Benchmarking context parallelism correctly#
A valid comparison must hold the workload and hardware constant while changing the context-parallel configuration.
Build a benchmark matrix with:
- Prompt lengths: short, medium, long, and extreme.
- Output lengths: short and long.
- Concurrency: low, target, and peak.
- Model attention type: GQA or MLA.
- TP size and DCP degree.
- Intra-node and cross-node topology.
- Prefill and decode measurements separately.
- Mixed request lengths and realistic arrival patterns.
Measure:
- TTFT.
- ITL p50, p95, and p99.
- End-to-end request latency.
- Prompt and output tokens per second.
- Maximum sustainable concurrency.
- KV-cache occupancy and per-rank allocation.
- GPU memory headroom.
- Communication and collective time.
- GPU utilization and attention-kernel time.
- Preemptions, queueing, and failed requests.
For DCP, record the KV-cache capacity at which the system reaches its concurrency limit. A benchmark that measures only one request at a time may miss the principal benefit: the ability to keep more long-context requests resident.
Use the same prompt traces and output-length distribution for every configuration. Warm up the model, separate initialization from steady-state timing, repeat runs, and report the hardware and runtime versions.
16. Numerical decision example#
Suppose a service runs eight GPUs and receives long-context requests.
Baseline TP:
- Each GPU can host 20 long-context requests before KV memory is exhausted.
- The service sustains 160 concurrent requests across the eight GPUs.
- Decode ITL p95 is 45 ms.
With DCP:
- KV memory per rank falls enough to support 32 requests per GPU.
- The service can now host 256 concurrent requests.
- Communication increases p95 ITL to 49 ms.
- Aggregate output throughput rises by 35%.
Is DCP better?
It depends on the SLO. If the p95 ITL limit is 50 ms and the goal is higher long-context throughput, the DCP configuration may be a good trade. If the service requires p95 ITL below 45 ms, it fails the latency target even though throughput improved.
Now suppose DCP p95 rises to 65 ms. The additional concurrency may not justify the latency regression for an interactive product. The team should try a smaller DCP degree, a faster topology, or a different request-placement policy.
The decision should be based on SLO-compliant goodput, not the largest possible KV-cache capacity.
17. Common mistakes#
Using DCP when the KV cache is not the bottleneck. If the model is compute-bound or requests are short, the communication overhead may make performance worse.
Assuming TP always reduces KV memory. TP can hit the KV-head limit and duplicate cache storage. Inspect actual per-rank KV allocation.
Choosing the maximum DCP degree by default. More shards mean more coordination. Sweep supported values under the real workload.
Averaging partial attention outputs directly. Correct distributed attention requires normalization-aware merging, such as online-softmax/LSE combination.
Ignoring prefill/decode differences. Prefill CP and decode CP have different compute and communication patterns. Benchmark them separately.
Ignoring topology. A cross-node collective can be much more expensive than an intra-node transfer. Map ranks to actual GPU links.
Using only short prompts in benchmarks. DCP's main capacity benefit appears with long contexts and meaningful concurrency.
Ignoring dynamic KV growth. The cache must remain correctly sharded as tokens are appended. Validate block ownership and effective block-size reporting.
Reporting only throughput. More throughput can come with worse ITL or tail latency. Report both capacity and interactivity.
Treating CP as a substitute for disaggregation. They solve different problems and can be combined, but one does not imply the other.
18. Production rollout checklist#
- [ ] Identify whether KV-cache capacity or attention bandwidth limits the workload.
- [ ] Record model attention architecture, KV-head count, and TP layout.
- [ ] Measure actual KV-cache duplication across ranks.
- [ ] Confirm that the chosen CP/DCP degree is supported by the runtime and attention backend.
- [ ] Verify correct query distribution and partial-attention merge.
- [ ] Validate dynamic KV-cache growth and block ownership.
- [ ] Map CP ranks to the actual NVLink and network topology.
- [ ] Benchmark prefill CP and decode CP independently.
- [ ] Replay realistic long-context traces at target concurrency.
- [ ] Measure TTFT, ITL p50/p95/p99, throughput, and maximum concurrency.
- [ ] Monitor per-rank KV occupancy, communication time, and memory headroom.
- [ ] Canary the configuration and compare SLO-compliant goodput.
- [ ] Keep a tested rollback configuration.
19. Key takeaways#
- Context parallelism distributes token positions across GPUs instead of relying only on attention-head sharding.
- Prefill CP distributes prompt processing; decode CP distributes KV-cache ownership and attention over long histories.
- DCP is especially useful when TP has reached the KV-head sharding limit and KV cache is duplicated across ranks.
- Distributed attention must merge partial outputs with correct softmax normalization; averaging shard outputs is not correct.
- More DCP ranks reduce per-rank cache footprint but add communication and synchronization.
- The best degree depends on model architecture, sequence length, concurrency, GPU topology, and latency SLOs.
- Benchmark long-context concurrency and ITL together. Memory savings are valuable only when they improve the service's actual objective.
The practical question is not “How many GPUs can I add to context parallelism?” It is “How much KV capacity and useful concurrency does each additional context shard buy, and what latency and communication cost does it introduce?”
References
- 1.vLLM — Context Parallel Deploymentdocs.vllm.ai
- 2.
- 3.vLLM — Parallelism and Scalingdocs.vllm.ai
- 4.
- 5.
- 6.vLLM — Optimization and Tuningdocs.vllm.ai
Related questions
- How does Decode Token Parallelism (TKNP) decouple attention ownership from model-weight placement to scale high-concurrency, long-context LLM decoding across nodes?
- How do you design hierarchical KV-cache offloading for sparse-attention LLM decoding across GPU HBM, host DRAM, and scale-up memory pools?
- How do you optimize expert-parallel communication and load balancing for low-latency Mixture-of-Experts (MoE) LLM inference?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents