Reducing LLM Inference Costs: MoE Architecture and KV Cache Optimization

    As large language model applications move from pilots to scale, inference cost becomes a critical constraint. This article examines the main cost drivers—computation, memory, and data transfer—and explains how Mixture of Experts (MoE) decouples total parameters from activated parameters, why KV cache becomes the bottleneck for long-context serving, and which optimization directions are commonly used: attention-structure compression, tiered storage, and prefix reuse. It also covers multimodal deployment choices, the cost characteristics of agent workloads, billing and cost-estimation methods, engineering practices for production adoption, and key risks to validate before migration or scale-up.

    1. Background: Why Inference Cost Becomes a Core Problem

    In the early stage of LLM adoption, teams mainly focused on model capabilities, such as whether a model could handle code generation, document understanding, or multi-step reasoning. Once applications enter large-scale deployment, cost quickly becomes a key factor in whether a project can be sustained. An agent task often includes multiple rounds of tool calls, long-context retrieval, and repeated model requests, and each round rereads previous content. Input tokens accumulate quickly, and inference cost rises accordingly.

    Inference cost mainly consists of three parts: computation, memory usage, and data transfer. Computation is related to the scale of activated parameters; memory usage mainly comes from model weights and KV cache; and data transfer appears in multi-GPU communication and cache reads/writes. Understanding the relationship among these three parts is a prerequisite for designing cost-reduction solutions.

    2. MoE Architecture: Total Parameters and Activated Parameters

    Mixture of Experts (MoE) is a common sparse architecture. The model contains a large number of expert sub-networks, but each token is computed by only a few of them. As a result, the total parameter count can be large while the number of activated parameters in a single forward pass remains relatively small.

    A router selects experts for each token. The most common approach is to compute gating scores, take the top-k experts, and then compute a weighted sum of their outputs. The illustrative code below shows the basic logic:

    1. import numpy as np
    2. def topk_route(hidden: np.ndarray, gate_weight: np.ndarray, k: int = 2):
    3. """Select k experts for a single token and compute normalized weights (illustrative implementation)"""
    4. logits = hidden @ gate_weight # Shape: [num_experts]
    5. top_idx = np.argsort(logits)[-k:] # Take the k experts with the highest scores
    6. exp_scores = np.exp(logits[top_idx])
    7. weights = exp_scores / exp_scores.sum() # Apply softmax normalization over selected experts
    8. return top_idx, weights

    The benefit of MoE is that it decouples “model capacity” from “computation per pass.” Two engineering issues need attention. The first is load balancing: if a large number of tokens are routed to a few experts, some devices become bottlenecks, so training usually introduces an auxiliary loss term to constrain the distribution. The second is communication overhead: when experts are distributed across devices, tokens need to be dispatched and collected across GPUs, and network bandwidth affects end-to-end latency.

    During model selection, evaluate total parameters, activated parameters, and deployment memory together. Total parameters determine the storage space required for weights, while activated parameters determine the computational intensity per token. The larger the gap between the two, the more compute can be saved per inference pass, but memory pressure may not decrease at the same time, so the choice should be made with hardware constraints in mind.

    3. The Long-Context Bottleneck: KV Cache

    During autoregressive generation, the model caches the keys (Key) and values (Value) of attention at each layer to avoid recomputing historical tokens. This cache is the KV cache. The longer the context and the more concurrent requests, the more memory the KV cache occupies, and it often exhausts resources before model weights do.

    Under standard multi-head attention, the KV cache size for a single token can be estimated as follows:

    Bytes per token = 2 × layers × KV heads × head dimension × bytes per element

    The coefficient 2 represents the two caches for Key and Value. With structures such as grouped-query attention (GQA), the number of KV heads is smaller than the number of query heads, so the cache size decreases accordingly.

    1. def kv_bytes_per_token(num_layers: int, num_kv_heads: int,
    2. head_dim: int, dtype_bytes: int = 2) -> int:
    3. """Calculate the KV cache size in bytes for a single token"""
    4. return 2 * num_layers * num_kv_heads * head_dim * dtype_bytes
    5. def kv_total_gib(context_len: int, batch_size: int, **model_cfg) -> float:
    6. """Estimate total KV cache in GiB for a given context length and concurrency"""
    7. per_token = kv_bytes_per_token(**model_cfg)
    8. return per_token * context_len * batch_size / 1024**3
    9. # Example assumptions: 60 layers, 8 KV heads, head dimension 128, FP16 storage, 128K context, single concurrency
    10. print(round(kv_total_gib(131072, 1, num_layers=60, num_kv_heads=8, head_dim=128), 1))

    Under these assumptions, the KV cache for a single concurrent request with a 128K context is about 30 GiB. As concurrency increases, memory demand grows linearly. Therefore, optimization for long-context services usually focuses on the cache itself. Common directions include the following.

    Attention-structure compression: Reduce the per-token cache cost by compressing representations of historical tokens, reducing the number of key-value pairs that need to be cached, or using different attention strategies at different layers. Some approaches combine sparse attention so that the current token attends to only a subset of historical positions.

    Tiered storage: High-bandwidth memory (HBM) has limited capacity and high cost, so less frequently accessed cache can be moved to host memory or local solid-state drives while hot data remains in GPU memory. A tiered strategy needs to handle swap-in and swap-out latency; otherwise, it slows down time to first token.

    Cache reuse: Multi-turn conversations and agent tasks often share the same system prompt and historical prefix. The serving side can hash-match prefixes and directly reuse the computed KV cache when there is a hit. The more stable the prefix design, the higher the hit rate.

    4. Native Multimodality and External Vision Modules

    There are roughly two paths for implementing multimodal capabilities. One is to attach an additional vision encoder outside the language model and then map image features into the language model’s representation space through a projection layer. The other is to let the model process text, images, and other modalities together during pretraining, so visual understanding becomes part of the model backbone.

    The advantage of the external approach is that it can reuse mature vision models and has a lower development barrier. The disadvantage is interface alignment cost between the two modules: deployment requires maintaining two sets of weights and inference workflows, and memory usage adds up. The native approach reduces module-assembly overhead and provides a more unified deployment form, but it places higher demands on training data and training workflows.

    For application developers, the following questions are worth checking during selection: the maximum image input resolution and token billing method, latency for mixed text-image requests, whether a single request can carry multiple images, and whether the output format meets structured parsing requirements. Specific parameters should be based on the service provider’s official documentation and should not be inferred from experience.

    5. Cost Characteristics of Agent Workloads

    Agent tasks differ clearly from ordinary question answering. A typical task may include planning, retrieval, tool invocation, result validation, and summary output. Each step sends the previous conversation history and tool results to the model, so input tokens grow quickly with the number of rounds.

    This has three direct effects. First, input volume is much larger than output volume, so input-side unit prices and caching strategies have a greater impact on total cost. Second, prefix repetition is high: system prompts, tool definitions, and historical summaries are largely unchanged across requests, making them suitable for caching. Third, long tasks are latency-sensitive, and repeated prefill caused by cache misses noticeably lengthens waiting time.

    Therefore, the usual approach to reducing agent cost is to stabilize the prompt structure and place variable content at the end; truncate and summarize tool results to avoid irrelevant information occupying context; and set different maximum output lengths for different steps.

    6. Billing Mechanisms and Cost Estimation

    LLM service billing usually includes input (with cache hits and misses distinguished) and output. Some services also set different prices by time period, for example, higher unit prices during peak hours and lower prices during idle periods. Such mechanisms encourage users to schedule non-real-time tasks during off-peak periods.

    Cost estimation can be done with a simple function. The example below uses assumed unit prices only to demonstrate the calculation method; actual prices should be based on the service provider’s published information:

    1. def request_cost_yuan(hit_tokens: int, miss_tokens: int, output_tokens: int,
    2. price_hit: float, price_miss: float, price_out: float) -> float:
    3. """Calculate the cost of a single request; unit prices are yuan per million tokens"""
    4. total = hit_tokens * price_hit + miss_tokens * price_miss + output_tokens * price_out
    5. return total / 1_000_000
    6. # Assumed prices: hit 0.1 yuan, miss 2 yuan, output 4 yuan (for demonstration only)
    7. cost = request_cost_yuan(hit_tokens=80_000, miss_tokens=5_000,
    8. output_tokens=1_000,
    9. price_hit=0.1, price_miss=2, price_out=4)
    10. print(f"Cost per request: {cost:.4f} yuan")

    This example shows that with the same total input volume, changes in cache hit rate significantly change the cost. Therefore, when evaluating a solution, in addition to unit prices, teams should also measure the real hit rate, average input length, and output length, and then estimate costs together with business call frequency.

    7. Engineering Adoption Recommendations

    Build a unified model access layer. Business code should not be directly coupled to private parameters of a specific service. Instead, an adapter layer should unify request formats, timeout policies, and retry logic. When a service is discontinued, a version is switched, or traffic needs to be routed to an alternative model, only the adapter configuration needs to change, minimizing changes on the business side.

    Record key metrics. At a minimum, monitor input tokens per request, cache-hit tokens, output tokens, time to first token, and total latency. These data can be aggregated into a logging service or monitoring platform, with alert thresholds for cost and latency.

    Design degradable execution paths. For non-critical steps, teams can switch to a lighter model or reduce retrieval rounds when cost exceeds a threshold or a service is abnormal. Degradation policies should be written into configuration in advance and validated under load testing.

    Control context growth. Use rolling summaries for conversation history, trim fields from tool output, and retain only the information truly needed by subsequent steps. This work often delivers more direct cost benefits than adjusting model parameters.

    Pay attention to compliance and data boundaries. When user-sensitive data is involved, confirm the service provider’s data-processing terms and desensitize data before sending. Retention periods for caches and logs should also be included in security review.

    8. Risks and Caveats

    Prices, available regions, API versions, and model retirement schedules for LLM services may change. Systems that depend on a specific version should retain version-locking capability and run regression tests before migration. When routing to an alternative model, output formats, refusal boundaries, and tool-calling behavior may differ, so validation with real samples is required.

    Cost estimation also has uncertainty. Cache hit rate is affected by request order and concurrency, and the traffic distribution between peak and off-peak periods changes the weighted actual unit price. Before launch, replaying historical logs is recommended to obtain a cost estimate close to reality, and then decide resource investment.

    Summary

    Inference cost is determined jointly by computation, memory, and data transfer. MoE architecture reduces computation per pass through sparse activation; KV cache structure optimization and tiered storage relieve memory pressure; and prefix reuse and context governance directly affect input cost in agent scenarios. In engineering practice, teams should first unify the access layer and establish a metrics system, then optimize solutions around real hit rates and token distributions. In this way, cost control has a verifiable basis.