A Guide to Selecting Sparse LLMs: MoE, Long Context, and VRAM Estimation
This article explores strategies for balancing large language model capabilities with computational costs through sparsification. It provides a detailed analysis of Mixture of Experts (MoE) for parameter efficiency, sparse attention for handling long contexts, Multi-Token Prediction (MTP) for inference acceleration, and practical methods for estimating and optimizing VRAM usage for the KV cache. Additionally, it offers a comprehensive checklist to guide model selection and implementation.
1. Background: The Trade-off Between Parameter Scale and Compute Cost
The capability of large language models (LLMs) improves with larger parameter scales and increased training data. However, during inference, generating a single token requires extensive matrix operations. The larger the model, the higher the computational load, VRAM usage, and response latency for a single request. Engineering teams must find a balance between capability limits and costs.
Sparsification is currently a common approach to address this. The model has a large total parameter count, but only a subset is activated during each forward pass. This concept follows two main directions. First, introducing a Mixture of Experts (MoE) structure in the feed-forward layers to reduce the per-token computational load. Second, reducing the number of historical positions involved in attention calculations to lower the overhead associated with long contexts. These two approaches target the costs of parameter scale and context length, respectively, and are suited for different scenarios. When selecting a model, it is crucial to first identify where the bottleneck lies.
2. Mixture of Experts (MoE): Total vs. Activated Parameters
2.1 Basic Concepts
In a Mixture of Experts (MoE) structure, the feed-forward layer is split into multiple expert networks. A router scores each token and selects a small number of experts to participate in the computation. The total parameters saved by the model include the weights of all experts, but the parameters actually activated for a single token are only those of the selected experts and shared layers.
2.2 Sparsity Calculation
Sparsity can be measured by the ratio of activated parameters to total parameters:
Sparsity = (Activated Parameters / Total Parameters) × 100%
Example: A model with a total of 700B parameters that activates 40B parameters per token has a sparsity of approximately 40 / 700 ≈ 5.7%. The compute per token is close to that of a 40B dense model, while the model’s knowledge capacity approaches the 700B scale.
Two points need attention. First, VRAM must still accommodate all expert weights; the sparse structure reduces compute, not the storage footprint of the weights. Second, sparsity only indicates the proportion of activated parameters and does not mean that throughput or costs will decrease by the same ratio. With large batch sizes, different tokens within a batch will hit many different experts, requiring almost all expert weights to be read into VRAM, which diminishes memory bandwidth savings. The communication overhead of expert parallelism and the load on each GPU also affect actual latency. Therefore, evaluation should be based on measured throughput and latency.
2.3 Basic Routing Process
Below is Python pseudo-code for the routing process, intended solely to illustrate the logic and not corresponding to any specific implementation:
def moe_forward(x, router, experts, top_k=2):scores = router(x) # Calculate score for each experttopk_idx = scores.topk(top_k).indices # Select the top k experts with the highest scoresweights = softmax(scores[topk_idx]) # Normalize the scores of the selected expertsout = 0for w, i in zip(weights, topk_idx):out += w * experts[i](x) # Only compute the selected expertsreturn out
The pseudo-code omits several engineering boundaries. top_k determines the number of experts activated per token; a larger value increases computation and communication. Softmax is typically applied only to the selected expert scores, though it can be applied to all experts depending on the model design. In expert parallelism scenarios, each token’s representation must be sent to the GPU holding the corresponding expert and aggregated back after computation. This all-to-all communication is often the primary bottleneck. Some systems also set a capacity factor to limit the number of tokens a single expert can receive per batch; excess tokens are dropped or rerouted to other experts, which affects output quality and must be monitored during evaluation.
Engineering also requires handling load balancing. If most tokens are routed to a few experts, those experts become overloaded while others remain idle. Common practices include adding a load balancing term to the training loss or limiting the number of tokens each expert can receive during routing.
2.4 Training and Inference Considerations
Training sparse structures is more complex than dense models, with main challenges including routing instability, uneven expert utilization, and high cross-device communication overhead. During inference, experts are typically distributed across multiple accelerator cards, requiring tokens to be dispatched and aggregated across cards. Network bandwidth can become a bottleneck. When selecting a model, teams should evaluate both compute and communication capabilities. Judging based solely on parameter scale or activated parameter numbers often leads to overestimating the benefits.
3. Sparse Attention: Reducing Computation for Long Sequences
The computational load of standard self-attention is proportional to the square of the sequence length. Increasing the sequence from 4K to 128K increases the number of elements in the attention matrix by about 1024 times, i.e., (128 / 4)² = 1024. As the context grows longer, attention easily becomes the primary overhead.
The idea behind sparse attention is to allow each token to focus only on a subset of historical positions. Common patterns include the following three categories:
- Sliding window: Only attend to the most recent
wpositions. - Global tokens: Retain a few positions that are always visible, such as system instructions or the beginning of a document.
- Content-based selection: First use lightweight scoring to pick relevant historical blocks, then perform fine-grained attention on these blocks.
Schematic code is as follows:
def select_blocks(query, block_keys, top_b=8):# Use block-level summaries for quick scoring, keeping only the top_b highest-scoring historical blocksblock_scores = query @ block_keys.Treturn block_scores.topk(top_b).indices
Sparse attention also carries the risk of information omission. If critical information happens to fall into an unselected block, the output may be incorrect. Therefore, in practice, it must be paired with long-context evaluation. A common workflow is as follows:
- Prepare a set of long texts, with lengths covering the main intervals of the target context window.
- Insert a specific piece of information at different depths within the text (e.g., at 10%, 30%, 50%, 70%, and 90%), such as a number or a factual statement.
- Ask the model to answer based on the context and determine if the information was correctly recalled.
- Calculate the recall rate for each depth and compare it with the full-attention baseline.
Teams should set pass thresholds in advance, such as ensuring the recall rate at each depth is not lower than a certain proportion of the baseline. The threshold should be determined based on business tolerance and should not directly copy others’ figures.
4. Multi-Token Prediction: Enhancing Training Signals and Inference Throughput
Traditional language models predict only the next token at each step. Multi-Token Prediction (MTP) allows the model to simultaneously predict several subsequent tokens at the same position, providing denser training supervision for each position.
4.1 Training Benefits
During training, the additional prediction heads provide more supervision targets, helping the model learn long-range dependencies. The benefits of this method depend on data scale, the number of prediction steps, and loss weights, requiring ablation studies to confirm; fixed gains should not be assumed.
4.2 Inference Acceleration
During inference, the additional prediction heads can generate candidate tokens, which are then verified in a single pass by the main model. If the candidates are accepted, a single forward pass can output multiple tokens, reducing the total number of forward passes. This concept is similar to speculative decoding.
Higher acceptance rates generally lead to more noticeable speedups, but the speedup ratio is affected by other factors. The prediction heads themselves introduce extra computation, and the verification step has a cost. As batch sizes change, the computational load per step changes, and benefits may vary accordingly. Therefore, the acceptance rate is a key metric but not the only one. The acceptance rate is closely related to the task type. Code completion often has many repetitive structures, resulting in higher acceptance rates; open-ended writing has lower acceptance rates.
4.3 Implementation Essentials
- The number of prediction steps should not be too large. More steps lead to less accurate distant predictions and a subsequent drop in acceptance rate.
- Acceptance rates should be tracked by task type to decide whether to enable this feature.
- The verification step must ensure that the output is consistent with standard decoding results, or consistent within an agreed-upon error margin.
It is recommended to use the table below to record statistical results for easy comparison:
| Task Type | Batch Size | Average Acceptance Rate | Average Output Tokens per Forward Pass | End-to-End Latency Change | Enabled |
|---|---|---|---|---|---|
| Code Completion | TBD | TBD | TBD | TBD | TBD |
| Open-ended Writing | TBD | TBD | TBD | TBD | TBD |
| Agent Tool Calling | TBD | TBD | TBD | TBD | TBD |
5. VRAM Estimation for Long Context Windows
Supporting long contexts is not just an attention computation issue; it is also a VRAM issue. During inference, the keys and values for each layer need to be cached (KV cache), and its size grows linearly with sequence length.
The estimation formula is as follows:
KV cache bytes = 2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element
The coefficient 2 indicates that both K and V are stored.
Example: 80 layers, 8 KV heads, a head dimension of 128, a sequence length of 131072 (i.e., 128K), and 2 bytes per element (FP16 or BF16). Substituting these into the calculation:
2 × 80 × 8 × 128 × 131072 × 2 = 42,949,672,960 bytes, which is approximately 40 GiB.
A single request requires about 40 GiB of VRAM just for the KV cache, not counting model weights and activations. Concurrent requests will multiply this usage. If the number of KV heads is increased from 8 to 64—approaching multi-head attention without grouping—the KV cache for the same configuration would increase to about 320 GiB. This shows that the choice of attention structure has a significant impact on VRAM.
Common engineering countermeasures include the following categories:
- Grouped-Query Attention (GQA) or Multi-Query Attention to reduce the number of KV heads.
- Quantizing the KV cache, for example, using 8-bit storage for keys and values, which reduces the footprint to about 20 GiB for the same configuration. Quantization may introduce precision loss and requires evaluation on target tasks, compared against FP16 or BF16 baselines.
- Paged cache management to reduce VRAM fragmentation.
- Scheduling based on request length to prevent overly long requests from squeezing out resources for other requests.
6. Benefits, Costs, and Use Cases of the Four Technologies
| Technology | Primary Benefit | Primary Cost | Applicable Scenarios |
|---|---|---|---|
| Mixture of Experts (MoE) | Reduces per-token compute, expands model capacity | VRAM must still hold all experts; complex communication and load balancing | Large parameter scale, limited compute budget, multi-GPU interconnectivity available |
| Sparse Attention | Reduces attention computation overhead for long sequences | May miss critical information; requires long-context recall evaluation | Long document processing, long conversations, codebase retrieval |
| Multi-Token Prediction (MTP) | Enhances training supervision density; may reduce forward passes during inference | Prediction heads add overhead; acceptance rate varies by task | Tasks with many repetitive structures, like code completion |
| KV Cache Optimization | Reduces VRAM usage for long contexts | GQA may affect quality; quantization requires precision evaluation | High-concurrency, long-context service deployment |
7. Selection and Implementation Checklist
When selecting a model, it is recommended to check off the following four categories item by item.
- MoE Communication and Load Balancing
- Record the token distribution across experts to ensure no experts are chronically idle or overloaded.
- Measure the proportion of all-to-all communication time within a single-step latency.
- Measure actual throughput at the target batch size rather than just looking at the activated parameter ratio.
- Sparse Attention Recall Evaluation
- Conduct depth-based insertion tests following the process in Section 3.
- Compare the recall rate with the full-attention baseline and determine if it passes based on team thresholds.
- Re-test on real business long document samples, not just relying on synthetic data.
- MTP Acceptance Rate Tracking
- Record acceptance rates, average output token counts, and end-to-end latency by task type.
- Confirm that the verification step is consistent with standard decoding results or within the agreed error margin.
- Decide whether to enable MTP for a task based on the statistical results.
- KV Cache VRAM Estimation
- Use the formula to calculate KV cache usage for the target context length and concurrency.
- Include model weights, activations, and cache fragmentation margins into the VRAM budget.
- If the estimation exceeds hardware capacity, prioritize evaluating GQA and quantization schemes, and confirm after performance evaluation.
After completing the above checks, teams can choose a solution based on the bottleneck. If the bottleneck is parameter scale, prioritize evaluating MoE communication capabilities; if the bottleneck is long context, prioritize evaluating sparse attention and KV cache optimization; if the bottleneck is single-request latency, consider MTP. The benefits of each item should be based on measured data in the business scenario.
