Reducing LLM Inference Costs with Sparse Activation and Latent Attention
This article explains two architecture approaches for lowering large language model inference costs: Mixture of Experts (MoE), which reduces per-token computation, and Multi-head Latent Attention (MLA), which compresses the KV cache. It covers routing, load balancing, parameter counting, memory estimation, and deployment considerations.
1. Background: Two Bottlenecks in LLM Inference Costs
The cost of LLM inference comes mainly from two sources. The first is forward computation, which scales with the number of parameters each token actually uses. The second is the GPU memory taken by the KV cache, which grows linearly with context length and batch size.
A dense model sends every token through all of its parameters, so the computation per token rises with model size. In long-context workloads, the KV cache often exhausts GPU memory before compute does, which limits the number of concurrent requests. Two common optimization routes address these bottlenecks. Sparse activation reduces the computation per token, and cache compression reduces memory use. The two solve different problems, so they can be combined.
2. Mixture of Experts (MoE): Separating Total and Active Parameters
MoE splits the feed-forward network into multiple experts. A gating network, called the router, scores each token and selects k experts to process it. The remaining experts add no computation cost for that token.
2.1 Routing Mechanism
Routing typically takes three steps:
- Compute a score for each expert for every token (a linear transformation followed by softmax);
- Select the top k experts with the highest scores;
- Renormalize the weights of these k experts, then compute the weighted sum of their outputs.
import torchimport torch.nn.functional as Fdef topk_router(hidden, gate_weight, k=2):"""hidden: [tokens, d_model]; gate_weight: [num_experts, d_model]"""logits = hidden @ gate_weight.T # [tokens, num_experts]probs = F.softmax(logits, dim=-1)topk_probs, topk_idx = torch.topk(probs, k, dim=-1)topk_probs = topk_probs / topk_probs.sum(dim=-1, keepdim=True)return topk_idx, topk_probs
2.2 Load Balancing
If routing concentrates on a few experts for a long time, the other experts sit idle, and training can become unstable. Common remedies include adding an auxiliary balancing term to the training loss, or setting a capacity limit for each expert. Tokens that exceed an expert’s capacity overflow to other experts or skip the layer. Some designs also keep shared experts that process every token and hold general knowledge, so the routed experts can focus on specific domains.
2.3 Relationship Between Parameter Count and Computation
Two kinds of parameter counts need to be distinguished:
- Total parameters determine model capacity and the memory needed to store the weights.
- Active parameters determine the computation per token.
For example, suppose a model has 100 billion total parameters and 10 billion active parameters per token. In FP16, the weights take about 100B × 2 bytes ≈ 200 GB. The forward computation per token is about 2 × 10B ≈ 20 GFLOPs, ignoring attention and other overhead.
MoE therefore reduces computation, not weight storage. Deployment still requires loading all experts, so the memory capacity requirement does not decrease.
3. Multi-head Latent Attention (MLA): Compressing the KV Cache
3.1 KV Cache Cost in Standard Multi-Head Attention
Standard multi-head attention caches the key (K) and value (V) vectors for every token at every layer. The number of cached elements per token per layer is:
2 × number of heads × head dimension
With many heads, the cache grows quickly.
3.2 Basic Idea of Low-Rank Compression
The core idea of MLA is to reconstruct K and V from a low-dimensional latent vector. The method works as follows:
- Project the hidden state down into a latent vector c_KV of dimension d_c, and cache only this vector;
- When computing attention, use up-projection matrices to recover K and V from the latent vector;
- In practice, the up-projection matrices can be merged into the query and output projection weights. This avoids explicit reconstruction and reduces intermediate computation.
3.3 Decoupled Rotary Position Embedding
Rotary position embedding (RoPE) applies to the key vectors. Combining it directly with low-rank compression would damage the representation of positional information. MLA therefore usually keeps a small set of extra key dimensions, d_r, dedicated to position information, and processes them separately from the compressed content. These dimensions also need to be cached.
As a result, the number of cached elements per token per layer is:
d_c + d_r
3.4 Numerical Example
Assume 32 heads with a head dimension of 128. Standard multi-head attention caches 2 × 32 × 128 = 8,192 elements per token per layer. If d_c = 256 and d_r = 32, the cache holds 288 elements, about 1/28 of the standard approach.
These settings serve only as a calculation example. They do not reflect any specific model.
4. Estimating Memory and KV Cache Size
Engineers often need to estimate memory usage for a given configuration. The script below compares the KV cache size of the two attention schemes in the same scenario.
def kv_cache_bytes(seq_len, num_layers, elems_per_token_per_layer,dtype_bytes=2, batch_size=1):return (batch_size * seq_len * num_layers* elems_per_token_per_layer * dtype_bytes)HEADS, HEAD_DIM, LAYERS, SEQ = 32, 128, 60, 32768mha_elems = 2 * HEADS * HEAD_DIM # K and Vmla_elems = 256 + 32 # latent d_c + decoupled RoPE key d_rfor name, elems in [("MHA", mha_elems), ("MLA", mla_elems)]:gib = kv_cache_bytes(SEQ, LAYERS, elems) / 1024**3print(f"{name}: {gib:.2f} GiB per sequence")
Running the script gives about 30.00 GiB for MHA and 1.05 GiB for MLA, per 32K-token sequence in FP16. On the same GPU, MLA allows substantially more concurrent sequences.
When estimating total memory, account for weights, KV cache, activations, and framework overhead. The cache estimate can serve as the main basis for concurrency planning.
5. Key Issues in Engineering Deployment
5.1 Expert Parallelism and Communication Overhead
In multi-device deployments, experts are usually spread across different devices. Each token must be dispatched to the device hosting its selected experts, and the results must be gathered back. Communication volume depends on the routing distribution and batch size, and it often becomes the throughput bottleneck. Measure the actual load and track which experts receive tokens during design.
5.2 Kernel Optimization for Irregular Computation
Within one batch, tokens activate different experts, so the computation splits into many small matrix multiplications. A common optimization groups tokens by expert and runs grouped matrix multiplication. Combined with expert capacity control, this reduces idle compute and padding.
5.3 Numerical Consistency Verification
MLA involves absorbing up-projections and decoupling position encoding, so its computation graph differs from standard attention. Before launch, compare the output with a reference implementation using fixed inputs. Check that the error stays within an acceptable range, and cover long sequences and boundary lengths.
5.4 Impact of Quantization on Accuracy
Weight quantization and cache quantization affect accuracy differently. Cache quantization acts directly on attention keys and values, so it is more sensitive to generation quality in long contexts. Evaluate both on your own business data rather than relying only on general leaderboards.
5.5 Evaluation Methods
When selecting a model, use datasets relevant to your business. They should cover the target tasks, languages, and context lengths. A ranking on a single benchmark does not represent production performance. Consider latency, throughput, and cost together.
6. Selection Guidelines
- If computation is the main bottleneck and GPU memory capacity is sufficient, MoE provides clear benefits.
- If concurrency is limited by the KV cache, especially in long-context scenarios, cache compression is more effective.
- The two techniques address complementary problems and can be combined in the same system.
Before choosing a design, estimate the weight and cache size of your own configuration with the script above. Then measure routing distribution and latency under real workloads. These results usually say more about whether a solution fits your use case than parameter tables and marketing metrics.
