Cost Reduction Practices for Large Model Inference Under High Concurrency
This article explains where large language model inference costs come from and how to reduce them across three stages: pre-training, post-training, and inference. It covers architecture choices such as hybrid attention, MoE, and KV cache compression, post-training techniques that shorten and sharpen outputs, and inference optimizations including quantization, speculative decoding, and continuous batching. It also outlines engineering practices for long-context workloads, including context compression, prefix caching, tiered quotas, queueing, and observability, followed by a four-step rollout path and deployment suggestions on Baidu AI Cloud.
1. Background: Compute Capacity Is Tight
A common pattern has emerged in the industry: a large model service, facing constrained compute resources, imposed limits on long conversations. These included a shorter cap on single-input length, a limit on how long inactive long conversations are retained, and a daily call quota that returns a “service busy” message once exhausted. Over the same period, the official status page reported multiple service interruptions affecting the chat service and the APIs of several model versions. Meanwhile, weekly usage rankings for open-source models showed a single model version jumping by an order of magnitude in call volume within one week.
Together, these signals point to one fact: large model inference has moved past “can it run” into “how much useful traffic can limited compute carry.” For developers and enterprise users, the real challenge is not peak QPS but the cost per token and the GPU memory pressure created by long contexts.
2. Three Sources of Cost
Before cutting costs, know where they land. Inference cost comes from four parts:
- GPU memory usage: the KV cache grows linearly with context length and concurrency, making it the main bottleneck in long-context scenarios.
- Compute volume: the complexity of attention and expert routing determines the time per token.
- Output length: the generation stage decodes token by token, so longer outputs accumulate more cost.
- Scheduling waste: queueing, retries, timeouts, and repeated computation all add overhead that produces nothing.
The conclusion is straightforward: optimizing only one of these yields limited gains, so all three stages must work together.
3. Pre-Training: Cutting Costs at the Architecture Level
Architecture choices set the floor on cost. Directions widely used in the industry include:
- Hybrid attention: combining local window attention with global attention to reduce attention overhead on long sequences.
- Sparse expert structure (MoE): decoupling total parameter count from the parameters activated per token, trading larger parameter capacity for lower compute per token.
- Memory/key-value compression structures: storing part of the history in compressed form, which substantially shrinks the KV cache.
Illustrative configuration (pseudocode, conveying the idea only):
config = {"total_params": "224B","activated_params_per_token": "12B","attention": "hybrid_local_global","kv_cache_ratio_vs_dense": 0.15,"context_window": 1_000_000,}
The key point: when evaluating a model, do not look only at total parameters. Look at the two metrics that actually drive the bill: activated parameters per token and the KV cache growth factor.
4. Post-Training: Shorter and More Accurate Outputs
Post-training offers the best return on cost reduction, because it leaves inference hardware costs unchanged while directly compressing output length.
- Self-distillation: using a stronger model as the teacher to transfer broad capability to the target model, avoiding repeated labeling.
- Reinforcement learning for preference optimization: introducing length penalties and task-completion rewards so the model produces less redundant phrasing while preserving accuracy.
- Structured output constraints: schema constraints make results directly parseable, reducing post-processing.
From an engineering standpoint, make “average output length per end-to-end task” a first-class metric in regression testing, monitored alongside accuracy, so tokens are never saved at the expense of quality.
5. Inference: Raising Throughput
Composable techniques on the inference side include:
- Fused operators (the megakernel approach): reducing kernel launches and GPU memory round trips.
- Low-bit quantization: 4-bit weight and activation quantization to ease memory and bandwidth pressure.
- Speculative decoding with a draft model: verifying multiple candidate tokens in a single forward pass.
- Continuous batching and paged caching: improving concurrency utilization and reducing fragmentation.
# Continuous batching scheduling sketchwhile True:batch = scheduler.form_batch(max_tokens=8192)outputs = engine.step(batch) # requests join and leave on each iterationdispatcher.stream(outputs)
6. Engineering Long Contexts and Quota Policies
For long conversations, simply adding capacity is not economical. Layered governance is the safer approach:
- Context compression: keep recent turns in a sliding window, summarize older content, and feed the summary back in.
- Cache reuse: enable prefix cache hits for identical prefixes such as system prompts and knowledge snippets.
- Tiered quotas: allocate quota by activity level and priority, downgrading or archiving inactive sessions.
- Queueing and graceful degradation: when the limit is reached, return a clear message and enter a queue instead of failing outright.
- Observability: track token consumption, cache hit rate, and timeout rate with logging services and monitoring alerts.
def build_context(history, limit=40_000):recent = history[-8:]summary = summarize(history[:-8]) if len(history) > 8 else ""ctx = summary + render(recent)return ctx[:limit]
7. Rollout Path and Practices on Baidu AI Cloud
A four-step rollout is recommended. First, run baseline load tests to quantify the token and GPU memory curves for each request type. Then apply quantization and batching to capture the first round of throughput gains. Next, introduce context compression and prefix caching. Finally, close the loop with quotas, queueing, and alerts.
On Baidu AI Cloud, model services can be combined with general-purpose capabilities such as container platforms, object storage, message queues, logging services, and monitoring alerts to build elastic scaling and canary release pipelines. This smooths compute scheduling between peaks and troughs, keeping high-concurrency long-context workloads stable at a controllable cost.
