Sparse Attention and Mixture of Experts: Technical Approaches to Lowering LLM Costs
This article explains how Mixture of Experts (MoE) and Sparse Attention reduce the compute cost of large language models. It covers MoE routing and load balancing, the two-stage sparse attention selection process, the complexity trade-offs of each method, and how to evaluate long-context solutions.
1. The Problem: Long Contexts Drive Up Inference Costs
When large language models process long text, attention computation is one of the main sources of cost. In standard self-attention, each token computes its relevance to every earlier token in the sequence. Compute therefore grows with the square of the sequence length L, or O(L²). In scenarios such as document question answering, code repository analysis, and multi-turn agent tasks, inputs often reach tens of thousands of tokens, and costs rise quickly.
Expectations for model capability have not dropped. Developers face a core tension: larger parameter counts usually produce better results, but compute and memory costs per inference also increase.
Common industry approaches fall into two categories:
- Architectural level: Activate only part of the model for each computation. Mixture of Experts (MoE) is one example.
- Operator level: Reduce the number of tokens involved in attention computation. Sparse Attention is one example.
The two approaches can be combined, since each addresses cost in a different part of the model.
2. Mixture of Experts: Separating Model Capacity from Per-Step Compute
2.1 Core Idea
A Mixture of Experts architecture splits the feed-forward network into multiple expert sub-networks and adds a router. For each token, the router selects only a few experts to perform the computation. The model’s total parameter count can be very large, but each token passes through only a small fraction of those parameters. As a result, the model keeps a large knowledge capacity while the compute per inference stays at a moderate level.
This can be summarized in one sentence: total parameters determine the capability ceiling, and active parameters determine the cost of each computation.
2.2 Routing and Load Balancing
The router outputs a score for each expert. The system selects the top k experts by score and normalizes those scores to use as weighting coefficients. Two issues need attention in implementation:
- Load imbalance: If most tokens are routed to a few experts, some devices sit idle while others become bottlenecks. Common fixes include adding a load-balancing term to the training loss or setting a capacity limit for each expert during inference.
- Communication overhead: When experts are distributed across multiple accelerators, tokens must be dispatched and gathered across devices, and network bandwidth can become a bottleneck. This is especially noticeable in multi-node deployments.
2.3 Example Code
The following code only illustrates the data flow. It omits batching optimizations and distributed communication.
import torchdef moe_forward(x, experts, router, k=2):# x: [tokens, d_model]logits = router(x) # [tokens, num_experts]topk_scores, topk_idx = torch.topk(logits, k, dim=-1)weights = torch.softmax(topk_scores, dim=-1) # normalize over the selected expertsout = torch.zeros_like(x)for j in range(k):for e_id, expert in enumerate(experts):mask = topk_idx[:, j] == e_id # find tokens routed to this expertif mask.any():out[mask] += weights[mask, j:j + 1] * expert(x[mask])return out
3. Sparse Attention: Focusing Only on the Most Relevant Past Tokens
3.1 The Cost of Standard Attention
In full attention, each query is compared against all L previous keys, and the results are used to take a weighted sum of the values. As the sequence grows, both the compute and the key-value data accessed increase. For very long contexts, this part often accounts for a large share of inference time.
3.2 Two-Stage Selection Process
Sparse attention usually works in two stages:
- Coarse filtering: A lightweight indexer computes a relevance score for each past token. The indexer typically uses lower dimensions and fewer attention heads, so scoring each token costs far less than full attention.
- Precise computation: Select the top k tokens by score, and run standard attention only over those k positions.
3.3 Change in Complexity
In full attention, the compute for each query is proportional to L. With sparse attention, the compute for the precise stage is proportional to k. When k is much smaller than L, the main attention cost drops from O(L²) to O(L·k).
The indexer still scans all past tokens, so the overall complexity still depends on L. Only the constant factor drops significantly. Capacity planning should reflect this. It should not assume that compute becomes linear.
3.4 Example Code
import torchdef sparse_attention(q, keys, values, indexer, top_k):# q: [d], keys and values: [L, d]scores = indexer(q, keys) # lightweight scoring, shape [L]k = min(top_k, keys.shape[0])idx = torch.topk(scores, k).indices # select the top-k positionsk_sel, v_sel = keys[idx], values[idx]d = q.shape[-1]attn = torch.softmax(q @ k_sel.T / d ** 0.5, dim=-1)return attn @ v_sel
3.5 Boundary Conditions to Watch
- Choosing k: A small k can miss key information, while a large k reduces the benefit. Tune k on a validation set for each task.
- Indexer quality: If the indexer ranks tokens poorly, the correct context never enters the top-k set. These errors are hard to detect from the output alone, so they require dedicated recall tests.
- Cache management: Keys and values (KV) for past tokens must still be stored in GPU memory or system memory. Sparse attention mainly reduces compute and does not necessarily reduce memory use. Lowering memory requires cache eviction or tiered storage strategies.
- Training and inference consistency: If a model was trained with full attention but runs inference with sparse attention, verify that quality does not degrade.
4. Key Trade-Offs in Deployment
When choosing an attention approach, compare the options across these dimensions:
| Dimension | Full Attention | Sparse Attention |
|---|---|---|
| Compute complexity | Grows with L² | Main attention grows with L·k. The indexer still grows with L. |
| Long-context latency | Rises noticeably with length | Growth slows as length increases |
| Implementation complexity | Lower, with a mature ecosystem | Higher, requires an indexer and matching kernels |
| Memory usage | Stores all KV | Still stores all KV. Extra strategies are needed to reduce it. |
| Risk of information loss | No extra filtering error | Risk of the indexer missing relevant tokens |
Start by analyzing the distribution of context lengths in your workload. If most requests are short, sparse attention offers limited benefit, and the added complexity may not be worth it.
5. How to Evaluate a Long-Context Solution
Do not rely on a single metric. At minimum, cover the following four areas:
- Quality: Test on your own datasets for tasks such as long-document question answering, information extraction, and code localization. Pay attention to recall when key information sits in the middle of the sequence, not just the average score.
- Latency: Measure time to first token (prefill stage) and per-token generation latency (decode stage) separately. The two stages have different bottlenecks and require different optimizations.
- Throughput: Measure the number of tokens processed per unit time at your target concurrency.
- Cost: Convert the compute consumed per request into cost per token, so you can compare approaches on equal terms.
When evaluating, keep the input distribution fixed, group results by context length, and report confidence intervals to avoid drawing conclusions from a small sample.
