Optimizing Inference Systems for Large-Scale MoE Models

    This article explores the practical challenges of serving large-scale Mixture-of-Experts (MoE) models, showing that the primary bottleneck is often runtime state management rather than raw parameter size. It covers multi-pool coordination for hybrid attention, layered prefix caching, sparsity and offloading strategies, expert parallelism scheduling, multi-step prediction, and the observability required for capacity planning.

    1. The Real Bottleneck: Runtime State, Not Parameter Count

    As large-scale Mixture-of-Experts (MoE) models move into production, many teams’ first instinct is that they are short on GPU memory or compute. In real serving pipelines, however, the more common bottleneck is not the parameters themselves but the complexity of the state space that the inference runtime must maintain.

    Take a new generation of large models as an example. Their attention structure is often not a single form but a combination of multiple mechanisms:

    • Sliding Window Attention (SWA): focuses only on a local window, making it suitable for capturing nearby dependencies;
    • Compressed attention: compresses long history into low-rank or segmented representations to reduce long-context cost;
    • Hybrid switching: different layers or stages switch between compression granularities.

    This means the inference engine can no longer treat the KV Cache as a simple structure with “one raw KV per layer.” Instead, it must maintain multiple physical pools and coordinate mappings at the same time:

    1. full-token coordinate space
    2. ├── sliding-window physical pool
    3. ├── low-granularity compressed pool
    4. ├── high-granularity compressed pool
    5. ├── index auxiliary pool
    6. └── compression state pool

    Once capabilities such as prefix caching, CUDA Graph, prefill-decode (PD) disaggregation, and tiered offloading are introduced, the mapping relationships among these pools become even more complex. Therefore, the core goal of inference system optimization should be redefined as: managing multi-form state as efficiently as possible under limited memory and bandwidth, while making the scheduler and the caching system work together.

    2. Hybrid Attention Runtime: From “One KV” to “Multi-Pool Coordination”

    Traditional inference implementations usually assume that the KV structure is identical across layers and that the access path is also identical. Hybrid attention breaks this assumption. The system needs to abstract a unified coordinate layer that maps logical token positions to different physical pools.

    A practical design approach is to introduce a two-layer structure of “logical coordinate + pool handle”:

    1. class TokenLocator:
    2. pos: int # logical full position
    3. pool_id: int # target physical pool
    4. offset: int # offset within the pool
    5. compress_level: int # compression level, 0 means uncompressed

    This brings three benefits:

    1. Decoupling attention algorithms from storage implementation: when adding a new attention form, you only need to register a new pool type and mapping rules;
    2. Supporting coexistence of mixed precision and mixed granularity: local windows keep high-precision raw KV, while remote history uses compressed representations;
    3. Laying the groundwork for cross-node migration: in PD-disaggregated scenarios, you only need to migrate pool handles and necessary metadata, rather than entire blocks of GPU memory.

    Two engineering details also need attention. First, compression state often has cumulative semantics across steps, so initialization, update, and destruction timing must be clearly defined within the request lifecycle; otherwise, long-context quality will fluctuate. Second, CUDA Graph capture requires stable shapes and addresses, so the multi-pool structure needs reserved fixed capacity along with in-pool reclamation strategies to avoid graph invalidation caused by dynamic scaling.

    3. Tiered Caching and Prefix Reuse: Turning Repeated Computation into Lookup

    In real workloads, a large number of requests share the same prefix (system prompts, templates, few-shot examples). The value of tiered caching is to turn this repeated prefill into compute-once, reuse-many-times.

    The recommended tiered design is as follows:

    Tier Location Capacity Access Latency Typical Use
    L1 GPU memory pool Small Very low Hot prefixes in the current batch
    L2 Host memory Medium Low Session-level shared prefixes
    L3 External storage/cache service Large Medium Cross-instance template reuse

    The key engineering point is the combination of “prefix tree + reference counting + eviction policy.” The prefix tree locates the longest reusable segment, reference counting ensures that nodes in use are not evicted, and the eviction policy must balance hit rate and defragmentation. If the model uses compressed attention, you also need to record whether the compression state is reusable; otherwise, you get a second computation where “the raw KV hits but the compression state is missing.”

    A simplified matching logic can be expressed as:

    1. def match_prefix(tokens):
    2. node = root
    3. last_hit = 0
    4. for i, t in enumerate(tokens):
    5. child = node.children.get(t)
    6. if child is None:
    7. break
    8. node = child
    9. if node.ref_ready:
    10. last_hit = i + 1
    11. return last_hit, node

    Under PD-disaggregated deployment, prefix caching must also support cross-role transfer: caches produced by prefill nodes must be packageable, verifiable, and loadable onto decode nodes, so metadata version numbers and consistency checks cannot be omitted.

    4. Sparsification and Offloading: Making the Right Trade-offs Under Bandwidth Constraints

    Long contexts and multi-turn conversations cause cache size to grow rapidly. Sparsification and tiered offloading are two complementary approaches.

    The idea behind sparsification is that not all historical tokens are equally important to the current generation. Using a lightweight scoring mechanism to select a critical subset to participate in attention computation can significantly reduce bandwidth pressure. In implementation, it is recommended to decouple scoring from the main compute pipeline so that scoring itself does not become a new serial bottleneck.

    Offloading follows the principle of “hot data stays in GPU memory, warm data goes to host memory, cold data lands in external storage.” It is worth emphasizing that offloading must be prefetch-first: before decoding begins, issue asynchronous transfers in advance based on the access pattern of upcoming tokens, and use double buffering to hide transfer latency.

    1. step t: compute + issue prefetch for t+1
    2. step t+1: use ready buffer + issue prefetch for t+2

    If the prefetch hit rate is insufficient, fall back to the full path rather than blocking and waiting, to keep tail latency under control.

    5. Expert Parallelism and Scheduling: Load Balance Determines Actual Throughput

    The throughput ceiling of MoE is usually determined by the slowest expert. When Expert Parallelism (EP) is used together with Tensor Parallelism (TP) and Data Parallelism (DP), three issues need particular attention:

    1. Routing skew: a few hot experts cause long tails in compute and communication;
    2. Capacity overflow: tokens exceeding a single expert’s capacity need an overflow or drop policy;
    3. Communication amplification: All-to-All communication volume grows as parallelism increases.

    A feasible optimization combination includes: introducing a load-aware capacity factor on the routing side, pipelining dispatch and aggregation by buckets on the communication side, and replica expansion for hot experts on the execution side. The scheduler should use “maximum expert load per step” rather than “average load” as the core metric, and dynamically adjust batch size accordingly.

    6. Multi-Step Prediction and Graph Capture: Reducing Decode Overhead

    Multi-step Prediction (MTP) predicts multiple candidate tokens in a single forward pass and then filters them in a verification step, which can improve effective throughput when the acceptance rate is high. The key to implementation is that the number of candidates must be linked to batch size: the larger the batch, the fewer candidates, to avoid verification cost outweighing the benefit.

    For graph capture, it is recommended to organize by “batch-size bucketing + fixed pool capacity” to keep the number of captured graphs manageable; for scenarios with frequent shape changes, keep an eager fallback path to prevent jitter from frequent re-capture.

    7. Observability and Capacity Planning

    A complex state space must be paired with observability; otherwise, the cost of locating problems is extremely high. At a minimum, collect:

    • Occupancy rate, fragmentation rate, and eviction count of each physical pool;
    • Prefix hit rate and compression-state hit rate;
    • Prefetch hit rate and fallback count;
    • Expert load distribution and overflow ratio;
    • Queue time and step-time distribution for prefill and decode.

    For capacity planning, estimate the GPU memory baseline with “concurrent sessions × average context length × state bytes per token,” then add compression gains and offloading ratio to get the maximum servable context. If a container platform and message queue are used to decouple request ingress from execution, burst traffic can be smoothed further; combined with logging services and monitoring alerts, the source of long tails can be located faster.

    8. Conclusion

    Optimizing inference for large-scale MoE models is essentially translating “model structure diversity” into “deterministic management of runtime state.” Hybrid attention requires multi-pool coordination, prefix reuse requires tiered caching and consistency, sparsity and offloading require prefetch-driven bandwidth governance, and expert parallelism requires scheduling based on the slowest expert. Only by linking these parts into a closed loop can you achieve stable and predictable throughput and latency under limited resources.