A Cost Optimization Guide for LLM Selection: MoE, Hybrid Attention, and KV Cache

    A practical guide to estimating and reducing large language model inference costs. This article explains how to build a rough cost model around compute, attention, and KV cache memory, then covers sparse Mixture-of-Experts (MoE) architectures, hybrid attention schemes, KV cache compression, residual information fusion, and native multimodal inputs. It includes key metrics for evaluation, routing and expert capacity formulas, worked memory calculations, and practical trade-offs for each optimization.

    1. Background and the Cost Model

    LLM inference cost is determined by three factors: the compute required per token, the compute and memory traffic that attention incurs as sequence length grows, and the GPU memory occupied by the key-value cache (KV Cache). Before choosing a model, estimate cost with a rough model rather than looking only at parameter count.

    The forward-pass compute per token is approximately proportional to the number of activated parameters. For dense models, activated parameters equal total parameters. For MoE models, activated parameters are only a fraction of the total.

    KV cache memory can be estimated with the following formula:

    Memory = 2 × num_layers × num_KV_heads × head_dim × sequence_length × batch_size × bytes_per_element

    Worked example (hypothetical configuration, not any specific model): 32 layers, 8 KV heads, head dimension 128, sequence length 32768, batch size 1, bf16 (2 bytes per element). The result is 2 × 32 × 8 × 128 × 32768 × 1 × 2 bytes, roughly 4 GiB. If batch size increases to 8, the KV cache for the same configuration requires about 32 GiB. Long-document analysis and multi-turn agent workloads often hit memory limits at this point, not compute limits.

    The following metrics table establishes a unified evaluation standard. All comparisons should be performed on the same hardware, with the same input/output lengths and the same concurrency.

    Metric Meaning Typical Measurement
    Activated parameter ratio Parameters actually computed per token as a fraction of total parameters Derived from model architecture
    Expert load variance Variance in token counts received by experts within the same layer Count tokens per expert per layer
    KV cache memory Cache capacity for a single request or batch Computed by formula, verified with inference framework measurements
    TTFT Time to first token, mainly affected by the prefill phase Fixed input length, report P50 and P95
    TPOT Average time per output token, mainly affected by decode-phase memory traffic Fixed output length, report the average
    Throughput and unit cost Tokens processed per second, and cost per million tokens Measured under fixed hardware and load; cost includes GPU occupancy time
    Accuracy regression Score difference vs. a baseline model on the same evaluation set Same evaluation set and decoding parameters

    2. Sparse Mixture of Experts: Separating Total and Activated Parameters

    In a dense model, every token passes through all parameters. A sparse Mixture of Experts (MoE) model splits the feed-forward network into multiple experts, with a router selecting a small subset of experts for each token. Total parameters can be very large, but each forward pass uses only part of them.

    The typical workflow:

    1. The router scores each expert for every token.
    2. The top-k experts are selected by score.
    3. The token is sent to these experts, and outputs are merged with normalized weights.

    Here is routing sketch code with input checks:

    1. import torch
    2. def topk_route(hidden, router_weight, k=2):
    3. # hidden: [tokens, d_model]; router_weight: [d_model, num_experts]
    4. assert hidden.dim() == 2 and router_weight.dim() == 2
    5. assert hidden.shape[1] == router_weight.shape[0]
    6. assert 1 <= k <= router_weight.shape[1]
    7. logits = hidden @ router_weight
    8. # Softmax over all experts first, then take top-k, then normalize the selected weights.
    9. probs = torch.softmax(logits.float(), dim=-1)
    10. weights, indices = torch.topk(probs, k, dim=-1)
    11. weights = weights / weights.sum(dim=-1, keepdim=True)
    12. return weights.to(hidden.dtype), indices

    Softmax-then-top-k and top-k-then-softmax over the selected logits produce numerically different weights. Either way, the implementation must match what was used during training; otherwise inference results will deviate from the model’s original behavior.

    Worked example: if a layer has 64 experts and each token selects 2, the expert activation ratio for that layer is 2/64, about 3.1%. This only illustrates the arithmetic of sparsity and does not represent any specific model’s specifications. Actual cost savings also depend on communication overhead, the fraction of dropped tokens, and accuracy regression results—activation ratio alone is not sufficient.

    MoE capacity is usually controlled with the expert capacity formula:

    Expert capacity = capacity_factor × tokens_per_batch × k ÷ num_experts

    Example: with 4096 tokens per batch, k = 2, 64 experts, and a capacity factor of 1.25, each expert’s capacity is 1.25 × 4096 × 2 ÷ 64 = 160 tokens. Tokens exceeding capacity are dropped or routed through the residual path. A capacity factor that is too small raises the drop rate and degrades accuracy; one that is too large wastes memory and compute.

    MoE has three main costs:

    • Load imbalance: some experts are overloaded while others sit idle. Load-balancing losses and routing bias terms can mitigate this.
    • Router collapse: a few experts absorb most tokens while the rest are undertrained. Monitor expert load variance.
    • Communication overhead: when experts are spread across multiple GPUs, tokens must be exchanged via all-to-all communication. Communication time can offset compute savings.

    In practice, these issues are managed through the capacity factor, load-balancing losses, and a sound expert parallelism strategy. When choosing parallelism, use profiling tools to check the fraction of per-step time spent on communication.

    3. Hybrid Attention and KV Cache Compression

    Attention is the dominant cost of long contexts. Common optimization approaches fall into two categories: changing how attention is computed, and reducing how much history must be stored.

    The table below compares common attention schemes.

    Scheme Compute (vs. sequence length) Memory Characteristics Best Suited For Main Cost
    Dense full attention Quadratic growth KV grows linearly with length Precise retrieval at arbitrary positions Highest cost for long contexts
    Linear attention Roughly linear Fixed-size state Continuous context, streaming generation Weaker precise long-range localization
    Sliding window attention Roughly linear KV outside the window can be evicted Text with strong local dependencies Information outside the window needs other mechanisms to retain
    Sparse attention (block-sparse or top-k key selection) Depends on selection strategy Requires storing all or part of the KV Tasks requiring cross-segment localization Wrong selection loses critical information

    Selection principles:

    • For tasks dominated by long-range precise retrieval—such as locating clauses in long contracts—keep some full attention layers or use sparse selection.
    • For tasks dominated by continuous text generation—such as long-form summarization and streaming dialogue—linear attention or sliding windows are a better fit.
    • Most hybrid schemes interleave the two attention types across layers. The interleaving ratio should be determined jointly by retrieval tests and perplexity.

    When evaluating hybrid attention, run three types of tests together: perplexity (language modeling ability), retrieval hit rate (insert key information at different positions and check whether the model can answer), and long-context QA accuracy. Perplexity alone cannot reveal long-range information loss.

    Common KV cache compression techniques:

    • Grouped Query Attention (GQA): multiple query heads share a set of KV heads, directly reducing the KV head count.
    • KV quantization: downgrading the cache from bf16 to INT8 or FP8 roughly halves memory. The cost is that quantization error may affect numerical stability on long sequences.
    • Window eviction: keep only a recent window and a small number of key positions. The cost is that information outside the window is not directly accessible.
    • Low-rank or latent compression: project KV into a lower-dimensional space before caching. The cost is extra projection compute, which may increase decode latency.

    Enable compression techniques one at a time, running an accuracy regression after each. When multiple compression techniques are enabled simultaneously, it is hard to identify which one caused the accuracy drop.

    4. Residual Information Fusion and Native Multimodal Input

    Residual information fusion refers to merging representations from different layers or branches into the current layer via gating or weighted combination, aiming to improve information retention and training stability. Designs vary considerably; when selecting a model, rely on papers and open-source implementations rather than naming conventions.

    Costs of fusion designs:

    • Extra parameters and extra memory traffic can increase inference latency.
    • Gating parameters require training to tune; poor initialization can destabilize training.

    Evaluate by comparing training loss curves, downstream accuracy regression results, and the incremental inference latency. Latency deltas should be measured at the same batch size and sequence length.

    Native multimodal input means images, audio, and other content are split into tokens and share the same backbone with text. This removes the need for a separate vision encoding path but increases the token count in the context.

    Example: if each image is split into 1024 vision tokens and a single request contains 4 images, that adds 4096 extra tokens. Per the KV formula, these tokens linearly increase cache memory and lengthen prefill time—that is, TTFT rises.

    Evaluation metrics for multimodal scenarios include: visual question answering accuracy, average tokens per image, TTFT, and per-request cost. Image resolution should align with the