Long-Context LLM Inference: KV Cache Compression and 4-bit Quantization
This article explores technical strategies for optimizing long-context large language model (LLM) inference, addressing the high costs associated with memory capacity and bandwidth. It breaks down three primary bottlenecks—memory capacity, memory bandwidth, and scheduling overhead—and details corresponding solutions such as KV cache compression, kernel fusion, and 4-bit quantization. Additionally, it covers the co-design of model architecture and product metrics, engineering practices for multimodal and Agent scenarios, and methodologies for comprehensive performance evaluation.
I. Background: Why Long-Context Inference is Costly
Large language model (LLM) inference is typically divided into two phases. The prefill phase processes the input prompt all at once; it is computationally intensive but highly parallelizable. The decode phase generates output tokens one by one. For every token generated, the model must read all weights and the historical KV cache, resulting in high memory access volume and low computational intensity. When the context length reaches hundreds of thousands or even a million tokens, the bottleneck in the decode phase often lies not in compute power, but in GPU memory capacity and bandwidth.
The KV cache stores historical key-value vectors to avoid redundant calculations in the attention mechanism. Its size is proportional to the number of layers, KV heads, head dimensions, sequence length, and batch size. The calculation formula is as follows:
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, dtype_bytes=2):# The coefficient 2 means K and V are each saved oncereturn 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytesGB = 1024 ** 3# The following is a hypothetical configuration to illustrate the scale, not parameters of a specific modelfull = kv_cache_bytes(layers=60, kv_heads=8, head_dim=128,seq_len=1_000_000, batch=1, dtype_bytes=2)print(f"FP16 KV cache is about {full / GB:.1f} GB")
Under the above hypothetical configuration, the KV cache for a single million-token sequence exceeds 200 GB. The model weights themselves also occupy a massive amount of memory. Therefore, long-context services must simultaneously solve three types of problems: whether memory capacity is sufficient, whether the memory access volume per token can be reduced, and whether the scheduling overhead of each decoding step can be compressed.
The following sections discuss the technical measures corresponding to these three types of problems and provide engineering validation methods.
II. Problem Breakdown: Three Bottlenecks and Corresponding Solutions
Breaking down decoding latency, it roughly consists of three parts:
- Memory Capacity Bottleneck: The KV cache grows linearly with the context, determining the maximum concurrency and maximum context length a single GPU can serve. The corresponding solution is KV cache compression.
- Memory Bandwidth Bottleneck: To generate one token, weights and the KV cache must be read from memory. The smaller the byte size of weights and the KV cache, the shorter the read time. The corresponding solution is quantization.
- Scheduling and Launch Overhead: A single network layer contains many small operators. Launching a kernel separately for each operator introduces extra launch latency and read/write operations for intermediate results. The corresponding solution is kernel fusion.
These three measures interact with each other. KV cache compression can increase concurrency, quantization reduces the read volume per step, and fusion minimizes intermediate data movement. They must be adjusted together within the same evaluation system rather than being optimized in isolation.
III. KV Cache Compression
3.1 Reducing KV Heads Structurally
In standard Multi-Head Attention (MHA), each query head corresponds to an independent set of keys and values. Grouped-Query Attention (GQA) allows multiple query heads to share the same set of key-value heads, while Multi-Query Attention (MQA) has all query heads share a single set. Such designs reduce the KV cache proportionally. For example, reducing the number of KV heads from 64 to 8 shrinks the KV cache to one-eighth of its original size. The trade-off is a potential decrease in model expressiveness, so the architecture must be determined during the training phase rather than simply replacing it during inference.
3.2 Low-bit KV Cache Storage
KV vectors can be stored in 8-bit or lower bit-widths and then dequantized to computational precision upon reading. The key to this approach lies in the quantization granularity. Setting scale factors per-channel or per-group typically retains precision better than sharing a single scale factor across the entire tensor.
3.3 Selective Retention of Historical Information
Some methods retain only important historical tokens based on attention scores or positional rules, or use coarser representations for distant history. These methods can significantly reduce cache size, but it is necessary to verify whether the quality of long-distance dependency tasks (such as cross-paragraph QA or codebase retrieval) is affected.
3.4 Theoretical Upper Bound of Compression Ratio
Assuming the KV cache is compressed to one-sixth of its original size, theoretically, about six times the KV usage can be accommodated under the same memory budget. The actual concurrency improvement will be lower than this figure due to weight occupation, activation memory usage, fragmentation, and the inherent overhead of scheduling policies. These items should be accounted for together during estimation, rather than looking only at the KV cache itself.
def max_concurrent_seqs(total_gb, weight_gb, act_gb, per_seq_kv_gb):free = total_gb - weight_gb - act_gbreturn max(int(free // per_seq_kv_gb), 0)# Assumption: 80 GB memory, 40 GB weights, 6 GB activation reserved, 4 GB KV per sequenceprint(max_concurrent_seqs(80, 40, 6, 4.0)) # Before compression: 8print(max_concurrent_seqs(80, 40, 6, 4.0 / 6)) # After compression: about 39
This example shows that the concurrency benefits of KV compression can be amplified or weakened by weight occupation. The larger the weights, the less space is left for the KV cache, meaning concurrency gains from compression depend heavily on the actual memory budget.
IV. Network-wide Fusion and Kernel Optimization
4.1 Motivation for Fusion
During a single decoding step, operations like attention, normalization, feed-forward networks, and residual connections are typically split into multiple kernels. Each kernel must read inputs from memory and write outputs back. After fusion, intermediate results can remain in on-chip caches or registers, reducing read/write operations and lowering kernel launch counts.
4.2 The Megakernel Approach
A Megakernel merges the extensive computations of one or more decoding layers into a single or a few persistent kernels, handling inter-layer synchronization and scheduling internally. Its core benefits are threefold: reducing launch overhead, reducing memory round-trips for intermediate results, and allowing better overlap of computation and memory access.
The difficulty with such schemes lies in synchronization. Data dependencies exist between layers, requiring precise barriers or atomic operations inside the kernel to ensure correctness. Improper synchronization design can lead to deadlocks or data races. Therefore, during development, incremental validation should be done on small-scale configurations before scaling to the full model.
4.3 Verification Principles for Fusion
Two types of checks must be performed after fusion. The first is numerical consistency, comparing the fused output layer-by-layer against an unfused baseline; the error should be kept within a reasonable range for the given precision. The second is boundary checking, covering different sequence lengths, batch sizes, and the last incomplete block. Kernels that only pass standard-length tests are highly prone to errors at boundary lengths.
V. 4-bit Quantization
5.1 Basic Forms of Quantization
Weight quantization maps floating-point numbers to low-bit integers. A common practice for 4-bit symmetric quantization is to calculate scale factors per group, saving one scale value per group while storing rounded integer elements within the group. Smaller groups yield higher precision but increase the storage overhead of scale factors. Common group sizes range from 32 to 128, requiring a trade-off between precision and storage overhead.
def quantize_group_int4(weights, group_size=32):q_all, scales = [], []for i in range(0, len(weights), group_size):g = weights[i:i + group_size]max_abs = max(abs(x) for x in g) or 1e-8scale = max_abs / 7 # int4 range is -8..7, take 7 for the positive sideq = [max(-8, min(7, round(x / scale))) for x in g]q_all.extend(q)scales.append(scale)return q_all, scalesdef dequantize_int4(q, scales, group_size=32):return [q[i] * scales[i // group_size] for i in range(len(q))]w = [0.12, -0.53, 0.07, 0.91, -0.44, 0.02, 0.33, -0.08]q, s = quantize_group_int4(w, group_size=4)w_hat = dequantize_int4(q, s, group_size=4)err = sum(abs(a - b) for a, b in zip(w, w_hat)) / len(w)print(f"Mean Absolute Error: {err:.4f}")
5.2 Benefits and Costs of 4-bit
Reducing weights from 16-bit to 4-bit theoretically cuts weight storage and read volume to a quarter. When the decode phase is bandwidth-bound, this change directly reflects in the time taken per step. The costs are twofold: first, quantization errors may accumulate and affect generation quality; second, dequantization itself requires computation, and a poor implementation can offset some of the bandwidth gains.
5.3 Preventing Quality Regression
Before and after quantization, perplexity, benchmark task scores, and business-side human evaluations should be compared. For precision-sensitive tasks like code generation, mathematical reasoning, and structured output, it is recommended to set up a separate regression test suite. If a specific layer is particularly sensitive to quantization, it can be kept at a higher precision. Such mixed-precision strategies are very common in engineering.
VI. Co-design of Model Architecture and Product
6.1 Why Co-design is Necessary
The model architecture determines the computational and memory access patterns of inference. The number of attention heads, layers, experts, and whether sparse activation is used all affect subsequent compression and fusion approaches. If inference optimization is only considered after model training is complete, many optimization spaces will be sealed off by the architecture itself. Therefore, model designers need to understand inference constraints in advance, and inference engineers also need to understand the model’s training objectives.
6.2 Reverse-engineering Design from Product Metrics
Metrics that the product side cares about typically include time-to-first-token (TTFT), decode throughput, single-GPU concurrency, maximum context length, and output quality. These metrics constrain each other. For example, compressing the KV cache to improve concurrency might harm the quality of long-distance tasks; using more aggressive quantization to increase throughput might raise the error rate for structured outputs. Co-design requires writing these metrics as explicit constraints and making trade-offs during the design phase.
6.3 Iterative Closed Loop
Co-design is typically a closed loop. Real load distributions fed back by the product—such as input length percentiles, the ratio of multi-turn conversations, and tool invocation frequency—will in turn affect the model’s training data composition and inference parameters. Measurement results from the inference side, such as time consumption per phase and memory peaks, are used to revise architectural design. The shorter the loop, the easier it is for the system to converge to a usable balance point.
VII. Engineering Considerations for Multimodal and Agent Scenarios
7.1 Context Overhead of Multimodal Inputs
Images, videos, or audio are converted into a large number of tokens after encoding. A single high-resolution image might occupy hundreds or even thousands of context positions, rapidly consuming the KV cache budget. In engineering, resolution can be selected based on task requirements, encoding caches can be used for repeated images, and repeated injection of the same visual input in multi-turn conversations should be avoided.
7.2 Cache Reuse in Agent Scenarios
Agents usually need to repeatedly call tools, and each round will carry system prompts, tool descriptions, and historical conversations. These prefix contents are highly repetitive, making them suitable for prefix caching—saving the already computed prefix KV states for direct reuse in subsequent requests. The hit rate of prefix caching depends on the stability of the prompt structure. Placing variable content at the end and keeping templates consistent can significantly improve the hit rate.
7.3 Scheduling Strategies under Long Context
When long and short requests are mixed, long requests occupy a large amount of memory, slowing down the response of short requests. A common practice is to separate queues or set memory limits for individual requests, reserving certain concurrency slots for short requests. Scheduling strategies need to be set based on real traffic distributions rather than just looking at averages.
VIII. Evaluation Methodology
8.1 Metric System
The evaluation of inference services should at least include the following metrics:
- Time To First Token (TTFT): The time from request arrival to the first output token, primarily reflecting prefill efficiency.
- Time Per Output Token (TPOT) or Decode Throughput: Reflects the stable performance during the decode phase.
- Memory Peak and Concurrency: Reflects capacity limits.
- Quality Metrics: Includes regression suite scores, legality rates of structured outputs, and human evaluation results.
8.2 Measurement Considerations
Mixing TTFT and decode throughput together in calculations will mask the respective issues of each phase. The following code measures the two phases separately and uses warm-up requests to eliminate cold start effects.
import timedef benchmark(generate_stream, prompt, max_new_tokens=256, warmup=2, repeat=5):# generate_stream(prompt, n) should yield tokens one by one, implemented by the specific servicefor _ in range(warmup):for _ in generate_stream(prompt, max_new_tokens):passttft_list = []tpot_list = []for _ in range(repeat):start = time.time()first_token_time = Nonetoken_count = 0for _ in generate_stream(prompt, max_new_tokens):if first_token_time is None:first_token_time = time.time()ttft_list.append(first_token_time - start)else:token_count += 1if token_count > 0:tpot_list.append((time.time() - first_token_time) / token_count)print(f"Average TTFT: {sum(ttft_list)/len(ttft_list):.4f}s")print(f"Average TPOT: {sum(tpot_list)/len(tpot_list):.4f}s")
