Production-Grade LLM Inference Optimization: A Practical Guide

    This guide breaks down production-grade LLM inference optimization into four layers—kernels, communication and memory, request lifecycle, and scheduling—and explains how they work together to balance latency and cost in long-context, high-concurrency serving. It covers operator fusion, KV cache management, prefill/decode disaggregation, continuous batching, key evaluation metrics, and an actionable checklist for teams building inference services on hardware-constrained environments.

    1. Background: Inference Is Becoming the Main Battleground for Compute

    Over the past two years, the center of gravity in the LLM industry has been shifting from training to inference. Training is a centralized, periodic resource expense, while inference is a distributed, continuous online service that faces real user traffic directly. This shift has three immediate consequences:

    1. A changing cost structure: Inference cost grows linearly with call volume, so the economics of a single request determine whether a business can scale.
    2. Harder latency constraints: Online scenarios impose clear requirements on Time To First Token and per-stream output speed; exceeding them means degraded experience.
    3. Sharp load fluctuations: Resource utilization differs dramatically between daytime peaks and nighttime troughs, and static resource allocation leads to serious waste.

    Against this backdrop, a number of production-grade inference frameworks targeting domestic acceleration hardware have emerged. Their shared technical challenge is to bring the output per unit of compute into the global first tier under the constraints of a maturing hardware ecosystem. This article abstracts their technical paths into a reusable optimization practice guide.

    2. The Four Layers of Optimization: From Kernels to Scheduling

    Production-grade inference optimization is not single-point tuning but a bottom-up systems engineering effort. It can be broken into four layers.

    2.1 Core Kernel Layer: Polishing the Hot Paths

    Only a limited number of operators are executed repeatedly during inference, mainly concentrated in attention computation, normalization, activation functions, quantization/dequantization, and sampling. Common optimization techniques include:

    • Operator fusion: Merging multiple memory-bound small operators to reduce the number of times intermediate results are written back to GPU memory or system memory. Memory access rather than computation is often the bottleneck in the decode phase.
    • Blocking and pipelining: Processing long-sequence attention in blocks so that computation overlaps with data movement, improving bandwidth utilization.
    • Low precision and mixed precision: Using lower bit-width representations for weights and activations while preserving precision on critical accumulation paths, as long as accuracy stays controlled.
    • Rewriting kernels for hardware characteristics: Different accelerators differ markedly in memory hierarchy, vector width, and synchronization primitives. Generic kernels often deliver only 30% to 50% of peak compute, so dedicated kernels are a necessary investment.

    Illustrative pseudocode expressing the “fusion + blocking” idea:

    1. # Pseudocode: blocked attention that avoids materializing the full attention matrix
    2. for q_block in split(queries, BLOCK_Q):
    3. acc = zeros_like(q_block)
    4. for kv_block in split(keys_values, BLOCK_KV):
    5. scores = matmul(q_block, kv_block.T) * scale
    6. scores = mask_and_softmax(scores)
    7. acc += matmul(scores, kv_block)
    8. yield normalize(acc)

    2.2 Communication and Memory Management Layer: What Determines Horizontal Scaling

    A single card cannot hold a large model with long context, so parallelism strategy and memory management become the key to the throughput ceiling.

    Combining parallelism strategies: Tensor parallelism reduces per-card weight pressure but communicates frequently; pipeline parallelism introduces bubbles; expert parallelism suits sparse structures; data parallelism boosts throughput. Production systems typically mix them by layer and by module, overlapping communication with computation to hide synchronization overhead inside compute time.

    KV cache management: In long-context scenarios, cache occupancy often exceeds the weights themselves. Mature approaches include paged cache allocation to reduce fragmentation, prefix sharing to reuse computation for identical system prompts, and tiered eviction by热度 to lower-cost storage.

    Memory pooling: Pre-allocation plus reuse instead of frequent allocation and release can significantly reduce long-tail latency jitter.

    2.3 Inference Pipeline Layer: The Full Lifecycle of a Request

    Taking a long input averaging around 98K tokens as an example, a request goes through: request intake and authentication, tokenization, batch formation, prefill, token-by-token decode, and post-processing with streaming return.

    Prefill is compute-intensive while decode is memory-intensive, and mixing them in the same batch causes mutual interference. The prevailing industry practice is disaggregated deployment: prefill and decode use different resource pools and parallelism configurations, passing cache over a high-speed link, so throughput and latency can be optimized separately.

    2.4 Task Scheduling Layer: Holding Utilization and SLOs at the Same Time

    The scheduler must handle three goals simultaneously: meeting service level objectives, maximizing resource utilization, and controlling long-tail latency. Common strategies include:

    • Continuous batching: Releasing a slot as soon as a request finishes and filling it with a new request, avoiding waiting for the whole batch.
    • Priority and admission control: Grading by tenant and by timeout budget, actively degrading under overload rather than collapsing entirely.
    • Timeouts and preemption: Setting limits for overly long requests to prevent individual requests from blocking the queue.
    • Off-peak resource reuse: Filling nighttime troughs with low-priority offline tasks, turning idle compute into revenue.

    3. How to Measure “Low Latency + Economics”

    To evaluate an inference service, cover at least the following metrics—none can be missing:

    Dimension Metric Meaning
    Latency P50/P99 Time To First Token Where the user perceives the response starting
    Throughput Per-stream output tokens/s Generation smoothness
    Capacity Concurrent streams per card Hardware carrying capacity
    Economics Revenue per card per hour Commercial sustainability
    Stability Long-tail timeout rate, error rate Production availability

    A set of production figures disclosed in the original text can serve as a reference magnitude: with an average input length of around 98K tokens, P50 Time To First Token is about 277 ms, per-stream output is about 138 tokens/s, and revenue per card per hour is about 118 RMB when converted at off-peak pricing. The significance of these numbers is that economics in long-context scenarios come from the multiplicative effect of kernel efficiency, cache reuse, and scheduling strategy, not from any single optimization.

    Data from multiple research institutions shows that domestic intelligent compute scale doubled within a year, with year-over-year growth exceeding 140%; leading cloud vendors’ AI infrastructure and compute service revenue grew year over year in a range generally between 50% and 190%. Meanwhile, the number of compute cards a single super node of mainstream accelerators can carry rose from the previous generation’s thousand-card level to the four-thousand-card level.

    These numbers send three signals:

    1. Demand is validated: Token consumption, customer contract value, and cloud revenue corroborate one another—inference demand is not a concept but cash flow.
    2. Lower cost expands applications: A drop in unit inference cost directly expands the scenarios that can be served, and call volume rises accordingly, forming a positive loop.
    3. Demand propagates upstream: Compute demand spreads along the chain of “cloud resources → server systems → chip manufacturing → power and cooling components,” and the domestic supply chain gains share under the dual conditions of constrained supply and local validation.

    For developers, this means inference optimization capability is turning from a nice-to-have into a fundamental engineering skill.

    5. Implementation Advice: An Actionable Checklist

    1. Measure before optimizing: Build end-to-end instrumentation, break down time spent in queuing, prefill, decode, and post-processing, and locate the real bottleneck.
    2. Choose parallelism and precision by scenario: Prioritize throughput for short requests; prioritize cache reuse and memory capacity for long context.
    3. Deploy prefill and decode separately, scaling each independently.
    4. Build a capacity model: Use peak QPS, average input/output length, and SLO targets to derive the required number of accelerators and redundancy ratio.
    5. Improve observability: Use general logging services, monitoring and alerting, and tracing, with threshold alerts on P99 and timeout rate.
    6. Make cost attributable: Track compute consumption by tenant and by model to support off-peak pricing and elastic scheduling.
    7. Keep a degradation path: Under overload, shorten max generation length, reduce batch size, or switch to a smaller model, prioritizing availability.

    6. Conclusion

    The essence of production-grade inference optimization is trading engineering effort for output per unit of compute under hardware constraints. Only when the four layers—kernels, memory, communication, and scheduling—work together, combined with disaggregated deployment and fine-grained observability, can latency and economics be held simultaneously under long context and high concurrency. As domestic compute supply and demand expand together, turning this methodology into a team’s standard process delivers more long-term value than chasing any single-point technique.