Engineering Practices for LLM Inference Cost Optimization
This article walks through practical engineering techniques for reducing the cost of large language model inference under service level objectives. It covers why inference cost becomes the main scaling constraint, how dedicated accelerators divide inference workloads, and two core optimizations: fused decoding kernels and sparse attention for long context. It also details reproducible load testing with replayed traffic, a deployment path from container images to OpenAI-compatible endpoints, and a tuning checklist for batch size, cold starts, cache fragmentation, quantization, and long request isolation.
1. Background: Inference Cost Is Becoming the Main Scaling Constraint
Once a large model moves from a demo into production, the team’s focus shifts quickly from “can it run” to “how many useful tokens does each dollar buy.” In long-context, multi-turn conversation, and AI Agent workloads, input and output length distributions are highly uneven, and hardware utilization swings sharply. Simply adding more cards often produces a linearly growing bill without a proportional gain in throughput. As a result, engineering optimization on the inference side has to answer three questions at once: can cost per token go down, is tail latency under control, and will long context drag down overall concurrency.
The key point is that cost optimization does not mean pushing price to the lowest possible level. It means minimizing the resource consumption per useful token under a fixed service level objective (SLO). Talking about throughput without latency constraints, or about quantization without quality constraints, just moves the problem somewhere else.
2. Hardware and Software Stack: How Dedicated Accelerators Split Inference Work
Beyond general-purpose GPUs, a class of custom accelerator cards built for tensor operations (such as cloud-developed training/inference chips) has started to take on online inference. This hardware typically offers high-bandwidth on-chip memory and large matrix compute units, which suits stable computation graphs that can be statically scheduled. The tradeoff is that the operator ecosystem is less rich than on general-purpose platforms, so a matching compiler toolchain and runtime are needed to fill the gaps.
A practical engineering path is to package drivers and the runtime in containers, unify the environment through images, and avoid host dependency drift. On top of that, expose interfaces compatible with mainstream calling protocols so business code can migrate without changes. This way, model replacement, version rollback, and canary releases can all reuse the existing container orchestration and traffic management capabilities.
3. Key Optimization 1: Turning Decoding into Fused Kernels
The bottleneck in autoregressive decoding is often not compute but memory access and kernel launch overhead. With per-operator execution, each layer repeatedly reads and writes the KV cache and synchronizes many times, leaving the GPU or accelerator idle while waiting. The common industry approach is kernel fusion: merging attention, normalization, projection, and activation steps within a layer into a few large kernels to reduce intermediate tensor materialization and scheduling overhead.
A more aggressive organization is a “half-layer” split, where one large kernel handles half of a layer’s computation and two kernels cover a full layer, maximizing data reuse within on-chip memory and register capacity limits. Illustrative pseudocode follows; the focus is on structure rather than specific APIs:
# Pseudocode: fused kernel scheduling during decodingfor layer in model.layers:fused_half(layer, kv_cache, part="up") # normalization + QKV projection + attentionfused_half(layer, kv_cache, part="down") # output projection + MLP + residual
The point is that fusion boundaries are determined by on-chip memory capacity and register pressure. Cut too large and it will not fit; cut too small and reuse benefits are lost. The right boundary has to be measured on the target hardware.
4. Key Optimization 2: Sparse Attention for Long Context
Million-token context makes attention computation and KV cache growth hard to sustain. Common responses include block-wise local attention, sliding windows, and learnable sparse patterns (global tokens + a local window + a small number of important tokens). Sparsification pays off twice: it reduces computation and compresses the cache that must stay resident, which raises the number of concurrent requests.
Three engineering cautions apply. First, the sparse pattern must match how the model was trained or fine-tuned, otherwise quality drops noticeably. Second, cache paging and eviction policies must work together to avoid fragmentation. Third, long-context requests should be routed separately from short ones so that a few extremely long requests do not raise overall tail latency.
5. Performance Validation: Reproducible Load Testing with Replayed Traffic
Whether an optimization works must be validated with loads that resemble the real distribution. The recommended approach is to collect production requests (after desensitization) into a replay set, run it repeatedly at fixed concurrency and fixed context length, and record throughput, requests per minute, token rate, and decoding speed percentiles (p50/p95/p99).
A typical load test matrix can be designed like this:
| Variable | Example values | Metrics observed |
|---|---|---|
| Concurrent sessions | 16 / 32 / 64 | Requests per minute, error rate |
| Context length | 32K / 128K / 1M | p99 latency, cache usage |
| Batch size | 4 / 8 / 12 / adaptive | Decoded tokens/s, memory watermark |
| Quantization precision | FP8 / mixed precision | Quality score, cost per unit |
Keep in mind that any specific numbers depend heavily on hardware model, model architecture, and input distribution, and cannot be compared directly across environments. The table above only illustrates testing dimensions; real conclusions should come from your own environment.
6. Deployment: From Image to Compatible Interface
The recommended sequence is: prepare a base image and pin the runtime version → build and pre-compile the computation graph cache (to avoid a long-tail cold start on the first request) → serve through a gateway compatible with mainstream OpenAI-style protocols → connect monitoring, alerting, and logging to collect throughput, latency percentiles, cache hit rate, and failure rate.
# Illustrative flow (commands kept neutral)docker build -t inference-runtime .# Warm-up: compile and cache the computation graphpython tools/compile_cache.py --model <model_dir># Start the compatible interface serviceserve --model <model_dir> --port 8080
After launch, three things are recommended: do capacity planning against business peaks and reserve elasticity; set quotas and queuing policies for extremely long context; and move quantization and sparsity settings into a configuration center so canary switches require no code changes.
7. Common Pitfalls and a Tuning Checklist
- Bigger batch is not always better: overly large batches worsen queuing and tail latency, so adaptive batching (dynamic batching against a latency target) can help.
- Cold starts must be warmed up: finish computation graph compilation and cache loading before the readiness probe.
- Cache fragmentation quietly eats concurrency: periodically compact paged caches and monitor hit rate.
- Evaluate quantization in pairs: look at quality and cost metrics together to avoid “lower cost, lower quality.”
- Isolate long requests: give extremely long context its own pool to protect the normal interactive experience.
8. Conclusion
Running very large MoE models on dedicated accelerators at extremely low cost per token comes down to a multiplicative effect of three things: fused kernels cut memory access and scheduling overhead, sparse attention holds down long-context cost, and replay-based load testing keeps tuning on track. Turning these three into configurable, observable, and rollback-capable engineering capabilities is what makes a sustainable balance among cost, latency, and quality possible. Built on general capabilities such as the container platform and monitoring and alerting on Baidu AI Cloud, this approach can be reused directly without binding to a specific implementation.
