Reducing LLM Inference Costs: Hardware-Software Co-Optimization Techniques Explained

    This article explains how to reduce large language model inference costs across model architecture, compute hardware, inference frameworks, and serving scheduling. It covers the Prefill and Decode stages, KV cache compression, MoE communication overhead, low-precision computing, operator fusion, trace-based performance analysis, and request scheduling design.

    1. Why Inference Cost Is a Core Constraint

    After a large model is trained, inference is the stage that keeps generating costs. Every user request consumes compute, GPU memory, and bandwidth. As context length grows and concurrency rises, the cost per token directly determines whether a service can be profitable. Reducing inference cost therefore usually requires considering four layers together: model architecture, compute hardware, the inference framework, and serving scheduling.

    Optimizing a single layer often yields limited gains. For example, if a model architecture cuts attention computation in half but the scheduling layer cannot group requests into larger batches, GPU utilization stays low and the overall cost reduction is small. Cost optimization is fundamentally an end-to-end systems problem.

    2. The Two Stages of Inference Workload

    LLM inference typically consists of two stages: Prefill and Decode.

    • Prefill: Processes the input prompt in one pass. Input tokens can be computed in parallel, so the workload is compute-intensive and well suited to fully using compute capacity.
    • Decode: Generates output tokens one at a time. Each step processes only one new token but must read the entire historical KV cache. The workload is memory-access-intensive and highly sensitive to memory bandwidth.

    The two stages have different bottlenecks, so many systems deploy them separately or allocate resources in different proportions. Metrics should also be tracked separately. Time to first token (TTFT) mainly reflects Prefill efficiency, while time per output token (TPOT) mainly reflects Decode efficiency.

    3. Compressing Attention and the KV Cache

    During Decode, standard multi-head attention must cache the Key and Value for every layer and every attention head. The KV cache size can be estimated with the following formula:

    KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element

    Example code:

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, bytes_per_elem=2):
    2. # The factor 2 accounts for both the Key and Value caches
    3. return 2 * layers * kv_heads * head_dim * seq_len * batch * bytes_per_elem
    4. # Example parameters, for demonstrating the calculation only
    5. size = kv_cache_bytes(layers=60, kv_heads=8, head_dim=128, seq_len=128_000, batch=4)
    6. print(f"{size / 1024**3:.1f} GiB")

    Both context length and batch size scale the cache linearly. Common ways to reduce cost fall into the following categories:

    1. Reduce the number of KV heads. For example, grouped-query attention lets multiple query heads share the same set of Keys and Values.
    2. Apply low-rank projection or other compression to the cache, reducing the storage dimension per token.
    3. Quantize the cache, reducing precision from FP16 to INT8 or lower.
    4. Keep only the cache entries for important tokens. Examples include a sliding window or a sparse strategy based on importance scores.

    Each method has an accuracy cost. In practice, teams usually need to balance perplexity, long-context retrieval accuracy, and memory savings, and run regression tests on representative tasks.

    4. MoE Architecture and Communication Overhead

    Mixture-of-Experts (MoE) models activate only a subset of experts for each token. The total parameter count can be very large while the compute per forward pass stays manageable. The cost is that experts are distributed across multiple GPUs. Tokens must be routed to the corresponding experts, and the results must be gathered afterward. The core of this process is all-to-all communication.

    Communication overhead is mainly affected by the following factors:

    • The total number of experts and the number of experts hosted on each GPU;
    • The data transfer volume determined by the top-k routing strategy;
    • The bandwidth and latency of the interconnect between GPUs;
    • Whether computation and communication can overlap.

    The following example computes the load share of each expert to check whether routing is skewed:

    1. import numpy as np
    2. def expert_load(router_logits, top_k=2):
    3. # router_logits has shape [num_tokens, num_experts]
    4. topk_idx = np.argsort(-router_logits, axis=1)[:, :top_k]
    5. counts = np.bincount(topk_idx.flatten(), minlength=router_logits.shape[1])
    6. return counts / counts.sum()
    7. logits = np.random.randn(4096, 16)
    8. load = expert_load(logits)
    9. print("Max expert load share:", round(load.max(), 3), "Ideal mean:", round(1 / 16, 3))

    If an expert’s load is significantly above the mean, the GPU hosting it becomes a bottleneck, and other GPUs sit idle waiting for it. Common remedies include adding an auxiliary load-balancing loss, setting an expert capacity limit, and replicating popular experts.

    5. Low-Precision Computing

    Low-precision computing reduces memory footprint, cuts memory traffic, and improves compute utilization. Common data types include FP16, BF16, FP8, and INT8. Three factors should guide the choice:

    • Whether the target hardware natively supports the precision;
    • Whether the numerical range of weights and activations fits the precision;
    • How much accuracy loss the business task can tolerate.

    In practice, per-channel or group-wise quantization is common, and higher precision is kept for layers that are sensitive to error. Before deployment, compare task metrics on representative datasets. Do not rely on a single benchmark score.

    6. Operator Fusion and Compilation Optimization

    During inference, much of the time goes to the launch overhead of small operators and to reading and writing intermediate results. Take normalization, scaling, residual addition, and activation functions as an example. If they run one by one, each step writes its intermediate tensor back to GPU memory. Operator fusion merges these steps into a single kernel, significantly reducing memory accesses.

    The following pseudocode illustrates the idea:

    1. # Before fusion: multiple reads and writes to GPU memory
    2. y = layer_norm(x)
    3. y = y * scale
    4. y = gelu(y + residual)
    5. # After fusion: a single kernel performs the computation, and intermediate results stay in on-chip cache
    6. y = fused_norm_scale_residual_act(x, residual, scale)

    Compilers also handle graph-level optimizations, including constant folding, operator reordering, memory reuse, and automatic tuning. Confirm optimization results through measurement. Theoretical estimates serve only as a reference.

    7. Trace-Based Performance Analysis

    A trace is a time-ordered record of a program’s execution. It includes the start and end times of each kernel, memory copies, communication events, and idle intervals. A trace can answer three questions:

    1. Are compute units idle for long periods?
    2. Do communication and computation overlap effectively?
    3. Which operators consume the most execution time?

    Use the following workflow for analysis:

    1. Fix the input length and batch size, and capture several steps after the system reaches stable operation;
    2. Aggregate time by operator category, separating compute, memory access, and communication overhead;
    3. Look for bubbles in the timeline to locate synchronization wait points;
    4. Compare key metrics before and after optimization to confirm that the gains come from the intended areas.

    Tracing adds overhead of its own. Enable it only during analysis, and avoid long sampling periods on production traffic.

    8. Concurrent Scheduling and Serving Layer Design

    The throughput of an inference service depends on its scheduling policy. Continuous batching allows new requests to fill open slots in an existing batch, which reduces GPU idle time. In addition, queues can be divided by request length and priority so that long-context requests do not block short ones.

    The serving layer usually also needs the following common components:

    • Object storage: stores model weights, offline data, and evaluation results;
    • Message queues: buffer traffic bursts and decouple request intake from inference execution;
    • Container platform: provides unified deployment and supports elastic scaling;
    • Logging, monitoring, and alerting: collect metrics such as TTFT, TPOT, queue length, and GPU memory usage.