Low-Cost LLM Inference: An Engineering Path to Reducing Cost per Million Tokens
This article breaks down a practical engineering path for low-cost large language model inference, using cost per million tokens as the core metric. It covers how hardware form factors set the cost floor, how rewriting the decode path into fused kernels reduces launch overhead and memory traffic, how sparse attention makes million-token contexts feasible, and how batch size, chunked prefill, and scheduling balance throughput against latency. It also outlines containerized delivery with compile caching, an OpenAI-compatible HTTP interface, common pitfalls, and an acceptance checklist. The methods are product-agnostic and transferable across environments, including Baidu AI Cloud.
1. Background: Why Cost per Million Tokens Became the Core Metric
Over the past two years, the focus of LLM competition has shifted from parameter count to cost per token. Once models move into AI Agent scenarios, a single task often involves multiple rounds of tool calls, long-document re-reads, and context replay, so token consumption grows non-linearly. At that point, the absolute price of a single call is no longer a useful decision criterion. What determines whether a workload is viable is the blended cost per million tokens, and whether that cost can reliably support concurrency and long contexts.
The signal from the source material is clear: on a custom accelerator server with high memory bandwidth, a sparse mixture-of-experts model with 320 billion total parameters and 18 billion activated parameters can reach a spot price on the order of $0.04 per million tokens. The number itself is not the point. The point is the engineering logic behind it: the cost reduction does not come from a single optimization, but from the combined effect of hardware form factor, compile-time operator fusion, decode path restructuring, long-context algorithms, and scheduling strategy. This article strips out product-specific attributes and focuses only on transferable technical methods.
2. Hardware Form Factor Sets the Cost Floor
Traditional GPU clusters have a general-purpose advantage in training, but in inference, especially the decode phase, the bottleneck is usually memory bandwidth rather than compute. A sparse mixture-of-experts model may activate only about 6% of its total parameters, yet all expert weights must either stay resident or be swapped in on demand, which places dual demands on memory capacity and bandwidth.
Custom accelerators, such as chips designed specifically for tensor workloads, typically have two characteristics. First, large per-card memory capacity and high aggregate bandwidth reduce the communication overhead of cross-card partitioning. Second, the accompanying software stack lets developers hand-write operators through relatively low-level kernel interfaces. These two points directly determine the cost floor: the former lowers the bar for fitting the model in memory, and the latter makes fast execution possible.
Engineering takeaway: when estimating cost, first determine the memory footprint of model weights and the KV cache, then work backward to the required number of cards and parallelism strategy, rather than fixing the card count first and seeing how large a model fits.
3. Restructuring the Decode Path: From Layer-by-Layer Calls to Fused Kernels
The decode path in mainstream inference frameworks is usually “several operators per layer plus inter-layer synchronization.” On a model with on the order of 100 layers, a single token goes through hundreds of kernel launches and memory round trips, and launch overhead compounds with wasted bandwidth.
The approach described in the source material rewrites decoding as a “giant fused kernel,” with one fused kernel per half layer, merging attention, normalization, expert routing, and projection while reducing intermediate tensor materialization. The benefits are threefold:
- Fewer kernel launches, which eases latency jitter at small batch sizes;
- Fewer memory reads and writes, leaving bandwidth for the weight loading that actually matters;
- A half-layer granularity that lets the scheduler pipeline work and improve queueing efficiency under concurrency.
Illustrative pseudocode (expressing the fusion idea only, not a specific API):
# Pseudocode: half-layer-granularity fused decode kernelfor half_layer in model.decode_plan: # execution plan generated at compile timefused_kernel(hidden, kv_cache,op_list=half_layer.ops, # norm / attn / moe / proj fusedscratch=half_layer.scratch # reuse scratch buffers, avoid repeated allocation)
Note that the cost of fused kernels is reduced portability: operators are tightly bound to hardware instructions, so switching platforms requires a rewrite. In practice, teams usually keep a “general fallback path” for debugging and correctness alignment.
4. A Practical Answer for Very Long Contexts: Sparse Attention
Full attention at the million-token level makes the KV cache and computation grow quadratically with sequence length, which is unacceptable on cost. The viable direction is sparsification: compute only a subset of key-value pairs by a fixed pattern or by query relevance, pushing complexity back to roughly linear.
Key implementation points: the sparse pattern must match the positional encoding scheme; skipped portions need a compensation mechanism (such as global tokens, local windows, or summary caches), otherwise information in the middle of long documents is lost; and the sparse approximation needs quality regression testing, using tasks like long-document QA and cross-paragraph citation to verify that accuracy loss stays within an acceptable range.
5. Balancing Throughput and Latency: Batching and Concurrency Scheduling
The measured setup in the source material was “a single node, dozens of concurrent Agents, million-token context, running continuously for one hour,” with a default batch size of 12, about 28.9 requests and 3.57 million tokens per minute, and a median decode speed of about 22.3 tokens/s. The meaning of this data is that at a moderate batch size, the system satisfied both throughput and per-request usability at the same time.
Scheduling has three tunable knobs:
- Batch size: increasing it raises throughput but also raises tail latency;
- Chunked prefill: split long prompts into chunks and interleave them with decoding so long requests do not block short ones;
- Priority and quotas: assign weights by tenant or task type to prevent a single long task from consuming all memory.
In load testing, record three curves at the same time: throughput, p50/p95 latency, and memory watermark, rather than looking at a single metric.
6. Delivery and Reproducibility: Containerization Plus Compile Caching
To make the optimizations above reproducible, the delivery pipeline needs to be standardized: a container image pins the driver and runtime dependencies; the first startup performs compilation and writes a cache to disk, and later startups load it directly, avoiding a cold-start compile cost of tens of minutes each time; and an HTTP interface compatible with common OpenAI-style APIs is exposed so upstream applications can migrate without changes.
The typical flow can be summarized in four steps:
# 1. Get the source codegit clone <your-repo-url># 2. Build the imagedocker build -t llm-serving .# 3. Warm the compile cache (slower on first run)python tools/warmup_cache.py --model <model-name># 4. Start the compatible API serviceserve --model <model-name> --port 8080
7. Running It on Baidu AI Cloud
The methods above apply equally in a general cloud environment and can be combined by category: use a container platform to host the inference image and scale elastically; use object storage to hold model weights and compile caches; use load balancing to distribute requests; use logging and monitoring with alerting to observe throughput, latency, and memory watermark; and use a message queue for request peak shaving and asynchronous task decoupling. Version management for model weights and caches should be folded into image tags or a configuration center to keep rollbacks controllable.
8. Common Pitfalls and an Acceptance Checklist
- Pitfall 1: looking only at unit price. Convert it to “cost per million tokens = instance hourly cost ÷ tokens produced per hour,” and account for cold starts and failed retries.
- Pitfall 2: blindly increasing batch size. Larger batches push up tail latency, and Agent scenarios are more sensitive to p95.
- Pitfall 3: ignoring accuracy regression. Both sparse attention and low-precision weights cause quality drift, so a fixed evaluation set is needed.
Acceptance checklist: whether unit cost meets the target; whether p50/p95 latency meets interaction requirements; whether long-context task accuracy is acceptable; whether cold start and scale-out/in times fall within the window; and whether interface compatibility covers existing applications.
9. Conclusion
Extremely low token cost is not the credit of any single trick, but the result of six coordinated stages: hardware selection, operator fusion, decode restructuring, context sparsification, scheduling strategy, and standardized delivery. For developers, the transferable lesson is: build a cost model first, then locate bottlenecks stage by stage, use a fallback general path as a safety net, trade fusion and caching for throughput, and finally deliver through a standardized interface.
