KV Cache Broadcast Optimization on Domestic AI Accelerator Clusters
When context lengths reach the million-token scale and multimodal inputs add large volumes of visual tokens, a single request's KV cache can exceed the memory of one accelerator card. This article explains how to estimate KV cache memory usage, why point-to-point transfer becomes a bottleneck in parallel inference, and how to design an efficient KV cache broadcast scheme. It covers topology-aware hierarchical broadcast, communication–computation overlap, buffer management, synergy with low-precision and mixed-precision caching, Encode–Prefill–Decode (EPD) disaggregated architectures, performance evaluation methods, and practical rollout guidance with risk controls.
1. Background: Memory Pressure from Long Context and Multimodal Inference
Every time a large language model generates a new token, it must read the key and value vectors of all preceding tokens. These vectors are collectively known as the KV cache. The longer the sequence, the more memory the KV cache consumes. When the context length reaches the million-token scale, the KV cache of a single request can exceed the memory capacity of a single accelerator card.
Multimodal input makes the problem worse. After encoding, images and videos are converted into large numbers of visual tokens. Like text tokens, they consume sequence length and require their KV vectors to be cached.
KV cache memory usage can be estimated with a simple formula:
KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element
The factor of 2 accounts for the two tensors: key and value. The code below gives an illustrative calculation. The parameters are hypothetical values, not measurements from any specific model:
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, dtype_bytes):"""Estimate the number of bytes occupied by the KV cache."""return 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes# Assumptions: 64 layers, 8 KV heads, head dim 128, sequence length 1M,# batch size 1, BF16 (2 bytes)size = kv_cache_bytes(64, 8, 128, 1_000_000, 1, 2)print(f"{size / 1e9:.1f} GB") # Prints approximately 262.1 GB
Under these assumptions, the KV cache for a single request alone is about 262 GB, far beyond single-card memory. The inference system must therefore shard the KV cache across multiple cards, or store it in lower-precision formats. Once sharded, data exchange between cards becomes the new bottleneck—this is exactly the problem that KV cache communication optimization addresses.
2. The KV Communication Problem in Parallel Inference
2.1 Sharding and Replication Introduced by Tensor Parallelism
Tensor parallelism distributes attention heads across multiple cards for computation. Each card only stores the KV vectors it is responsible for, and local attention computation requires no extra communication. However, in two scenarios, data must flow across cards.
The first is Grouped Query Attention (GQA). When the number of tensor-parallel cards exceeds the number of KV heads, multiple cards must hold replicas of the same KV head group. The KV vectors produced by each new token must be synchronized to these replicas—a typical one-to-many distribution.
The second is inference-stage disaggregation. In architectures that separate prefill from decode, the KV cache computed by prefill nodes must be transferred to decode nodes. If the decode side has multiple replicas or worker groups, the same data must be sent to multiple receivers.
2.2 Why Point-to-Point Transfer Is Inefficient
The most straightforward approach is for the sender to transmit the data once to each receiver. If a KV block must go to 7 receivers, point-to-point transfer occupies the sender’s egress bandwidth 7 times, and latency grows linearly with the number of receivers. When a KV block reaches hundreds of megabytes, this overhead directly slows down time to first token.
The broadcast primitive in collective communication offers an alternative: a root node distributes data to the entire communication group, and underlying algorithms (such as ring or tree topologies) allow data to flow in parallel across multiple links, reducing single-point pressure.
3. Designing KV Broadcast
What follows describes common design approaches in the industry, not the full details of any specific implementation. A practical KV broadcast solution typically includes the following components.
3.1 Identifying Data Owners and Receiver Groups
Each KV block has an owner at creation time—the worker process that produced the block. The scheduler records the owner of each block and establishes communication groups for the worker processes that need it. Communication groups should be organized according to the physical topology wherever possible, keeping processes on the same node in one group to reduce cross-node traffic.
3.2 Topology-Aware Hierarchical Broadcast
Interconnect bandwidth between cards within a node is typically much higher than inter-node network bandwidth. A sensible approach is two layers: first broadcast within the node, then have a representative process from each node broadcast to other nodes. This way, the data volume crossing inter-node links depends only on the number of nodes, not on the number of cards per node.
3.3 Overlapping Communication with Computation
Broadcast can be initiated asynchronously. After initiation, compute units continue processing the current layer, and synchronization only happens when the data is actually needed. This overlap effectively hides communication latency, provided communication time does not exceed available computation time.
The following illustrative code shows the broadcast flow for a single KV block:
def broadcast_kv_block(block_id, owner_rank, group, kv_pool):"""Illustration: broadcast a KV block from its owner to all workers in the group that need it."""if group.rank == owner_rank:buf = kv_pool.read(block_id) # Read the local KV blockelse:buf = kv_pool.allocate_like(block_id) # Pre-allocate the receive buffergroup.broadcast(buf, src=owner_rank) # Collective broadcastif group.rank != owner_rank:kv_pool.write(block_id, buf) # Write into the local cachereturn buf
The asynchronous overlap pattern looks like this:
handle = group.broadcast_async(buf, src=owner_rank)compute_layer(layer_idx) # Compute the current layer while waiting for communicationhandle.wait() # Synchronize only before the data is actually needed
3.4 Buffer Management and Synchronization
Frequently allocating and freeing large buffers causes memory fragmentation. A common practice is to pre-partition a fixed-size buffer pool and track block lifecycles with reference counts or timestamps. Synchronization points must also be explicit; otherwise, receivers may read data that has not been fully written.
4. Synergy with Quantization and Mixed-Precision Caching
4.1 Precision Determines Communication Volume
Communication volume is proportional to the bytes per element. The table below compares several common formats:
| Format | Bytes per Element | Typical Trade-offs |
|---|---|---|
| BF16 | 2 | High precision, large memory and bandwidth footprint |
| FP8 | 1 | Halves bandwidth; requires scaling factors to maintain numeric range |
| INT8 | 1 | Halves bandwidth; requires quantization parameters; precision loss depends on calibration quality |
Take a 1 GB BF16 KV block as an example: switching to an 8-bit format reduces the data transferred per broadcast to about 500 MB, theoretically halving latency. The actual gain depends on whether communication is truly the bottleneck.
4.2 Common Mixed-Precision Caching Strategies
A common practice is to differentiate precision by position. Recent tokens near the current position are kept at higher precision because they influence the output more directly; earlier historical tokens are stored at lower precision. This achieves a balance among memory usage, communication volume, and accuracy.
Note that quantization error accumulates as the sequence grows, so output quality must be validated on target tasks—throughput numbers alone are not sufficient.
4.3 Impact of Weight and Activation Quantization
W8A8 means both weights and activations use 8-bit quantization. Weight quantization reduces the model’s own memory footprint; activation quantization affects the size of intermediate results and thus the precision of generated KV vectors. The combination must be validated through calibration and regression testing to avoid noticeable quality degradation in long-context scenarios.
5. Cluster Level: Separating Encode, Prefill, and Decode
Multimodal inference workloads differ greatly in their characteristics. Vision encoding is mainly compute-bound; prefill demands both compute and memory; decode depends more on memory bandwidth and involves very little computation per step. Placing all three in the same group of processes makes it hard to achieve good resource utilization across the board.
The Encode–Prefill–Decode (EPD) disaggregated architecture splits the three types of work into independent worker pools, each of which can scale independently based on queue length. This split has a direct consequence: the KV cache must be transferred frequently between the prefill and decode pools, which amplifies the payoff from communication optimization.
When designing an EPD system, pay attention to the following:
- Queue lengths and wait times between worker pools, to prevent any pool from becoming a bottleneck;
- KV cache transfer paths, prioritizing links within the same facility and the same node;
- Failure recovery mechanisms—how to re-fetch or recompute the KV cache when a decode node fails;
- Cold-start time for scaling, especially when model weights must be preloaded.
6. Performance Evaluation Methodology
6.1 Core Metrics to Watch
When evaluating inference performance, observe the following metrics together:
- Time to First Token (TTFT): the time from request arrival to the first output token;
- Time Per Output Token (TPOT): the average time to generate each token during decode;
- Throughput: tokens processed per unit of time;
- Peak memory: confirm that the KV cache and buffer pool stay within budget;
- Cost per token: derived from hardware price, power consumption, and throughput.
One reported practice cites roughly a 3x end-to-end performance improvement, with per-token cost broadly comparable to mainstream GPU solutions. These numbers depend on the specific model, workload distribution, and hardware configuration, and cannot be applied directly to other environments. Teams should re-benchmark on their own data.
6.2 Illustrative Benchmark Script
The code below demonstrates a simple benchmark framework for comparing metrics before and after optimization:
import timeimport statisticsdef run_benchmark(send_request, prompts, warmup=5):"""Illustration: send requests to the inference service and collect latency stats."""for p in prompts[:warmup]:send_request(p) # Warm up to exclude cold-start effectsttfts, tpots = [], []start_all = time.time()total_tokens = 0for p in prompts[warmup:]:result = send_request(p) # Returns TTFT, total time, and token countttfts.append(result["ttft"])n = result["num_tokens"]total_tokens += nif n > 1:tpots.append((result["total_time"] - result["ttft"]) / (n - 1))elapsed = time.time() - start_allreturn {"ttft_p50": statistics.median(ttfts),"tpot_mean": statistics.mean(tpots),"throughput_tok_s": total_tokens / elapsed,}
6.3 Verifying Correctness
Performance optimization must be premised on correctness. Under identical inputs and random seeds, compare outputs before and after optimization. For low-precision paths, measure deviations in output distributions or compare accuracy on benchmark datasets. If results show a systematic shift, roll back to a higher-precision configuration.
7. Rollout Recommendations and Risk Control
When rolling out KV broadcast optimization, proceed in the following order:
- First use profiling tools to confirm the bottleneck is indeed KV communication, not computation or data loading;
- Start with intra-node broadcast and verify correctness and gains;
- Then extend to cross-node hierarchical broadcast while observing network contention;
- Before introducing mixed-precision caching, run quality regression on a small-scale dataset;
- Finally, run end-to-end benchmarks of the full EPD-disaggregated setup and tune the size of each worker pool.
Major risks include: data read anomalies caused by synchronization errors, memory fragmentation from poorly configured buffer pools, long-tail latency of broadcast under network congestion, and quality degradation from low precision. Each risk should have corresponding monitoring metrics and a rollback plan—for example, recording latency percentiles for every broadcast operation, and keeping a one-click switch back to high precision for quantized paths.
8. Checklist
- Clearly identify the owner and receiver group of each KV block, aligned with the physical topology;
- Overlap broadcast with computation, and complete synchronization before using the data;
- Use pre-allocation and reuse for buffers;
- Validate low-precision paths through quality regression;
- Benchmarks cover TTFT, TPOT, throughput, and peak memory;
- Keep configuration switches that allow fast rollback.
