Attention Architectures for Long-Context LLMs: KV Cache and Inference Cost Trade-offs

    When large language models handle longer contexts, the first bottleneck is usually memory, not compute. During inference, the model must store a Key and Value for every processed token—the KV cache—and attention architecture directly determines its size. This article compares MHA, MQA, GQA, and MLA, explains the memory math behind each, and covers techniques for scaling to million-token contexts, training-side optimizations, inference cost calculation, and prefix caching.

    When a large language model needs to handle longer contexts, the first bottleneck is usually memory, not compute. During inference, the model must store a Key and Value for every token it has processed—the KV cache. The longer the context, the larger the cache. The choice of attention architecture directly determines the size of this cache.

    This article does not make judgments about version-specific details of any particular model. Architecture changes, parameter counts, and training data should always be verified against the official technical reports or papers. What follows are the general trade-offs of several mainstream approaches.

    Why the KV Cache Becomes the Bottleneck

    In standard Multi-Head Attention (MHA), every attention head has its own Key and Value. The cache size per token can be estimated as:

    Cache bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per value

    The factor of 2 accounts for storing both Key and Value. Consider a hypothetical configuration: 64 layers, 64 KV heads, head dimension 128, and FP16 precision (2 bytes per value). That works out to roughly 2 MB per token, or about 256 GB for a 128K context—more than a single GPU can hold. These numbers are only meant to illustrate the order of magnitude, not any real model.

    Comparing Three Approaches

    Multi-Query Attention (MQA) lets all query heads share a single set of Keys and Values, reducing the KV head count to 1. With the same configuration, the cache drops to about 32 KB per token, or roughly 4 GB for a 128K context. Memory pressure falls dramatically, and memory bandwidth usage during decoding drops along with it. The cost is that heads lose independent key-value representations, which can weaken the ability to distinguish fine-grained information in long contexts. Any quality loss must be confirmed through actual evaluation.

    Grouped-Query Attention (GQA) sits in between. It divides query heads into groups, with each group sharing one set of KV. The number of groups sets the balance point between cache size and representational capacity, and it is currently adopted by many open-source models.

    Multi-head Latent Attention (MLA) takes a different approach: it compresses the KV into a low-dimensional latent vector for storage and reconstructs it through an up-projection matrix at use time. Assuming a latent dimension of 512 plus a 64-dimensional positional encoding component, each token takes about 1,152 bytes per layer (FP16). Across 64 layers that is roughly 72 KB, or about 9 GB for a 128K context. MLA trades compression for cache space while preserving multi-head expressiveness, but every computation pays an extra up-projection cost.

    The trade-offs can be summarized as follows: MQA has the smallest cache but the tightest constraint on expressiveness; MLA balances cache and expressiveness at the cost of more computation; GQA is a common middle-ground engineering choice. The relative quality of the three depends on model scale, training methodology, and evaluation tasks—no single ranking applies to every scenario.

    Pseudocode Examples

    The following code illustrates data flow only. It omits masking, rotary position embeddings, and other details, and cannot be run directly.

    1. import math
    2. import torch
    3. import torch.nn.functional as F
    4. # Multi-Query Attention: all query heads share one set of K and V
    5. # query: [batch, num_heads, seq_len, head_dim]
    6. # shared_key, shared_value: [batch, 1, seq_len, head_dim]
    7. def mqa_forward(query, shared_key, shared_value, head_dim):
    8. scores = torch.matmul(query, shared_key.transpose(-2, -1)) / math.sqrt(head_dim)
    9. weights = F.softmax(scores, dim=-1)
    10. return torch.matmul(weights, shared_value)
    1. # Multi-head Latent Attention: only low-dimensional latent vectors are cached
    2. # latent_cache: [batch, seq_len, latent_dim], e.g., latent_dim = 512
    3. # k_up_proj, v_up_proj: up-projection modules that reconstruct per-head K and V
    4. # After reconstruction, standard MHA runs—so every decode step pays an extra up-projection
    5. def mla_forward(query, latent_cache, k_up_proj, v_up_proj, num_heads, head_dim):
    6. batch, seq_len, _ = latent_cache.shape
    7. key = k_up_proj(latent_cache).view(batch, seq_len, num_heads, head_dim).transpose(1, 2)
    8. value = v_up_proj(latent_cache).view(batch, seq_len, num_heads, head_dim).transpose(1, 2)
    9. return standard_attention(query, key, value, head_dim) # standard MHA, not expanded here

    What It Takes to Reach Million-Token Contexts

    Million-token contexts are not achieved by any single technique, but by stacking several—each with its own cost.

    1. Positional encoding extrapolation: methods like RoPE scaling let the model operate at positions beyond its training length. The limitation is that quality degrades more the further you exceed the training length, so long-text evaluation is needed to verify.
    2. KV cache management: paged management, or quantizing the cache to FP8 or INT8. The limitation is that quantization may hurt accuracy and requires regression testing.
    3. Chunked prefill: splitting very long prompts into segments computed step by step, reducing peak memory and latency jitter. The limitation is dependencies between chunks, which increase scheduling complexity.
    4. Sparse or sliding-window attention: each position attends to only part of the history. The limitation is that you must decide which historical information can be dropped—wrong decisions directly hurt quality.
    5. Retrieval augmentation: chunking long material, retrieving relevant pieces, and placing only those in context. The limitation is that retrieval recall sets the quality ceiling; missed recalls produce incomplete answers.

    System-Level Optimizations on the Training Side

    When training very large models, gradient synchronization, communication overhead from tensor parallelism, and memory fragmentation all affect overall efficiency. The optimizer, operator fusion, and communication strategy interact with one another, so speeding up one component does not necessarily improve the whole. Whether an optimization is effective should be judged by end-to-end training throughput, convergence speed, and final metrics—not by the latency of a single operator.

    How to Calculate Inference Cost

    The core formula for per-unit inference cost is: cost per million tokens = GPU hourly cost ÷ tokens processed per hour × 1,000,000.

    Here is a hypothetical example. If a single GPU costs 10 yuan per hour and total throughput is 2,000 tokens per second, that is about 7.2 million tokens per hour, giving a unit price of roughly 1.39 yuan per million tokens. Actual throughput varies with batch size, context length, and request distribution, so it must be measured in practice. When accounting, you should also distinguish input from output tokens and record time to first token (TTFT), throughput, and concurrency together—otherwise numbers from different solutions are not comparable.

    Prefix Caching and Billing

    During inference, computing prefixes such as system prompts and fixed documents often consumes a large share of resources. When a request hits the prefix cache, the system can skip that computation, reducing TTFT and compute consumption. Providers often use this to