LLM Inference Cost Reduction Through Hardware-Software Co-Design: From Chips to Operators

    This article examines the main sources of LLM inference cost and how prefill and decode phases, hardware selection, parallelism, fused operators, MoE communication, model structure, low-precision computation, and a practical cost-analysis workflow affect efficiency. It emphasizes identifying the bottleneck before choosing an optimization layer, and it provides guidance for analyzing and reducing cost per token in production inference services.

    1. Why Inference Cost Becomes a Core Metric

    Model training is a one-time investment, while inference runs continuously on every user request. As service scale grows, the cost per token directly determines whether a product can be profitable and how much room exists for pricing strategy.

    Inference cost mainly consists of three parts:

    • Compute consumption: compute-unit time used by matrix multiplication and attention calculations.
    • Memory and bandwidth consumption: memory capacity occupied by weight reads, intermediate activations, and KV cache, plus the bandwidth consumed by reading and writing them.
    • Communication consumption: time spent synchronizing parameters and distributing data across multiple cards or nodes.

    There is no fixed hierarchy among these three. In short-text, high-concurrency scenarios, bandwidth often becomes the bottleneck first. In long-context scenarios, KV cache capacity and read overhead grow rapidly. Models using a mixture-of-experts structure are more likely to be constrained by communication. Therefore, cost reduction should first identify where the bottleneck is, then decide which layer to optimize.

    2. Prefill and Decode: Resource Characteristics of Two Phases

    A complete generation process can be divided into two phases.

    Prefill phase: the model processes all tokens in the user input at once. The computation volume is large, matrix operations can be highly parallel, compute-unit utilization is usually high, and the workload is compute-intensive.

    Decode phase: the model generates only one new token at a time and must read all weights and the historical KV cache. The per-step computation volume is small, but memory access volume is large, making this phase memory-bound.

    The two phases have different hardware requirements. Prefill depends more on peak compute, while decode depends more on memory bandwidth and capacity. If the same hardware configuration serves both workloads, one side will usually leave resources idle. Some systems split the two phases into different resource pools and tune them separately. This is the idea behind prefill-decode disaggregated deployment.

    Below is a simplified function for estimating the upper bound of decode throughput. It assumes each decode step reads the weights once and reads the KV cache for each request in the batch, while ignoring compute and communication time. It should therefore be used only to judge order of magnitude:

    1. def decode_throughput_upper_bound(mem_bw_gb_s, weight_bytes,
    2. kv_bytes_per_token, context_len,
    3. batch_size):
    4. # Total bytes read per decode step
    5. kv_bytes_per_req = kv_bytes_per_token * context_len
    6. bytes_per_step = weight_bytes + batch_size * kv_bytes_per_req
    7. steps_per_sec = mem_bw_gb_s * 1e9 / bytes_per_step
    8. # Each step generates one token for each request in the batch
    9. return steps_per_sec * batch_size

    This model shows two things: increasing batch size can amortize weight-read overhead, but longer contexts increase KV cache reads and offset part of the benefit. During tuning, use this kind of estimate to set direction first, then validate with actual trace data.

    3. Tradeoffs at the Hardware Layer

    Common evaluation dimensions when choosing accelerators include:

    1. Peak compute capability: determines the theoretical speed limit of the prefill phase.
    2. Memory bandwidth: determines how much data can be read per second during decode and is usually directly related to throughput.
    3. Memory capacity: determines how many weights, how long a context, and how large a batch can be accommodated.
    4. Interconnect bandwidth: determines whether communication can keep up with computation during multi-card collaboration.
    5. Effective throughput per unit of power: determines long-term electricity and data center costs.

    These metrics involve tradeoffs. Pursuing peak compute alone may leave resources idle during decode. Increasing bandwidth without enough capacity may limit batch size. A mature approach is to derive the required configuration from the request-length distribution, latency requirements, and concurrency of the business, rather than relying on a single parameter ranking.

    A supernode refers to organizing multiple accelerator cards into a logical whole through high-speed interconnect, so that their communication latency and bandwidth approach those inside a single machine. This type of design mainly serves models that require large-scale parameter sharing or large-scale expert parallelism.

    4. Communication Cost of Parallel Scheduling

    Once model size exceeds single-card capacity, parallel partitioning becomes necessary. Common approaches include:

    • Tensor parallelism: splits the matrices of a single layer across multiple cards by dimension. Collective communication is required after each layer, making it sensitive to interconnect bandwidth.
    • Pipeline parallelism: places different layers on different devices and passes activations between devices. It suits models with many layers and relatively small layers, but bubbles are easy to produce.
    • Expert parallelism: places different experts in a mixture-of-experts model on different devices. Tokens must be dispatched to the corresponding devices according to routing results.

    Choosing a parallelism method is essentially balancing computation, memory, and communication. Finer partitioning reduces pressure on each card but increases the number of communication operations. Scheduling should overlap communication with computation as much as possible, for example by asynchronously transmitting data needed by the next layer while computing the current layer.

    5. Fused Operators: Reducing Memory Round Trips

    Deep learning models contain many elementwise operations, such as normalization, residual addition, activation functions, and quantization. If each operation runs separately, every step writes intermediate results back to memory and reads them again in the next step. Memory access overhead often exceeds the computation itself.

    Operator fusion combines multiple adjacent operations into one kernel so that intermediate results remain in on-chip cache or registers. Here is an illustrative example:

    1. # Unfused: each step reads and writes memory
    2. y = norm(x) # read x, write y
    3. y = y + residual # read y and residual, write y
    4. q = quantize(y) # read y, write q
    5. # Fused: read once, write once
    6. q = fused_norm_residual_quant(x, residual)

    The benefit of fusion depends on data dependencies between operations and on on-chip resource size. Fusing too much increases register pressure in the kernel and may reduce parallelism. In practice, use performance profiling to find operation sequences with high memory-access share and fuse them in a targeted way.

    6. Communication Bottlenecks in Mixture-of-Experts Models

    The core of a mixture-of-experts structure is routing: each token passes through only a few experts, so the total parameter count can be large while the computation per pass remains manageable. However, routing also brings two problems.

    First, tokens need to be dispatched and collected across devices, creating all-to-all communication. Second, different experts may receive very different numbers of tokens, causing some devices to be overloaded while others wait, reducing overall utilization.

    Common mitigation methods include:

    • Load-balancing constraints: adding auxiliary losses during training to reduce extreme imbalance in expert load.
    • Grouped routing limits: limiting the number of device groups each token can access to reduce cross-node communication volume.
    • Communication-computation overlap: sending the next batch of data while expert computation for the current batch proceeds.
    • Low-precision transmission: using lower-bit-width data formats to transmit activations when precision is acceptable.

    Below is an illustration of the routing process:

    1. def route(tokens, gate_fn, top_k):
    2. scores = softmax(gate_fn(tokens)) # score of each token for each expert
    3. expert_ids = topk_indices(scores, top_k)
    4. weights = normalize(topk_values(scores, top_k))
    5. return expert_ids, weights

    The routing function itself has little computation. The real cost lies in the dispatch and combine operations afterward. Therefore, when evaluating MoE inference performance, communication time should be measured separately rather than looking only at forward computation time.

    7. Co-Design of Model Structure and Hardware

    Inference efficiency depends heavily on model structure. Methods for reducing KV cache size, such as grouped-query attention, low-rank compression, and combinations of sliding-window and sparse attention, all aim to reduce memory-access pressure during decode.

    The key is that model structure choices should consider both accuracy and hardware execution efficiency. An attention variant may have lower computational cost on paper, but if it introduces a large amount of irregular memory access, it may not be faster in practice. Therefore, the earlier model teams and systems teams align on requirements, the more they can avoid performance compromises later.

    This co-design does not mean serving only one specific hardware type. A general approach is to first determine the memory-access patterns and parallelism methods of operators, then choose structures that map efficiently to those patterns.

    8. Tradeoffs of Low-Precision Computation

    Reducing numerical precision is a common way to improve throughput and reduce memory usage. Common data formats include half-precision floating point, bfloat16, eight-bit floating point, and eight-bit integer.

    When using low precision, pay attention to the following:

    1. Weight quantization and activation quantization have different sensitivity; activations are usually harder to quantize.
    2. Calibration with representative data is needed, and accuracy degradation should be validated on the target task.
    3. Attention computation and normalization layers are more sensitive to precision and can retain higher precision.
    4. Quantization changes the numerical range and affects overflow and clipping, so the output distribution of key layers should be checked.

    Low precision is not a cost-free optimization. It requires a supporting calibration process, accuracy regression tests, and monitoring mechanisms.

    9. Engineering Practice: An Executable Cost Analysis Workflow

    To analyze the cost of your own inference service, proceed as follows:

    1. Collect runtime traces: use profiling tools to record event timelines under a real workload, including kernel execution, memory copies, and communication operations.
    2. Separate phases: measure latency, throughput, and memory usage for prefill and decode separately.
    3. Classify bottlenecks: group time consumption into compute, memory access, and communication, and find the largest category.
    4. Locate hotspots: within the largest category, identify the most time-consuming operators or communication operations.
    5. Define an optimization plan: choose fusion, parallelism adjustments, low precision, or structural changes for the hotspots.
    6. Run regression validation: check throughput, latency, and output quality together to confirm that the optimization does not introduce accuracy or stability issues.
    7. Convert to cost: use the hardware occupancy time per token and unit price to calculate the change in cost per million tokens.

    Each optimization round should leave comparable data behind. Without a baseline, it is difficult to judge whether an optimization conclusion is truly effective.

    10. Issues That Require Ongoing Attention

    Inference optimization is not a one-time task. Request-length distributions change, model versions are updated, and hardware drivers and inference frameworks continue to evolve. It is advisable to establish the following habits:

    • Run regression tests regularly with a fixed benchmark workload and monitor changes in key metrics.
    • Set separate metrics and alert thresholds for long-context and high-concurrency scenarios.
    • Include inference cost evaluation during model selection to avoid reactive fixes after launch.
    • Keep complete analysis records for team reviews and onboarding.

    The value of cost optimization ultimately appears through stable service quality and predictable unit cost.