Three Paths to Reduce LLM Inference Costs: Sparse Experts, Hybrid Attention, and Shallow Networks

    Large language model (LLM) inference costs are primarily driven by per-token compute, memory footprint for weights and caches, and memory bandwidth for data reading during decoding. This article explores three architectural approaches to mitigate these costs: sparse experts (Mixture of Experts), hybrid attention mechanisms, and shallow residual networks. It details core evaluation metrics, implementation specifics including routing and load balancing, strategies for compressing the KV cache, and cost estimation formulas to guide architecture selection and performance tuning.

    I. Background and Metrics

    Large language model (LLM) inference costs stem from three main areas: the compute required per token, the memory occupied by weights and caches, and the bandwidth required to read data from memory during each decoding step. While training costs can be amortized as a one-time expense, online inference incurs continuous costs per request, making architectural optimization critical for these three overheads.

    Before evaluating an architecture, it is essential to define several metrics:

    • Total Parameters: Determines model capacity. Weights must reside entirely in GPU or system memory, directly dictating the weight memory footprint.
    • Active Parameters: The parameters actually involved in computing each token. For dense models, this equals the total parameter count.
    • KV Cache Size: During long-context inference, the cached Keys and Values per layer grow linearly with the sequence length.
    • Throughput and Latency: Includes Time To First Token (TTFT), Time Per Output Token (TPOT), and tokens generated per second.

    A calculation note is necessary here: the forward compute for linear layers can be roughly estimated as approximately 2 × active parameters FLOPs per token. This estimate only includes matrix multiplications in linear layers, excluding attention score computation, softmax, normalization, inter-expert communication, and memory access overhead. Therefore, it should only be used for order-of-magnitude comparisons.

    II. Sparse Experts: Decoupling Total and Active Parameters

    In dense models, every token passes through all feedforward network parameters. Mixture of Experts (MoE) splits the feedforward network into multiple experts, where a router selects a small subset of experts to participate in the computation for each token. The model’s total parameter count can be massive, while a single forward pass only utilizes a fraction of it.

    The standard routing practice computes a score for each expert per token, selects the top-k experts, and re-normalizes those k scores. The following code demonstrates this process:

    1. import torch
    2. import torch.nn.functional as F
    3. def topk_route(hidden, router_weight, k=8):
    4. # hidden: [tokens, d_model]
    5. # router_weight: [d_model, num_experts]
    6. logits = hidden @ router_weight
    7. scores = F.softmax(logits, dim=-1)
    8. topk_scores, topk_idx = torch.topk(scores, k, dim=-1)
    9. topk_scores = topk_scores / topk_scores.sum(dim=-1, keepdim=True)
    10. return topk_idx, topk_scores

    Prerequisites for running this code:

    • The PyTorch version must support torch.topk and scatter_add_ (common in version 1.x and above).
    • The last dimension of hidden must equal the first dimension of router_weight (d_model).
    • k <= num_experts must hold true; otherwise, torch.topk will throw an error.
    • The code above only handles routing, not expert computation. In practice, you must dispatch each token to its corresponding experts and weight and merge the outputs.

    Normalization methods vary across implementations. Taking the top-k from full softmax scores and re-normalizing yields the same mathematical result as applying softmax to the top-k logits. However, some models switch to sigmoid gating or add bias terms during expert selection to aid balance. In such cases, the normalization method and gradient behavior will differ, so you should refer to the specific model’s implementation.

    Load Balancing

    If a few experts are consistently selected, others will be under-trained. In multi-GPU parallel setups, hotspots will form on the devices hosting these popular experts, slowing down the overall process. Three common mitigation strategies exist:

    1. Auxiliary Balance Loss: Penalizes the inconsistency between the actual allocation ratio and the routing probability.
    2. Expert Capacity Limit: The maximum number of tokens an expert can receive per batch, typically calculated as: Capacity = ceil(capacity_factor × num_tokens × k / num_experts).
    3. Overflow Strategy: Tokens exceeding capacity can be dropped or routed via the residual path to skip that layer. Dropping results in information loss, requiring checks during both training and inference.

    A common implementation of the auxiliary loss is as follows:

    1. def load_balance_loss(scores, topk_idx, num_experts):
    2. # scores: [tokens, num_experts], routing probability of each token to each expert
    3. # topk_idx: [tokens, k], selected expert indices for each token
    4. counts = torch.zeros(num_experts, device=scores.device)
    5. counts.scatter_add_(
    6. 0,
    7. topk_idx.flatten(),
    8. torch.ones_like(topk_idx.flatten(), dtype=counts.dtype),
    9. )
    10. frac_tokens = counts / topk_idx.numel() # Actual allocation ratio per expert
    11. mean_prob = scores.mean(dim=0) # Average routing probability per expert
    12. return num_experts * torch.sum(frac_tokens * mean_prob)

    Gradients of this loss only flow through mean_prob because the allocation ratio is a discrete count. The loss coefficient requires empirical tuning, commonly in the range of 1e-2 to 1e-3. Excessively large values will suppress the model’s specialized learning of experts.

    Expert Parallelism Communication and Risks

    When experts are distributed across multiple GPUs, each layer requires two all-to-all communications: one to send tokens to their corresponding experts, and one to retrieve the results. The unidirectional communication volume can be roughly estimated as: num_tokens × k × d_model × bytes_per_element. The communication volume grows with k and batch size, meaning expert parallelism might offer limited benefits for small batches but become a bottleneck for large ones. You should evaluate network bandwidth and parallelism strategies before deployment.

    Metric Relationship with Active Parameters Relationship with Total Parameters Primary Impact
    Weight Memory No direct relationship Grows linearly with total parameters Number of GPUs and memory capacity required
    Per-Token Compute Grows linearly with active parameters No direct relationship Compute throughput
    Expert Communication Volume Grows with k No direct relationship Multi-GPU bandwidth and latency

    III. Hybrid Attention: Compressing Long-Context Memory and Bandwidth

    Standard attention saves Keys and Values for every token in every layer, known as the KV Cache. Its size can be estimated as: batch × sequence_length × 2 × num_layers × num_kv_heads × head_dim × bytes_per_element.

    Consider the following example assumptions (not parameters from any specific model): 32 layers, 8 KV heads, head_dim of 128, using bf16 (2 bytes per element), batch of 1, and a sequence length of 32768. The cache per token is 2 × 8 × 128 × 2 × 32 = 131072 bytes, or 128 KB. The cache for the entire sequence is approximately 4 GiB, and it grows linearly with the sequence length.

    During the decoding phase, every generated token requires reading the entire KV Cache from memory once. Therefore, in long-context scenarios, decoding speed is typically memory-bandwidth bound rather than compute bound.

    The idea behind hybrid attention is to apply different attention forms across different layers. Common practices include:

    • Keeping full attention in some layers to handle long-range retrieval.
    • Using sliding window attention in some layers, caching only the most recent w tokens, making the cache size independent of the overall sequence length.
    • Using linear attention or state space models in some layers, replacing per-token caching with a fixed-size state.

    This design reduces the cache growth rate, but the trade-off is a potential decline in long-range dependency capabilities, and it requires corresponding kernel support. The proportion of full attention layers, the window size, and the arrangement of layers all need to be validated on the target task. If the task relies on precise retrieval within long documents, you should focus on testing retrieval-specific metrics rather than just looking at average perplexity.

    IV. Shallow Residual Networks: Reducing Layers While Maintaining Expressivity

    Residual connections take the form x + F(x). They allow signals and gradients to propagate across layers directly, making deeper networks easier to train while enabling shallower networks to maintain a certain level of expressivity at the same width.

    Reducing the number of layers yields two direct benefits: fewer serial compute steps, which decreases both TTFT and the number of kernel launches per decoding step; and lower weight and KV Cache footprints, as each layer must store its own cache.

    Here is a minimal residual block example, depending on PyTorch:

    1. import torch.nn as nn
    2. class ResidualBlock(nn.Module):
    3. def __init__(self, dim):
    4. super().__init__()
    5. self.norm = nn.LayerNorm(dim)
    6. self.ff = nn.Sequential(
    7. nn.Linear(dim, 4 * dim),
    8. nn.GELU(),
    9. nn.Linear(4 * dim, dim),
    10. )
    11. def forward(self, x):
    12. return x + self.ff(self.norm(x))

    Shallow does not mean equivalent. At the same parameter count, reducing layers usually requires increasing the width or the number of experts, which alters the memory and communication structure. You should use ablation studies to compare the quality across different depths and record the results alongside latency and memory metrics.

    V. Cost Estimation and Reproduction Checklist

    Common Formulas

    Item Approximate Formula Scope Description
    Per-Token Linear Layer Compute ~2 × Active Parameters FLOPs Only counts linear layer matrix multiplications
    Weight Memory Total Parameters × Bytes per Parameter Excludes activations and runtime overhead
    KV Cache batch × seq_length × 2 × num_layers × num_kv_heads × head_dim × bytes Only counts caches for full attention layers
    MoE Unidirectional Communication num_tokens × k × d_model × bytes Two all-to-all per layer; count separately

    Example Calculation

    Consider the following hypothetical values: total parameters of 100B, active parameters of 13B, and weights using bf16. The weight memory is approximately 100 × 10^9 × 2 bytes, or about 200 GB. The per-token linear layer compute is approximately 2 × 13 × 10^9 = 2.6 × 10^10 FLOPs, or about 26 GFLOPs. These numbers only illustrate the usage of the formulas and do not represent any actual model.

    Reproduction Steps for Evaluation

    1. Fix the hardware, drivers, framework, and model versions, and record all version numbers.
    2. Set input and output length distributions, covering both short-text and long-context scenarios.
    3. Warm up for several rounds before timing. Repeat each configuration multiple times and report the median and variance.
    4. Record Time To First Token (TTFT), Time Per Output Token (TPOT), throughput, peak memory, and multi-GPU communication time separately.
    5. Evaluate quality metrics on the target task, and specifically test retrieval capabilities in long-context scenarios.
    6. Change only one factor at a time (e.g., number of experts, k, window size, or number of layers) to facilitate attribution.

    VI. Conclusion and Applicable Boundaries

    Sparse experts are suitable for scenarios that require a large total capacity but want to control per-token compute, at the cost of handling load balancing and inter-expert communication. Hybrid attention is ideal for long-context inference, provided that the proportion of full attention layers can preserve retrieval capabilities. Shallow residual networks can reduce latency and cache footprint, but ablation studies must confirm that quality does not degrade.

    None of these three methods can be judged in isolation from specific conditions. Inference costs depend on hardware, parallelism strategies, sequence length, and batch size. The same architecture may perform completely differently under small versus large batches, or short-text versus long-context conditions. Therefore, when selecting an architecture, you should first estimate using the formulas above, and then validate with reproducible experiments using a consistent set of metrics.