High-Concurrency, Low-Cost LLM Inference Optimization: A Practical Guide

    This article breaks down how engineering teams can make large language model inference both high-throughput and cost-efficient. It covers the cost structure of online inference, architecture-level optimizations such as hybrid attention and KV cache compression, sparse experts with decoupled parameters, post-training techniques like self-distillation and length-constrained reinforcement learning, evaluation systems tied to real work products, and inference engineering methods including quantization, speculative decoding, and prefix caching. Readers will find practical formulas, code snippets, capacity planning guidance, and common pitfalls to avoid.

    1. Why Cost Efficiency Has Become the Core Metric for LLM Adoption

    In enterprise applications, the absolute capability ceiling of a model matters, but what really determines whether a business can scale is the product of three factors: cost per task, end-to-end latency, and output stability. A model that is slightly more capable but costs several times more and responds more slowly often cannot sustain traffic over the long term in high-frequency scenarios such as customer service, office document processing, and data analysis. Engineering teams therefore need to break “cost efficiency” down into measurable, optimizable engineering variables rather than leaving it at the level of subjective impressions.

    From a cost structure perspective, online inference spending is mainly composed of three parts: the compute during the prefill stage, the per-token memory bandwidth overhead during the decode stage, and the memory occupied by context caching. The longer the context and the higher the concurrency, the more likely cache occupancy becomes the bottleneck, which in turn limits the number of concurrent requests a single GPU can handle and directly drives up unit cost.

    2. Architecture-Level Optimization: Trading Smaller Caches and Sparser Activation for Throughput

    2.1 Hybrid Attention and Cache Compression

    The cache footprint of the attention mechanism is strongly correlated with sequence length, number of layers, and number of attention heads. Common industry approaches include grouped-query attention, mixing sliding-window and global attention, and cross-layer cache sharing. They all share the same core goal: preserve long-context modeling capability while compressing the cache down to a fraction of its original size, thereby significantly increasing single-GPU concurrency.

    The cache size can be understood with the following illustrative formula:

    1. # Illustrative only: shows the order-of-magnitude relationship, not specific product parameters
    2. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, dtype_bytes=2):
    3. # Per layer, per token cache = 2(K/V) * kv_heads * head_dim
    4. per_token = 2 * kv_heads * head_dim * dtype_bytes
    5. return layers * per_token * seq_len * batch
    6. print(kv_cache_bytes(layers=32, kv_heads=8, head_dim=128, seq_len=131072, batch=8))

    As shown, sequence length and batch size are linear scaling factors, while reducing kv_heads or introducing cross-layer sharing is equivalent to “discounting” the multipliers.

    2.2 Sparse Experts and Parameter Decoupling

    Decoupling total parameter count from the parameters activated per token is a mainstream approach for balancing capacity and cost. Total parameters determine knowledge capacity, while activated parameters determine the compute for a single forward pass. In engineering practice, it is also worth noting “memorization parameters” that do not participate in regular forward computation: they occupy storage but add almost no compute overhead, making them suitable for carrying long-tail knowledge.

    2.3 Training Stability and Scale-Up Validation

    Architecture changes must be paired with systematic scale-ladder experiments: validate convergence trends on small models, then extrapolate to large models, observing whether loss curves, gradient stability, and downstream task performance improve in tandem. Without this step, architectural innovations can easily fail once scaled up.

    3. Post-Training: Turning “Correct” into “Short and Accurate”

    3.1 Self-Distillation for Capability Transfer

    Using a more capable teacher model to generate high-quality trajectories and aligning a student model to that distribution is a cost-controlled way to inherit capability. Compared with aligning from scratch, self-distillation significantly reduces reliance on manual annotation.

    3.2 Length Constraints and Reinforcement Learning

    In real business scenarios, verbose output directly translates to higher cost and longer user wait times. By adding length penalties and format-compliance terms to the reward function, the model can compress its output while maintaining accuracy. An illustration:

    1. # Illustrative: reward shaping to suppress redundant output
    2. def reward(correct, fmt_ok, tokens, max_tokens):
    3. r = 1.0 if correct else 0.0
    4. r += 0.2 if fmt_ok else -0.2
    5. r -= 0.5 * (tokens / max_tokens) # length penalty
    6. return r

    In practice, halving end-to-end output length often brings a more noticeable improvement to the bill than simply switching to a cheaper model.

    4. Evaluation: Making Metrics Reflect Everyday Work Products

    Public leaderboard scores that are far removed from real scenarios tend to diverge from user experience. A more reliable approach is to build an internal task set covering typical tasks such as document editing, spreadsheet repair, presentation creation and revision, human-AI collaborative writing, audio/video processing, and visual understanding, while recording three dimensions simultaneously: output quality (blind human review), output length per turn, and end-to-end latency plus cost per task.

    A recommended evaluation workflow:

    1. Fix the task set and random seeds to ensure comparability across versions;
    2. Use blind testing and multi-person cross-scoring to reduce subjective bias;
    3. Report quality, latency, and cost curves together to avoid single-point optimization;
    4. Perform attribution classification on failed samples (instruction following, formatting, factuality, tool calling).

    5. Inference Engineering: Dual Optimization of Decode Speed and Deployment Density

    • Operator fusion and large-scale kernel merging to reduce kernel launches and memory access round trips;
    • Low-bit quantization (such as 4-bit weights) combined with keeping sensitive layers at higher precision to control accuracy loss;
    • Speculative decoding, draft models, and request scheduling optimization to push decode throughput into a higher range;
    • Prefix cache reuse and hit-based billing strategies to substantially reduce the cost of repeated context;
    • Building elastic scaling and observability by combining container platforms, message queues, logging services, and monitoring/alerting.

    For capacity planning, it is recommended to work backward from “single-GPU concurrency × decode throughput ÷ average output length” to estimate the required number of GPUs, with a buffer reserved for burst traffic:

    1. # Illustrative: GPU count estimation
    2. def gpus_needed(qps, avg_out_tokens, tps_per_gpu, buffer=1.3):
    3. per_gpu_qps = tps_per_gpu / avg_out_tokens
    4. return int(qps / per_gpu_qps * buffer) + 1

    6. Implementation Advice and Common Pitfalls

    First, do not replace business evaluation with public leaderboards. Second, do not focus only on lowering unit price while ignoring output length, which is often underestimated. Third, quantization and cache compression must undergo regression validation to prevent quality regressions on long-tail tasks. Fourth, cache hit strategies should be designed in coordination with business prompt templates; only a stable prefix structure can improve hit rates. Fifth, build a cost dashboard that attributes spending by task type, which is the only way to keep optimizing.

    Overall, connecting architecture sparsification, post-training length constraints, business-aligned evaluation, and inference-side engineering acceleration is the complete path to high-concurrency, low-cost LLM deployment. In related practice at Baidu AI Cloud, such capabilities are typically delivered as a combination of general product categories such as model services, container platforms, and monitoring/alerting, making it easy for teams to build on demand and iterate continuously.