Sparse Activation and Latent Attention Compression in Large Language Models: Engineering Practices
This article explains two techniques for reducing the cost of large language models. Sparse activation, implemented as Mixture of Experts, lowers the computation per token. Latent attention compression shrinks the key-value cache that grows during inference. The article covers how to estimate cache size, the routing and load balancing challenges of Mixture of Experts, how to measure training compute, and a deployment checklist.
1. Background
Large language models become more capable as parameter counts and training data grow. Scaling up also brings two direct costs: the floating-point operations (FLOPs) required for training, and the GPU memory and generation latency required for inference. When planning a model deployment, teams usually need to answer three questions. Can the same quality be achieved with less computation? How much GPU memory does each request consume during inference? How should the cache be managed in long-context scenarios?
Two main technical routes have emerged. The first is sparse activation. The model has a very large total parameter count, but each forward pass uses only a subset of those parameters. The typical implementation is the Mixture of Experts architecture. The second is compressing the key-value (KV) cache in attention, typically through low-rank latent representations. Sparse activation reduces computation, and cache compression reduces memory. The two can be combined.
2. Sparse Activation: Mixture of Experts
2.1 Basic Principle
Mixture of Experts (MoE) splits the feed-forward network into multiple expert sub-networks and adds a router. For each input token, the router scores the token based on its hidden state and selects only the top-scoring experts for computation. The remaining experts stay idle. As a result, model capacity and per-step compute cost can be designed separately. The total parameter count determines model capacity, and the number of parameters activated per token determines the compute cost of each step.
The benefit can be expressed with a simplified relationship. Let N be the total number of experts, k the number of experts activated per token, and p the parameter count of a single expert. The total parameter count is approximately N × p, and the feed-forward compute per token is roughly proportional to k × p. When N is much larger than k, growing model capacity does not raise compute cost proportionally.
2.2 Routing and Load Balancing
Routing design has two common challenges. The first is load imbalance. If a few experts are selected frequently, the others receive insufficient training, and the popular experts become bottlenecks. A common remedy is to add an auxiliary balancing term to the training loss that penalizes deviations in how often each expert is selected. The second is communication overhead. When experts are distributed across multiple devices, tokens must be dispatched to and gathered from those devices, so the routing strategy has to account for inter-device bandwidth.
The following simplified pseudocode illustrates the computation flow. Batching, capacity limits, and the balancing loss are omitted.
def moe_forward(x, router, experts, top_k):scores = softmax(router(x)) # Routing scores for each experttopk_scores, topk_idx = top_k_select(scores, top_k)out = zeros_like(x)for score, idx in zip(topk_scores, topk_idx):out += score * experts[idx](x) # Compute only the selected expertsreturn out
In practice, tokens need to be aggregated into batches to improve hardware utilization.
3. Inference Bottleneck: The Key-Value Cache
3.1 Estimating Cache Size
During autoregressive generation, the model must cache the key and value vectors of previous tokens. This is the KV cache. Its memory footprint can be roughly estimated as:
Cache bytes ≈ 2 × number of layers × KV heads per layer × head dimension × sequence length × bytes per element
For example, suppose a model has 40 layers, 8 KV heads per layer, a head dimension of 128, a sequence length of 32K tokens, and stores values in 16-bit floating point. The cache for a single request is then about 2 × 40 × 8 × 128 × 32768 × 2 bytes, or roughly 5.4 GB (decimal). These numbers are illustrative only. They show that when long contexts and concurrent requests combine, the cache can quickly become the largest consumer of GPU memory.
3.2 Low-Rank Latent Compression
The core idea of Multi-head Latent Attention is to avoid storing the complete keys and values for every head. Instead, the hidden state is projected into a lower-dimensional latent vector, and only that vector is cached. When computing attention, an up-projection restores the keys and values from the latent vector. The unit of caching changes from per-head keys and values to a smaller latent vector, which reduces memory use. The trade-off is additional projection computation, so memory savings must be balanced against compute cost.
Positional encoding needs separate handling. If position information is directly involved in the projection, the savings from compression are reduced. A common approach is to keep the components that require position awareness separate and compress the rest.
3.3 Evaluating Cache Compression
When evaluating cache compression, record three metrics together: memory footprint per request, time to first token, and tokens generated per second. Also verify on the same quality evaluation set that outputs show no significant degradation. This prevents resource metrics from being optimized at the expense of output quality.
4. Measuring Training Efficiency
When comparing the training cost of two models, parameter count alone is not enough. Training FLOPs is the recommended common measure. A widely used rule of thumb is:
Training FLOPs ≈ 6 × number of parameters involved in computation × number of training tokens
For sparse models, the parameter count should be the activated parameters rather than the total parameters. Under the same training budget, a sparse model can therefore often have a larger total capacity while keeping computation at an acceptable level.
This estimate ignores overhead from data processing, parallel communication, and failure retries. Actual wall-clock time also depends on hardware utilization, so the result should serve only as a reference when comparing options.
5. Quality Evaluation
When evaluating general capabilities, split the assessment by task. Chinese understanding, English understanding, code, mathematical reasoning, and instruction following should each use independent evaluation sets. A single leaderboard score rarely reflects real-world performance. Also check whether evaluation sets overlap with training data, since overlap can inflate results.
6. Deployment Checklist
- Analyze the distribution of concurrency and context length, and use it to estimate total cache size.
- Confirm whether the inference framework supports batched scheduling of sparse experts.
- Run stress tests on the target hardware, and record tail latency rather than only average latency.
- Set length limits and timeout policies for long-context requests.
- Apply safety and compliance filtering to outputs, and keep traceable logs.
- Establish regression evaluations, and re-run them after every model version change or quantization configuration change.
7. Summary
Sparse activation targets the computation bottleneck, while cache compression targets the memory bottleneck. The two solve different problems. Engineering teams should first measure which bottleneck dominates their workload, then choose the matching technique. They should validate quality with task-specific evaluations rather than deciding based only on parameter count or a single metric.
