LLM Inference Cost Engineering: A Practical Guide to Lowering Cost per Token
This article breaks down the engineering levers that determine LLM inference cost, using a 300B+ parameter MoE model on a single 8-accelerator node as the running example. It covers the cost-per-million-token formula, memory and routing bottlenecks in MoE decoding, tensor/expert/pipeline parallelism tradeoffs, half-layer fused kernels (megakernels), sparse attention for million-token contexts, continuous batching with chunked prefill, FP8 quantization decisions, benchmarking methodology and metric definitions, a reproducible setup path with an OpenAI-compatible service, and common pitfalls ranked by optimization priority.
1. Why Inference Cost Is the Core Constraint for LLM Deployment
Once model size reaches the hundreds of billions of parameters, the training budget is only the starting point. What actually decides whether a business can scale is the cost per token on the inference side. One often-overlooked fact: inference cost is not determined by model size alone, but by two variables together — how many tokens can be safely processed per second, and how much is paid per second. So the goal of cost engineering is clear: minimize the hardware amortization per token under an acceptable latency constraint.
The common industry measure of inference economics is “price per million tokens.” That price is the result of a simple formula:
unit cost = node hourly cost / (output tokens per second × 3600 / 1,000,000)
Only two levers exist: lower the node hourly cost, or raise effective throughput. The first depends on hardware selection and procurement strategy; the second is where the software stack can actually make a difference. Engineering practices have emerged that serve very large models on a single node and push the price per million tokens down to a very low range, with nearly all of the gain coming from software-level throughput improvements rather than cheaper hardware.
2. Inference Characteristics of Very Large MoE Models
Take a typical 300-billion-class mixture-of-experts (MoE) model: roughly 320 billion total parameters, about 18 billion activated parameters per token, with weights stored in FP8. These numbers expose the fundamental tension of the inference workload:
- Memory capacity pressure comes from total parameters. Even with 8-bit quantization, weights still run into the hundreds of billions of bytes, which a single card cannot hold, so tensor or expert parallelism is required.
- Compute pressure comes from activated parameters. Each token activates only about 5% of the parameters, so compute demand is far below a dense model, but memory access and routing overhead rise noticeably.
- Routing imbalance creates a long tail. Expert load distribution is naturally skewed, and hot experts become the bottleneck for the whole batch, directly driving up p99 latency.
The conclusion: MoE inference optimization is not about “computing faster,” but about “moving less and scheduling more accurately.”
3. Single-Node Hardware and Parallelism Topology
A single node with multiple cards is the common landing spot for this kind of workload. Take an 8-accelerator cloud instance as an example: inside the node, the accelerators are connected by a high-bandwidth interconnect, and inter-card communication never traverses the network. This yields two direct benefits: all-reduce and all-to-all latency stays stable at the microsecond level, and no extra fault tolerance or retransmission logic is needed for cross-node communication.
Parallelism strategies are typically combined:
- Tensor parallelism splits the attention and FFN matrix multiplications, solving the problem of weights not fitting on one card;
- Expert parallelism distributes different experts across cards, using all-to-all to dispatch and collect tokens;
- Pipeline parallelism further reduces peak per-card memory when there are many layers.
It is worth stressing that higher parallelism is not always better. Each additional parallelism dimension introduces another collective communication, and once communication share passes a certain threshold, throughput drops as parallelism rises. In practice, use “per-card memory usage no more than 80%” as the constraint and search backward for the minimum viable parallelism.
4. Operator Fusion in the Decode Phase: Turning Memory Access into Compute
Every step of autoregressive decoding reads all the weights again, which makes it a classic memory-bound workload. Most of the accelerator’s compute sits idle here; the bottleneck is memory bandwidth. The core idea is to reduce HBM accesses and kernel launch overhead, and the concrete means is operator fusion.
One proven approach is to fuse each layer’s decode computation into a single large kernel (often called a megakernel), sliced at a granularity of one fused kernel per half layer. This eliminates intermediate tensor write-back and read-back between layers, and removes the scheduling overhead of hundreds of kernel launches. Illustrative pseudocode:
# Pseudocode: half-layer-granularity fused decode kernelfor half_layer in range(num_layers * 2):fused_kernel(hidden, # stays on-chip/in registers, never hits HBMkv_cache, # read on demand onlyexpert_weights, # FP8 weights, shared readrouter_logits)
The gains are quantifiable: assume each layer originally reads and writes 4 intermediate tensors, so 40 layers means 160 extra memory accesses; after fusion this drops to nearly zero. In memory-bound scenarios, that often translates to a 30%–50% improvement in decode throughput.
5. Sparse Attention for Million-Token Contexts
When context length is pushed to 1 million tokens, standard attention grows quadratically in complexity, and KV cache size also inflates linearly to an unacceptable level. The workable engineering solution is sparse attention: let each query attend only to a carefully selected subset of keys, reducing complexity from O(n²) to close to O(n·k).
Three points matter in practice:
- The sparse pattern must cover three categories — “local window + global anchors + sampled blocks” — to balance nearby detail and long-range recall;
- The KV cache needs paged management, combined with block-level eviction to control peak memory;
- Sparsification loses some accuracy, so it must be validated with long-text recall evaluation sets rather than perplexity alone.
6. Batch Scheduling: The Real Throughput Switch
On fixed hardware, batch size is the most sensitive parameter for throughput. A larger batch amortizes weight reads more fully and lowers cost per token; but a larger batch also raises per-request decode latency. So the scheduler’s job is to “find the largest feasible batch within the latency SLA.”
A common approach is continuous batching: instead of waiting for a whole batch to finish, completed requests are evicted and newly arrived requests inserted step by step, keeping accelerator utilization high over time. Combined with chunked prefill, long-prompt prefill can be sliced into decode batches, avoiding the head-of-line blocking caused by long requests stalling short ones.
Example configuration:
scheduler:max_batch_size: 12max_num_tokens: 32768chunked_prefill: trueprefill_chunk: 2048eviction_policy: lru
7. Precision and Quantization Tradeoffs
FP8 weights are the current sweet spot for cost-performance: half the memory footprint of FP16, with more controllable accuracy loss than INT4. But quantization is not a single switch; it requires layered decisions:
- Use FP8 for weights, and higher precision for activations to stabilize the numerical distribution;
- Quantizing the KV cache to 8 bits can substantially extend context capacity, but long-text task degradation must be assessed;
- Keep high precision for sensitive modules such as the router gating, to avoid expert selection drift.
8. Benchmarking Methodology and Metric Definitions
Evaluating an inference service cannot come down to a single “tokens per minute” number. A credible benchmark fixes the following variables and reports the full definition:
- Load model: replay real business traffic rather than synthetic short prompts;
- Concurrency shape: fix the number of concurrent sessions (e.g., 32 agent sessions), run for more than an hour, and observe long-run stability;
- Context length: state clearly whether it is 1K or 1M;
- Metric triple: request rate (req/min), throughput (token/min), and decode speed percentiles (p50/p99, token/s);
- Resource levels: accelerator utilization, memory usage, and inter-card communication share.
Only when “concurrency × context length × batch size” are all stated together is the data comparable. A common reference magnitude in the industry: on a single node, with 32 concurrency, million-token context, and batch size 12, roughly 29 requests per minute complete with about 3.57 million output tokens, and p50 decode speed is around 22 token/s. The point of such numbers is not exact reproduction, but a reasonable expected range.
9. Building from Scratch: Environment and Service Setup
A reproducible path usually has four steps:
# 1. Get the codegit clone <your-repo-url> && cd trnrt-demo# 2. Build the image (with driver and runtime dependencies)docker build -t llm-serving:dev .# 3. Warm the compile cache to avoid a long compile on the first requestpython tools/compile_cache.py --model glm-5.3-flash --dtype fp8# 4. Start the OpenAI-compatible servicetrnrt serve --model glm-5.3-flash --port 8000
Once the service is up, the application side only needs to call it over the standard OpenAI-compatible protocol, so migration cost is very low:
resp = client.chat.completions.create(model="glm-5.3-flash",messages=[{"role": "user", "content": "Summarize this text"}],max_tokens=512,)
One reminder: the compile cache must be warmed before benchmarking. A first request that triggers kernel compilation causes a cold-start spike of tens of seconds, and without warm-up the p99 numbers will be badly distorted.
10. Common Pitfalls and Optimization Priority
- Pitfall 1: blindly raising parallelism. Past the communication inflection point, throughput drops instead, so measure the inflection point first.
- Pitfall 2: looking only at average throughput. Perceived performance is decided by p99, and averages hide the long tail.
- Pitfall 3: ignoring routing skew. Hot experts keep individual cards saturated for long periods, so expert replication or capacity factor tuning is needed.
- Pitfall 4: skipping accuracy validation. Any quantization change should be run against the business evaluation set.
Suggested optimization priority: operator fusion > batch scheduling > sparse attention > quantization tuning > parallelism topology fine-tuning. The first two usually capture most of the gains, with the lowest change risk.
11. Conclusion
The drop in inference cost is not the credit of any single point technique, but the combined effect of “fused kernels + sparse attention + continuous batching + sensible quantization + single-node high-bandwidth topology.” For engineering teams, the truly reusable asset is not a specific number, but a clear evaluation methodology and optimization order: first quantify whether the bottleneck is memory access or communication, then decide whether to change operators or scheduling, and finally validate the gains with long-run benchmarks. Bake this method into CI, and unit cost per token can be pushed onto the next curve steadily, even as hardware and models keep iterating.
