Lowering Per-Token Inference Cost for Large Language Models Through Hardware-Software Co-Optimization

    This article explains how to reduce the unit cost of large model inference by combining hardware and software optimization. It covers how to collect performance traces, identify bottlenecks, analyze prefill and decode separately, reduce communication overhead in MoE models, manage KV cache pressure, apply low-precision quantization with accuracy checks, and calculate cost per token. Readers will learn how to turn profiling results into specific optimization actions.

    The cost of large model inference depends on hardware, energy consumption, and serving efficiency. On the same accelerator card, the cost per token can differ several times over depending on batch size, context length, and precision. For this reason, cost reduction cannot rely on peak compute alone. It requires analysis of execution traces, memory access behavior, and system configuration, layer by layer. This article follows that analysis order. It covers how to collect performance data, how to identify bottlenecks, and how to put hardware-software co-optimization actions into practice.

    1. Using Traces to Locate Bottlenecks

    A trace records, over a fixed time window, the start time, duration, resource usage, and communication events of each operator on a device. It breaks a general symptom such as “lower overall throughput” into specific operators or specific waits.

    When collecting a trace, keep three points in mind. First, complete a warm-up run so that model loading and first-time compilation are excluded. Second, choose a stable time window, such as several consecutive decode steps, instead of a random slice. Third, change only one variable per comparison and keep the model, batch size, and precision fixed, so that the baseline stays valid.

    When analyzing a trace, focus on the following metrics:

    1. Compute unit utilization: whether matrix operations use the available compute capacity. Low utilization often comes from small batches or highly fragmented operators.
    2. Memory bandwidth utilization: during decode, most of the time goes to reading weights and the KV cache. If bandwidth is close to saturation while compute sits idle, the bottleneck is memory access.
    3. Operator launch count and average duration: a high launch count with short durations usually means insufficient fusion and a large share of time spent on scheduling overhead.
    4. Overlap ratio of communication and computation: in MoE models, communication time that is not covered by computation adds directly to latency.

    Each metric should map to an action you can take. When memory bandwidth is saturated, first consider operator fusion, reducing intermediate result writes, or changing how the KV cache is stored. When operator launches are too frequent, consider graph compilation or merging adjacent small operators.

    2. Analyzing Prefill and Decode Separately

    The prefill stage processes the entire input in one pass. Its matrices are large, so it is mainly limited by compute capacity. The decode stage generates one token per step, but it must read all model weights and the cached KV data. It is therefore mainly limited by memory bandwidth. The two stages have different bottlenecks, so they need different optimization methods.

    Memory pressure during decode grows with the number of concurrent requests and the context length. More concurrent requests consume more KV cache memory, which limits how many requests one card can serve at the same time. To estimate how much concurrency a card can support, look at both memory capacity and memory bandwidth, not only the compute specification.

    A common approach is to deploy prefill and decode on separate instance groups and configure batching policies for each. This approach adds the cost of transferring state between instances and makes scheduling more complex. It is better suited to scenarios with long inputs and stable request volume. Whether to adopt it should be decided by comparing results on real traffic.

    3. MoE Communication: Overlapping Computation with Communication

    Each token in an MoE model is routed to a subset of experts. In multi-card deployments, the experts are distributed across devices, so each layer produces one or two All-to-All communication operations. The communication volume grows with the number of tokens and experts. Routing results also affect it, which often leads to unbalanced loads.

    The core goal is to reduce the time that communication occupies on the critical path. There are three ways to do this:

    • Routing constraints: limit the number of devices each token can be sent to, which reduces the amount of data transferred across nodes.
    • Load balancing: monitor the number of tokens each expert receives, and replicate or relocate hot experts so that no single card becomes a waiting point.
    • Pipelined overlap: split a batch into smaller chunks so that communication for one chunk runs at the same time as computation for another.

    To verify the result, measure the share of total step time spent on communication that is not covered by computation. If this share decreases, the overlap is working. Splitting the work too finely, however, increases scheduling overhead, so you need to find a balance point between the two.

    4. How Attention Design Shapes KV Cache Pressure

    The evolution of attention mechanisms has centered on the KV cache. Multi-head attention (MHA) keeps separate K and V vectors for each head. Multi-head latent attention (MLA) compresses K and V into a low-dimensional latent vector for storage and restores them when needed, which significantly reduces the cache size. Some newer models also explore more aggressive compression or sparse attention schemes.

    These designs place different demands on hardware. A smaller cache reduces memory bandwidth pressure, but the restoration step adds computation. If the ratio of compute to memory access on a chip does not match the new structure, the gains can be offset. Hardware design should therefore take the direction of model evolution into account and leave headroom in on-chip memory capacity, interconnect bandwidth, and the balance of compute units.

    When evaluating these designs, use end-to-end test results for the same model on the same hardware. Speedup measured on a single operator is not a reliable basis for judgment.

    5. Low-Precision Computation and Accuracy Risks

    Low-precision computation reduces memory usage and increases the amount of computation per unit time. INT8 and FP8 are common choices. The hardware must natively support the chosen format. Otherwise, the benefit of quantization can be cancelled out by dequantization overhead.

    There are two main quantization approaches. Post-training quantization (PTQ) does not require retraining. It only needs a small batch of calibration data to determine the quantization parameters. PTQ is quick to implement, but it is sensitive to outliers, and accuracy loss can be significant. Quantization-aware training (QAT) simulates quantization error during training. It usually preserves accuracy better, but it requires additional training resources.

    In practice, follow these steps:

    1. Prepare a calibration set that covers the input distribution of your real workload, not only general-purpose text.
    2. Build an accuracy evaluation set that includes both task metrics and long-context samples.
    3. Keep higher precision for sensitive layers, such as the output layer and parts that are sensitive to outliers.
    4. Define a fallback policy. When accuracy for a certain type of request falls below a set threshold, switch that request to a higher-precision version.

    6. How to Calculate Cost

    You can estimate the unit cost per token with the following formula:

    Cost per token = total hourly cost of one card ÷ effective output tokens per hour

    Total hourly cost of one card includes hardware depreciation, electricity, and an allocated share of operations costs. Effective output tokens are the tokens generated while meeting the latency target. Requests that exceed the latency limit are not counted.

    For an example with assumed figures, suppose the total hourly cost of one card is 10