Expert Scheduling and Caching for Memory-Constrained MoE Inference
When GPU memory cannot hold all expert weights in a Mixture of Experts model, estimate the total expert weight size first, then decide whether to store them in host memory or on SSD. This article explains how to use double buffering to overlap data transfer with computation, how to design an expert cache (LRU by default, LFU variants when hotness is skewed, shared across all layers), why prefill and decode have different bottlenecks, and how to plan cache capacity, prefetching, eviction, batching, and monitoring with concrete calculation examples.
1. Background: The Capacity-Bandwidth Trade-off in MoE
The Mixture of Experts (MoE) architecture splits the feed-forward network into multiple expert sub-networks. A router selects a small number of experts for each token, denoted as k, with common settings such as top-2 or top-8. Top-k means the router picks the k highest-scoring experts. Activated parameters are the parameters that actually participate in computation for each token, which is far smaller than the model’s total parameter count. As a result, the model can have a very large total parameter count while per-step computation depends only on the activated parameters.
At deployment time, the total parameter count determines storage pressure. Here is an illustrative calculation with hypothetical numbers, used only to convey the order of magnitude: assume each layer has 64 experts, each expert weighs about 0.5 GB in FP16, and the model has 48 layers. The total expert weight size is then:
64 × 0.5 GB × 48 = 1536 GB
Even with 4-bit quantization compressing the size to a quarter, it still comes to roughly 384 GB. Consumer GPUs typically have only 8 GB to 32 GB of VRAM, which cannot hold the full set of experts.
The common approach, therefore, is to keep expert weights in host memory or on a local SSD and move them to the GPU on demand. Data movement goes over the PCIe bus. The table below compares storage tiers by order of magnitude. Bandwidth figures are theoretical peaks; real achievable values are usually lower and must be measured on the target hardware.
| Storage tier | Typical capacity | Typical bandwidth | Access latency |
|---|---|---|---|
| GPU VRAM | 8–96 GB | Hundreds of GB/s to TB/s | Low |
| Host memory | Tens to hundreds of GB | Tens of GB/s (PCIe-limited) | Medium |
| Local SSD | Hundreds of GB to several TB | Several GB/s (NVMe sequential read) | High |
GPU VRAM and host memory differ by more than an order of magnitude in bandwidth, so data movement often becomes the critical path of inference. The more experts a model has and the more scattered the activated experts are per step, the larger the transfer volume.
2. Prefill vs. Decode: Different Bottlenecks
Inference has two phases. Prefill processes the entire input prompt at once, while decode generates output tokens one at a time. The two phases face different pressures and require different optimizations.
In the prefill phase, a large number of tokens are processed simultaneously. These tokens are routed to different experts, and the set of activated experts in a layer often covers most of the experts. Each loaded expert serves multiple tokens, so the cost of weight loading is amortized, and the computation volume is large. The main pressures here are the total number of experts that must be loaded within a layer and the VRAM consumed by intermediate activations. The longer the prompt, the greater the pressure, so long prompts often need to be processed in chunks to control the number of activated experts and activation memory per pass.
In the decode phase, each step typically generates one token per sequence. Each layer activates only k experts, per-step computation is small, and weight reading dominates. Different steps may access different experts, so whether the cache hits directly determines per-step latency. On a cache miss, the step must wait for weights to be transferred from host memory or SSD, and latency rises significantly. The core metrics for the decode phase are therefore cache hit rate and bytes loaded per step.
3. Four Core Techniques
3.1 Double Buffering: Overlapping Transfer and Computation
Double buffering keeps two expert weight buffers on the GPU. While computing layer i, the required experts reside in buffer A. Meanwhile, a separate CUDA stream asynchronously copies the experts needed for layer i+1 from host memory into buffer B. When the next layer begins, the two buffers swap roles.
This technique works only if the transfer time for a layer does not exceed the computation time for that layer. If transfer is slower, the compute side stalls, and double buffering hides only part of the latency. Asynchronous copies typically require pinned memory, which consumes host memory and must be included in the capacity budget.
3.2 LRU Cache: Keeping Recently Used Experts
An LRU (Least Recently Used) cache keeps a fixed number of experts in GPU memory. On a hit, they are used directly; on a miss, they are loaded from host memory, and the least recently used expert is evicted.
LRU is simple to implement and effective for workloads with strong temporal locality. Its weakness is that it ignores frequency. Prefill accesses a large number of experts at once and may evict the experts that are truly hot during decode. For this reason, you can manage the caches used by prefill and decode separately, or switch to LFU (Least Frequently Used) or segmented LRU when hotness differences are pronounced.
Cache keys should be (layer index, expert index), and all layers should share a single cache pool rather than a fixed per-layer allocation. The reason is that hotness distributions differ across layers, and fixed allocations waste VRAM.
3.3 Bandwidth-Adaptive Execution Paths
The same expert can either be transferred to the GPU for computation or left on the host side for CPU computation. The costs of the two paths can be roughly compared:
- Transfer path time ≈ expert weight bytes ÷ measured available bandwidth
- CPU path time ≈ floating-point operations required by the expert ÷ available CPU compute
When an expert serves only a few tokens, the CPU path may be faster; when it serves many tokens, moving it to the GPU is more efficient. The executor can choose the path dynamically based on measured bandwidth and per-expert token counts. This comparison depends on measured values—hardware varies widely, so theoretical peaks alone are not a reliable basis for decisions.
3.4 Runtime Elastic Adjustment
During inference, the KV cache grows with context length, so VRAM usage changes over time. If the expert cache has a fixed size, long contexts may cause out-of-memory errors. At runtime, monitor the following signals and adjust parameters:
- Free VRAM: shrink the expert cache when it runs low
- Cache hit rate: when consistently low, increase cache capacity or adjust the eviction policy
- Prefetch wait time: when too long, reduce prefetch depth
Adjustments should use thresholds and hysteresis bands to prevent the cache size from oscillating between two values. Every adjustment should be logged to make performance changes easier to diagnose.
4. Implementation Checklist
4.1 Estimating Cache Capacity
Estimate the VRAM available for the expert cache as follows:
- Determine total VRAM and reserve a percentage for system overhead and fragmentation, e.g., 10%.
- Subtract non-expert weights, including attention, embedding, and output layers.
- Subtract the target KV cache usage, calculated from maximum context length and concurrency.
- Subtract activations and compute workspace.
- Divide the remainder by the byte size of a single expert to get the number of cacheable experts.
The following hypothetical numbers demonstrate the calculation: a 24 GB GPU with a 10% reserve (2.4 GB), 6 GB of non-expert weights, 4 GB of KV cache, and 2 GB of activations and workspace. VRAM available for the expert cache is:
24 − 2.4 − 6 − 4 − 2 = 9.6 GB
With a 0.5 GB FP16 expert, about 19 experts can be cached. With 4-bit quantization, a single expert is about 0.125 GB, allowing roughly 76 experts. Quantization introduces accuracy loss and should be evaluated on the target task before adoption.
In this example, the full model has 3072 experts (64 experts × 48 layers). The cache holds only a small fraction, so the hit rate depends on whether routing has clear hotspots. If routing is roughly uniform, even caching dozens of experts may yield a low hit rate. Verify this by measuring the routing distribution on real requests.
4.2 Prefetching Strategy
Prefetching means loading experts into the cache before they are needed.
- Prediction method: use the current layer’s hidden states to approximate the next layer’s routing decisions. Prediction accuracy must be measured—wrong predictions waste bandwidth and cache slots.
- Prefetch depth: usually prefetch only the next layer or one to two layers ahead; deeper prefetching consumes too much bandwidth.
- Bandwidth budget: total prefetched bytes should be bounded by measured bandwidth and computation time; abandon the excess.
- Pinning: experts currently in use by the active layer must be locked and must not be evicted by the prefetch process.
4.3 Eviction Policy
- Use LRU by default, with locks on experts currently in use by the active layer.
- When hotness differences are pronounced, protect high-frequency experts or use an LFU variant.
- Before eviction, check whether any queued requests need the expert, to avoid loading an expert and immediately evicting it.
4.4 Batch Scheduling
- Group tokens by expert index within a batch so that each loaded expert serves as many tokens as possible.
- In prefill, process long prompts in fixed-length chunks; tune the chunk size based on VRAM peaks and the number of activated experts.
- When merging multiple sequences in decode, the set of activated experts per step grows, so cache capacity must be rechecked.
4.5 Monitoring Metrics
At minimum, record the following metrics, tracked separately for prefill and decode:
- Cache hit rate, broken down by layer and by expert hotness
- Bytes loaded per step and actual PCIe or SSD throughput
- Double-buffer wait time, i.e., how long the compute side waits for transfers to finish
- Time to first token (prefill) and per-token latency (decode)
- VRAM peak usage and fragmentation
- Prefetch accuracy and wasted prefetch bytes
5. Applicability Limits and Risks
- Bandwidth: actual PCIe and SSD throughput is often below theoretical peaks, and multi-GPU communication, NIC traffic, or disk I/O may contend with expert loading. The benefits of this approach depend on bandwidth—measure first.
- Hotness distribution: the more concentrated the routing, the more effective the cache. With uniform routing, cache benefits are limited and the system approaches a state of moving weights every step.
- Quantization error: low-bit quantization reduces VRAM usage but may degrade output quality.
- Cache hit rate: when the hit rate falls below expectations, per-step latency may approach the no-cache baseline.
- Memory pressure: as the KV cache or concurrency grows, the expert cache must shrink accordingly.
Fallback procedures:
- When monitored compute wait time exceeds a threshold, reduce prefetch depth—or disable prefetching and switch to on-demand loading if necessary.
- When VRAM is insufficient, shrink the expert cache and release pinned memory.
- Keep a switch to disable caching and prefetching entirely, for troubleshooting.
- Record metrics before and after every parameter adjustment to judge whether it was effective.
All performance numbers should be measured on the target hardware under real workloads; the numbers in this article only illustrate the calculation methods.
6. FAQ
What if VRAM is insufficient for MoE inference?
Estimate the total expert weight size first, then decide whether to store them in host memory or on SSD. Then use double buffering to hide transfer latency, and use a cache to keep hot experts resident.
How should the expert cache be chosen?
Use LRU by default. If the hotness distribution is clearly skewed, protect high-frequency experts or switch to an LFU variant. The cache should be shared across all layers.
How do prefill and decode differ?
Prefill processes a large batch of tokens, with pressure coming from the total number of experts loaded per layer and activation memory. Decode processes few tokens per step, with pressure coming from cache hit rate and bytes loaded per step. Track metrics separately for each phase and set cache policies accordingly.
