LLM Inference Performance Optimization: An Engineering Guide

    This article presents an engineering guide to optimizing large language model (LLM) inference. It covers the key latency and throughput metrics, how to identify compute-, memory-, and scheduling-bound bottlenecks, and practical operator-level techniques such as operator fusion, memory access optimization, low-precision computation, and reliable benchmarking. It then discusses system-level methods including continuous batching, KV cache management, and request scheduling, followed by considerations for edge and local deployment. The article closes with a repeatable performance analysis workflow and practices for community collaboration and toolchain automation.

    1. Why LLM Inference Needs Dedicated Optimization

    After model training is complete, inference is often the component that continues to consume resources. Each request goes through tokenization, prefill, token-by-token decode, and result return. Training focuses on throughput and convergence, while inference must balance time to first token, per-token generation speed, concurrency, and unit cost. These metrics often constrain one another: increasing batch size can improve overall throughput, but it may also lengthen the wait time for an individual request.

    Therefore, inference optimization should not chase the peak of a single metric. It should be designed around the business service-level objectives (SLOs), clearly defining which metrics must be met and which can be allowed to trade off.

    2. Identify the Bottleneck First: Compute, Memory, and Scheduling

    Inference performance bottlenecks generally fall into three categories.

    1. Compute Bound: When matrix multiplications are large, the utilization of compute units determines execution speed. The prefill stage usually falls into this category.
    2. Memory Bound: During decode, generating each token requires reading all weights and the historical KV cache. Data movement often takes longer than computation, making bandwidth the main limit.
    3. Scheduling Bound: Requests have different lengths, leading to waiting and idling within a batch and low device utilization. This type of problem is not caused by the operator itself and must be addressed at the system level.

    The Roofline Model can help determine the bottleneck type. First calculate the arithmetic intensity of each operator, which is the ratio of floating-point operations to memory access bytes:

    1. Arithmetic intensity = FLOPs / Bytes accessed
    2. Attainable performance = min(peak compute, arithmetic intensity × peak bandwidth)

    If arithmetic intensity is below the hardware threshold, the operator is bandwidth-limited, and optimization should focus on reducing data movement. If it is above the threshold, the focus should be on improving compute unit utilization.

    3. Operator-Level Optimization

    3.1 Operator Fusion

    If multiple elementwise operations, such as bias addition, activation functions, and normalization, are launched separately, each step must write intermediate results back to memory and read them out again. After fusion, intermediate results remain in on-chip cache or registers, reducing memory accesses.

    Take y = gelu(x + bias) as an example. Without fusion, intermediate tensors are read and written twice. When fused into a single operator, the input is read once and the result is written once. For large tensors, this change can have a clear impact on latency.

    3.2 Memory Access Patterns

    Contiguous and aligned memory accesses can be combined into wide transactions, significantly improving effective bandwidth. Matrix tiling allows data blocks to be reused in cache and reduces access to slower memory. Tensor memory layout, whether row-major or column-major, also affects the memory access efficiency of adjacent threads. Before changing the layout, the benefit should be validated with measured data.

    3.3 Low-Precision Computation

    Data formats such as INT8 and BF16 can reduce weight size and bandwidth requirements while improving compute throughput. Quantization itself is not a lossless operation. In practice, follow these steps:

    • Compare output quality metrics before and after quantization on a representative validation set.
    • Keep numerically sensitive layers, such as the output layer and some normalization layers, at higher precision.
    • Keep accuracy loss within the range acceptable to the business, and use business metrics as the final acceptance criteria.

    3.4 Benchmarking Method

    Performance optimization must be based on reliable measurements. The following example uses standard libraries to perform warmup, multiple samples, and percentile statistics. It is suitable for most synchronously executed inference functions:

    1. import time
    2. import statistics
    3. def benchmark(fn, warmup=5, repeat=50):
    4. # Warmup excludes first-call overhead such as compilation and cache initialization
    5. for _ in range(warmup):
    6. fn()
    7. latencies = []
    8. for _ in range(repeat):
    9. start = time.perf_counter()
    10. fn()
    11. latencies.append((time.perf_counter() - start) * 1000)
    12. latencies.sort()
    13. return {
    14. "mean_ms": statistics.mean(latencies),
    15. "p50_ms": latencies[len(latencies) // 2],
    16. "p99_ms": latencies[min(len(latencies) - 1, int(len(latencies) * 0.99))],
    17. }
    18. # Usage example; run_inference is the inference function under test
    19. # result = benchmark(lambda: run_inference(model, batch))

    If the device uses asynchronous execution, call the device synchronization interface before and after timing. Otherwise, the measured time only includes task submission overhead, and the result will be seriously distorted. When reporting results, provide both the mean and percentiles such as P99, because tail latency usually reflects user experience better than the mean.

    4. System-Level Optimization

    4.1 Continuous Batching

    Static batching must wait for the longest request in the batch to finish. Once shorter requests complete, the device can only idle. Continuous batching removes completed requests after each decode step and fills the batch with new requests from the queue. The device remains fully utilized, and overall throughput improves. This approach places higher demands on the scheduler implementation, which must handle request state management and dynamic memory allocation.

    4.2 KV Cache Management

    KV cache memory usage grows linearly with sequence length and concurrency. The usage for a single request can be estimated as follows:

    1. KV cache usage ≈ 2 × layers × sequence length × KV heads × head dimension × bytes per element

    The coefficient 2 corresponds to the two caches, K and V. Allocating memory for the maximum length at once can easily cause waste and fragmentation. Paged management divides the cache into fixed-size blocks, allocating and reclaiming them on demand, which can effectively reduce fragmentation. At the same time, the server should set a maximum context length and maximum concurrency to prevent memory exhaustion from causing service failures.

    4.3 Request Scheduling and Timeout Control

    Different businesses have different latency tolerances. Requests can be placed in priority queues, queue waiting time can be limited, and requests exceeding a threshold can follow a degradation strategy, such as returning cached results or switching to a smaller model. This design can protect the latency of core paths under high load.

    5. Key Points for Edge and Local Deployment

    Deploying models on edge devices such as personal computers with neural network acceleration units is mainly limited by memory capacity, power consumption, and thermal conditions. Proceed in the following order:

    1. Determine model size and quantization scheme: Estimate the memory usage of weights and KV cache, and confirm whether the model can run resident on the target device.
    2. Choose a data format that matches the hardware: Compare INT8 and BF16 in terms of accuracy and speed, and select the option that meets business requirements.
    3. Check operator coverage: After model conversion, confirm that all operators can be executed by the acceleration unit. Unsupported operators fall back to generic implementations, and performance may drop significantly.
    4. Limit application parameters: Set context length and concurrency limits according to the scenario to avoid exceeding device resources.
    5. Run end-to-end tests: The test scope should include preprocessing, model inference, and postprocessing, not just the time of the model forward pass.

    6. Establish a Sustainable Performance Analysis Process

    Performance optimization should follow a fixed process rather than relying on random parameter tuning based on experience.

    Step Key Actions Output
    Define metrics Determine time to first token, output throughput, P99 latency, peak memory, and cost per request Metric list and acceptance criteria
    Establish baseline Fix input distribution, hardware environment, and software versions Reproducible baseline report
    Profile hotspots Use device profiling tools to measure the time share of each operator Bottleneck ranking
    Optimize one item at a time Change only one variable and run regression tests each time Optimization records with clear attribution
    Lock configuration Write parameters into configuration files and include them in version control Rollback-capable production configuration

    Change only one variable at a time so that the source of any gain can be identified. If multiple parameters are changed at once, even if metrics improve, the result is difficult to reproduce and explain.

    7. Community Collaboration and Toolchain Development

    The value of the open-source community lies in reproducible cases, public benchmark data, and thorough problem discussions. Teams can record the preconditions, methods, and measured results of each optimization in an internal knowledge base so that later team members can trace them. When participating in external discussions, submitted issues should include a minimal reproducible example, environment information, and test data, which makes it easier to get useful feedback.

    For the toolchain, it is recommended to package model conversion, precision validation, performance testing, and regression checks into an automated pipeline. Each code or model change should automatically run benchmarks and compare them with the baseline. If key metrics regress, the pipeline should block the release. This reduces manual omissions and exposes performance issues early.

    8. Conclusion

    LLM inference optimization is a systems engineering task. The correct order is to measure first, then locate the bottleneck, and finally implement changes ranked by benefit and risk. The operator level, system level, and deployment level affect one another. For example, operator fusion changes memory usage, and quantization affects batching strategy. Only by unifying metrics, fixing the environment, and recording each change can a team determine whether an optimization is truly effective and turn experience into reusable engineering capability.