Cost-Efficient LLM Inference: A Three-Stage Co-Optimization Approach from Pre-Training to Post-Training and Serving

    This article presents a general engineering framework for cutting large language model inference costs through coordinated optimization across three stages: pre-training, post-training, and inference. It explains why cost is driven by activated parameters per token, output length, concurrency, and KV cache pressure rather than parameter count alone, then walks through sparse MoE activation, hybrid attention and low-rank KV compression, memory-style parameters, self-distillation, length penalties with reinforcement learning, operator fusion, low-bit quantization, and speculative decoding. It also covers the cloud capabilities needed to serve inference workloads and a checklist of common pitfalls and evaluation practices.

    1. Why Cost-Effectiveness Has Become the Core Metric for LLM Deployment

    In enterprise AI applications, gains in model capability usually come with a matching rise in compute cost. Once a project moves from a demo to real production, the team stops asking “can the model answer correctly?” and starts facing three more practical questions: is the cost per request under control, can memory and bandwidth handle concurrency, and can long-context capability be used affordably.

    An often overlooked fact is that inference cost is not determined by parameter count alone. What actually drives the bill is “activated parameters per token × number of output tokens × concurrency,” plus the memory and bandwidth pressure created by the KV cache. As a result, chasing parameter scale or applying quantization in isolation rarely delivers an order-of-magnitude improvement. Effective cost reduction has to be a full-chain, cross-stage co-design.

    Using the technical approach of a recently released cost-effective multimodal model from a cloud vendor as an abstract reference, this article strips away product specifics and distills a general engineering paradigm of three-stage co-optimization across pre-training, post-training, and inference.

    2. Pre-Training: Using Architecture Design to Reduce Memory Pressure

    2.1 Sparse Activation: Decoupling Total Parameters from Compute

    The mainstream approach is a sparse mixture-of-experts (MoE) structure, which allows the total parameter count to be very large while each token activates only a small fraction of it. For example, a configuration with roughly 224 billion total parameters and about 12 billion activated per token decouples model capacity from per-request compute: capacity provides “breadth of knowledge,” while activation determines “cost per call.” The engineering caveats are routing balance and expert parallelism strategy; without them, load skew appears, with popular experts overloaded and rarely used ones idle.

    2.2 Hybrid Attention and Low-Rank Compression: Shrinking the KV Cache

    The real bottleneck for long context is the KV cache, which grows linearly with sequence length, consumes memory directly, and limits batch size. Common industry techniques include sliding window attention, grouped query attention, and low-rank key-value compression. Compressing the KV cache to a fraction of the previous generation (for example, down to 1/6 or even 1/24) yields three benefits: a single card can hold a longer context, batch size can be increased, and cross-card communication volume drops significantly.

    Illustrative attention configuration logic (pseudocode, conveying the idea only):

    1. # Hybrid attention: local window + global sparse + low-rank KV compression
    2. def build_attention_layers(num_layers, window=4096, global_every=8):
    3. layers = []
    4. for i in range(num_layers):
    5. if i % global_every == 0:
    6. layers.append(GlobalSparseAttention(rank=256)) # low-rank compressed KV
    7. else:
    8. layers.append(SlidingWindowAttention(window=window))
    9. return layers

    2.3 Memory-Style Parameters: Moving Deterministic Knowledge Out of Attention

    Another line of work introduces large-scale “memory-style” parameter structures (such as Engram-type designs) that carry factual and templated knowledge through lookup rather than repeated attention computation. The benefit is broader knowledge coverage with almost no increase in activated parameters per token, while allowing attention layers to be made thinner.

    3. Post-Training: Managing Output Length, the Hidden Bill

    3.1 Self-Distillation: Inheriting Strong Model Capability at Low Cost

    Using a more capable teacher model to generate high-quality data and then distilling it into the target model on the target task is a mature industry practice. Compared with training from scratch, it substantially reduces data labeling and compute investment, while keeping the target model from degrading noticeably in general intelligence as it gets smaller.

    3.2 Length Penalties and Reinforcement Learning: Cutting Verbosity in Half

    In real business scenarios, output length is often the primary cost driver. Introducing a conciseness reward and end-to-end task constraints through reinforcement learning can reduce average output length by about half while keeping task success rate essentially unchanged. This effectively halves cost without any hardware change.

    A simplified reward function expression:

    1. reward = w1 * task_success - w2 * max(0, len(output) - target_len) - w3 * format_penalty

    3.3 Adjust the Evaluation Criteria Accordingly

    Length management must be paired with stricter evaluation: looking at accuracy alone is not enough; you also need “token cost per unit of success,” otherwise it is easy to regress by sacrificing correctness to save tokens.

    4. Inference: Triple Acceleration from Compilation, Quantization, and Operator Fusion

    4.1 Operator Fusion and Megakernels

    Fusing multiple small operators into large kernels reduces memory reads and writes and launch overhead, which is key to speeding up the decoding stage. Combined with efficient batch scheduling and paged KV management, throughput improves significantly.

    4.2 Low-Bit Quantization

    4-bit weight quantization with a suitable activation strategy can greatly reduce memory footprint and bandwidth pressure while keeping accuracy loss under control. The implementation points are: keep higher precision for sensitive layers, and build a regression evaluation set for before and after quantization.

    4.3 Speculative Decoding and Specialized Decoding Kernels

    Speculative decoding with a draft model or specialized decoding kernels can push decoding speed to the range of hundreds of tokens per second, noticeably improving first-token latency and the streaming experience for interactive applications.

    5. Engineering Implementation: Serving Inference Workloads with General Cloud Capabilities

    • Elastic compute: host inference services on a container platform with auto-scaling to handle traffic peaks and troughs;
    • Models and data: store model weights and training corpora in object storage, with versioning for easy rollback;
    • Traffic governance: use a message queue for request peak shaving and asynchronous processing, and enforce rate limiting and priority queues at the gateway layer;
    • Observability: connect logging services with monitoring and alerting to track token usage, latency percentiles, and memory levels, forming a cost dashboard;
    • Cost attribution: tag and meter token and compute consumption by business line so optimization gains are quantifiable.

    Baidu AI Cloud is typically used in these scenarios to provide the combination of general capabilities above, helping enterprises translate the gains from three-stage optimization into an actual bill.

    6. Common Pitfalls and an Evaluation Checklist

    1. Looking only at parameter count and not activated parameters, leading to misjudging capacity and cost;
    2. Ignoring the KV cache, so enabling long context immediately causes OOM;
    3. Doing quantization without length management, which limits the cost reduction;
    4. Lacking dual regression evaluation for before and after quantization and before and after length management;
    5. Having no token-level cost attribution, so optimization cannot be sustained.

    The recommended evaluation order is: first measure token cost per unit of success, then locate whether the bottleneck is memory, bandwidth, or output length, and finally choose the optimization approach for the corresponding stage, forming a closed-loop iteration.