LLM Architecture Selection and Infrastructure Engineering for Long Context
This article explains how to choose attention mechanisms (MHA, MQA, GQA, MLA) for large language model deployment, how to estimate KV cache memory for million-token contexts, and which infrastructure optimizations—parallelism strategies, paged KV cache, prefix caching, and cache-aware routing—matter most in practice. It is written for developers responsible for model selection and inference deployment. All figures are illustrative assumptions; always verify against official technical reports and your own benchmarks.
Over the past year, competition in large language models has shifted from isolated architectural innovation to the co-design of architecture, inference frameworks, and hardware. Whether a model can run in production—and run affordably—often depends on how well the attention mechanism, parallelism strategy, and cache management work together. This article is written for developers who need to select and deploy models. It covers the trade-off logic behind attention mechanisms, provides a method for estimating GPU memory in long-context scenarios, and lists practical infrastructure checkpoints. All numbers in this article are illustrative assumptions; for actual selection, refer to the official technical report of each model and your own benchmark results.
How Attention Mechanisms Have Evolved
The original Transformer uses multi-head attention (MHA). Each query head has its own keys (K) and values (V), giving it the strongest expressive power. However, during inference, every token’s K and V must be cached—the KV cache. As context grows, the KV cache scales linearly with sequence length and quickly consumes GPU memory.
Multi-query attention (MQA) lets all query heads share a single set of K and V. The KV cache shrinks to a few percent of its original size, and memory bandwidth pressure drops significantly—at the cost of some expressive power. Grouped-query attention (GQA) sits between the two: query heads are divided into groups, and each group shares one set of K and V. Many open-source models today adopt GQA.
Multi-head latent attention (MLA) projects K and V into a low-dimensional latent space for storage and reconstructs them during computation. It strikes a good balance between cache size and expressive power, but requires additional decompression matrix operations at inference time and has a more complex memory access pattern.
None of these four mechanisms is absolutely superior. The choice depends on three factors: context length, memory budget, and the ratio of compute to bandwidth on your hardware.
Choosing Between MLA and MQA
One view holds that some newer models have re-evaluated the MLA-versus-MQA trade-off in large-parameter, ultra-long-context scenarios. One explanation: as total model parameters keep growing, the system bottleneck may shift from memory capacity to communication and memory access efficiency. The extra matrix multiplications MLA adds during decoding can amplify latency on bandwidth-constrained hardware. MQA has a more regular memory access pattern and cooperates more easily with communication overlap and distributed scheduling.
This explanation is plausible, but it only holds under specific conditions. When evaluating, check the following four points.
- Hardware: What are the GPU memory bandwidth, inter-GPU interconnect (such as NVLink or PCIe), and inter-node network bandwidth? The tighter the bandwidth, the more prominent the cost of MLA’s extra computation.
- Parallelism configuration: What is the tensor parallelism degree? The higher the degree, the less KV each GPU handles, and MQA’s advantage may diminish.
- Context length: At 8K versus 1M tokens, the KV cache’s share of GPU memory differs dramatically. In short-context scenarios, the cache is usually not the main bottleneck.
- Measurement methodology: When comparing, fix batch size, input/output lengths, and precision, and compare only one metric at a time—either throughput or time to first token.
Therefore, no single mechanism should be treated as the universal conclusion for all new models. The more reliable approach is to run comparative tests with your own workload.
Estimating Memory for Million-Token Contexts
KV cache size can be estimated with the following formula:
Bytes per cached token = 2 × number of layers × number of KV heads × dimension per head × bytes per element
The factor of 2 accounts for storing K and V separately. Consider a hypothetical configuration: 60 layers, head dimension of 128, using BF16 (2 bytes per element).
- With 64 KV heads (close to MHA), each token takes about 1.97 MB; one million tokens require roughly 1.97 TB.
- With 8 KV heads (typical GQA), each token takes about 245 KB; one million tokens require roughly 246 GB.
- With 1 KV head (MQA), each token takes about 30 KB; one million tokens require roughly 31 GB.
These numbers only illustrate orders of magnitude and do not represent any real model. For actual estimation, plug in the model’s real layer count, head count, precision, and batch size. Also note that each concurrent request has its own KV cache—higher concurrency means greater memory pressure.
Model weights also occupy memory. Assuming 1.6T total parameters, FP8 storage requires about 1.6 TB and BF16 about 3.2 TB. With 80 GB of memory per GPU, weights alone require at least 20 GPUs (FP8), excluding activations and framework overhead. This means tensor parallelism and pipeline parallelism typically must be used together, and very large models may also incorporate expert parallelism.
What to Watch in Infrastructure Optimization
- Parallelism strategy: Tensor parallelism suits high-bandwidth intra-node interconnects; pipeline parallelism suits cross-node partitioning. Cross-node communication latency must be hidden through compute-communication overlap, or GPUs will sit idle for long stretches. Use a profiler to observe GPU utilization and communication wait time.
- Memory allocation: Paged KV cache management (in the spirit of PagedAttention) reduces memory fragmentation and lets requests of different lengths share a memory pool. Metrics to check include memory utilization, the number of preempted requests, and maximum concurrency. “Zero fragmentation” is hard to achieve in practice; rely on measured fragmentation rates.
- Prefix caching: System prompts, knowledge base snippets, and multi-turn conversation history recur frequently. Prefix caching reuses previously computed KV to avoid redundant computation. The key metric is cache hit rate, which directly affects time to first token and per-request cost.
- Cache-aware routing: In multi-instance deployments, requests should be routed preferentially to instances that already hold the corresponding prefix cache. Otherwise, load balancing can degrade hit rates. Eviction policies should also be designed around access frequency and cache lifetime.
- Billing and cost: Some providers differentiate pricing based on input cache hits. If your application has a large volume of repeated prefixes, first verify the provider’s official rules—including billing units, hit determination criteria, and effective dates—before estimating costs. Do not assume all providers offer the same discounts.
When troubleshooting, check in this order: first whether GPU utilization is low, then communication time, then memory utilization and fragmentation, and finally cache hit rate. Most performance problems can be localized within these four metrics.
Three Questions for Model Selection
When selecting a model, start by answering three questions.
First, what is the maximum target context length? If you only need a few thousand tokens, cache pressure from GQA or MHA is usually manageable, and selection can weigh model capability more heavily. If you need to support million-level contexts, the cache structure becomes the primary constraint.
Second, can your own hardware handle it? Check the memory budget against weight size, parallelism degree, and KV estimates, then verify whether bandwidth and interconnects can meet peak demand.
Third, how high is the prefix repetition rate in your workload? The higher the repetition, the greater the payoff from prefix caching and cache-aware routing. In that case, the inference framework’s caching support may matter more than benchmark scores on paper.
The evolution of large models shows that systems engineering capability is becoming a competitive moat. There is no universal answer when choosing an architecture. Only by comparing attention mechanisms, parallelism strategies, and cache management side by side—and validating with real workloads—can you make a decision that balances performance and cost.
