Cutting LLM Inference Costs: Architecture Optimization and Engineering Practices
LLM inference costs are driven by compute per request, memory, and communication. This article explains how MoE sparse activation, hybrid attention, KV Cache compression, quantization, and heterogeneous deployment reduce those costs, and provides practical checkpoints for evaluating each optimization before production rollout.
Reducing the cost of large model inference requires optimizing architecture, adapting the engineering stack, and tracking costs as a single coordinated effort. Optimizing any one layer in isolation rarely delivers stable end-to-end gains. This article covers three areas—MoE sparse activation, memory and latency reduction via attention and KV Cache techniques, and quantization plus heterogeneous deployment—and closes with a checklist table you can use for evaluation.
1. How MoE Reduces Compute Through Sparse Activation
In a traditional dense model, every parameter participates in computing every token, so compute scales with parameter count. A Mixture-of-Experts (MoE) model splits the feed-forward layers into multiple expert networks, with a router selecting only a few experts for each token. Total model parameters can be very large, but only the selected subset actually participates in computation for any given token.
As an illustrative configuration: a model with 320 billion total parameters might activate 18 billion per token—roughly 5.6%. This is just an arithmetic example; the actual activation ratio in real models depends on the number of experts, the top-k value, and the layer structure, so always refer to the model’s official configuration.
The following pseudocode shows the basic top-k routing flow:
import torchdef moe_forward(x, experts, router, top_k=2):# Router scores each token and picks the top_k highest-scoring expertslogits = router(x) # [num_tokens, num_experts]probs = logits.softmax(dim=-1)topk_weights, topk_idx = torch.topk(probs, top_k, dim=-1)topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)output = torch.zeros_like(x)for expert_id, expert in enumerate(experts):# Find tokens routed to this expert; unselected experts skip forward computationtoken_pos, slot = (topk_idx == expert_id).nonzero(as_tuple=True)if token_pos.numel() == 0:continueexpert_out = expert(x[token_pos])# Weighted sum of expert outputs using routing weightsoutput[token_pos] += expert_out * topk_weights[token_pos, slot].unsqueeze(-1)return output
In production, token dispatch and merging across experts are typically handled by dedicated kernels; the loop here only illustrates the logic. The benefits of sparse activation only fully materialize when batching, expert load balancing, and cross-device communication are all healthy. If certain experts become overloaded, the corresponding devices turn into bottlenecks and offset the compute savings.
2. Hybrid Attention and KV Cache Compression for Lower Memory and Latency
Standard attention compute scales quadratically with sequence length—doubling the length roughly quadruples the attention cost. Linear attention uses kernel-function approximations to bring compute down to roughly linear in sequence length. Sparse attention limits how many tokens each token can attend to, reducing the number of attention pairs to compute. Combining both reduces attention compute in long-context scenarios, but long-range retrieval capability may degrade, so dedicated long-context benchmarks are essential.
KV Cache is the other major overhead in long-context inference. Memory usage for a single request can be approximated as:
KV Cache memory ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element × concurrent requests
The factor of 2 accounts for separate Key and Value caches.
Common compression approaches include: quantizing the cache (e.g., FP8 or INT8), evicting unimportant cache entries, sharing caches across layers or heads, and deduplicating or pooling index-related caches. Index pooling schemes may reduce cache copies, but the actual gains depend on the specific implementation, model architecture, and workload—there is no universal number. When evaluating any approach, verify the corresponding paper or open-source implementation, and check the tested model, sequence length, and hardware conditions.
3. Heterogeneous Hardware and Inference Engines: Quantization and Layered Deployment
Quantizing weights from FP16 to INT8 roughly halves weight memory and reduces memory-bandwidth pressure. But the accuracy impact depends on calibration data, quantization granularity (per-tensor or per-channel), and task type. Mathematical reasoning, code generation, and long-chain tasks are typically more accuracy-sensitive than simple Q&A.
Run the same evaluation suite before and after quantization. Fix the random seed or set temperature to 0, then compare accuracy on both general benchmarks and your own business data. If accuracy drops beyond an acceptable threshold, keep the FP16 baseline or quantize only some layers.
The idea behind layered deployment: different layers have different compute density and memory-bandwidth demands, so compute-intensive and memory-intensive layers can be placed on better-matched devices. However, cross-device transfers add latency—gains only materialize when the savings exceed the transfer overhead.
Compute-for-communication trade-off: in distributed inference, inter-node communication can become the bottleneck. Adding some redundant computation to reduce synchronization rounds can improve throughput. This only works when communication is genuinely the bottleneck; otherwise it just burns extra compute.
For domestic-accelerator (non-NVIDIA) chip adaptation, pay attention to memory capacity and memory bandwidth. Before launch, confirm operator coverage, compiler versions, and framework compatibility. Some operators may need to fall back to CPU or hand-written implementations, which can significantly hurt performance.
Open-source inference frameworks like SGLang and vLLM provide batching schedulers, KV Cache management, and quantization support, making them good starting points. When choosing one, check the supported model list, hardware backends, and community maintenance status. Engineering teams typically also use container platforms for elastic scaling, object storage for model weights, and logging/monitoring systems to track latency, throughput, and error rates—choose products based on your existing environment.
The table below summarizes the benefits and risks of each optimization:
| Optimization | Main Benefit | Main Risk | Pre-Launch Validation |
|---|---|---|---|
| MoE sparse activation | Lower compute per token | Uneven expert load, higher communication overhead | Monitor per-expert load and device utilization |
| Hybrid attention | Reduced long-context attention compute | Possible degradation in long-range retrieval | Long-context retrieval and QA tests |
| KV Cache compression | Lower memory usage, higher concurrency | Cache error accumulation, output quality fluctuation | Compare outputs and latency before/after compression |
| INT8 quantization | Lower memory and bandwidth requirements | Accuracy drops on math, code, and similar tasks | Compare on the same eval set with a defined accuracy threshold |
| Layered deployment | Better hardware utilization per layer | Cross-device transfer latency | End-to-end latency and throughput benchmarks |
