Production-Grade LLM Inference Optimization on Domestic AI Accelerators: A Practical Guide
This guide explains why inference—not training—is the real test for domestic AI accelerators, and how to optimize large language model serving for production workloads. It covers four core optimization dimensions: kernel-level efficiency, KV-cache memory management, communication/compute overlap in parallelism, and request scheduling. It also presents a unified latency-and-economics evaluation framework, observability requirements, a step-by-step implementation roadmap, and common pitfalls to avoid. Readers will learn how to move from "the model runs" to "the model serves real online traffic reliably and cost-effectively."
1. Background: Inference Is the Real Challenge for Domestic AI Accelerators
Over the past two years, domestic AI accelerators have iterated rapidly on peak FLOPS, memory capacity, and interconnect bandwidth, with paper specifications now approaching international mainstream levels. But moving a model from “it can run” to “it can handle large-scale online traffic in production” does not test peak compute—it tests effective compute utilization: whether operators are fully compiled and tuned, whether memory is carved into reusable blocks, whether collective communication overlaps with computation, and whether request scheduling keeps the pipeline continuously full.
Training workloads are latency-insensitive with regular batch shapes. Online inference is the opposite: input lengths have a long-tail distribution (from a few tokens to hundreds of thousands), output lengths are unpredictable, per-request latency directly determines user experience, and unit token cost determines whether the business model works. The maturity of the inference engine is therefore the true yardstick for whether a compute platform can deliver AI services at the highest standard.
2. Four Optimization Dimensions for Production-Grade Inference
1. Core Operators: From “Runs” to “Runs Efficiently”
The operator layer offers the most certain gains. Typical work includes:
- Fusion over stacking: Fuse element-wise operations such as normalization, activation, residual addition, and quantization/dequantization into adjacent compute kernels, reducing HBM read/write traffic. LLM inference is fundamentally memory-bandwidth-bound, so eliminating one round trip for an intermediate tensor is often more effective than increasing compute power.
- Tiled attention with online reduction: Implement attention using tiling plus online softmax reduction so that memory footprint is decoupled from sequence length, leaving room for paged KV caches.
- Low precision and mixed precision: Choose appropriate numeric formats for weights, KV cache, and activations separately; use per-layer sensitivity analysis to decide which layers can be reduced in precision, avoiding the quality regression of a one-size-fits-all approach.
- Compilation and adaptation for new hardware: New platforms often lack mature operator libraries. Build high-performance implementations on top of vendor-provided programming interfaces, and establish an operator-level benchmark suite to prevent regressions.
2. Memory Management: KV Cache Is the First Constraint for Long Contexts
With average input lengths reaching tens of thousands of tokens, KV cache memory can be several times larger than the weights themselves. Three things must be done:
- Paged cache management: Split the KV cache into fixed-size blocks and maintain a block table mapping logical sequences to physical blocks, eliminating reservation waste and enabling prefix sharing.
- Prefix reuse: System prompts, long documents, and multi-turn histories are highly repetitive. Hash blocks and skip repeated prefill on a cache hit—this is the most direct cost-reduction lever for long-input scenarios.
- Cache offloading and tiering: Move cold blocks down to host memory or even remote cache services, trading bandwidth for capacity, while using admission control to avoid thrashing.
Illustrative block-table management logic:
class KVBlockPool:def __init__(self, block_size, num_blocks):self.block_size = block_sizeself.free = list(range(num_blocks))self.table = {} # seq_id -> [block_id]self.hash_map = {} # prefix_hash -> block_iddef alloc(self, seq_id, tokens):blocks = []for chunk in chunked(tokens, self.block_size):h = prefix_hash(chunk)bid = self.hash_map.get(h) or self.free.pop()blocks.append(bid)self.table[seq_id] = blocksreturn blocksdef release(self, seq_id):for bid in self.table.pop(seq_id, []):self.free.append(bid)
3. Communication and Parallelism: Hide Collective Communication Behind Compute
In multi-GPU and multi-node deployments, tensor parallelism, pipeline parallelism, and expert parallelism introduce substantial collective communication. Key optimization points are overlap and topology awareness:
- Split per-layer all-reduce/reduce-scatter into finer-grained chunks and execute them overlapped with the next segment of computation;
- Map parallel dimensions according to interconnect topology, avoiding low-bandwidth cross-node links;
- Use finer-grained micro-batching for pipeline parallelism to compress pipeline bubbles;
- Pin processes to devices at the communication-library level to reduce tail latencies caused by affinity jitter.
4. Scheduling and Flow: Turn “Average” into “Stable”
Online service quality is determined by the tail. The scheduler’s goal is to keep devices continuously full while reserving latency budgets for interactive requests:
loop:batch = scheduler.form_batch()batch.admit_by(priority, ttft_budget, kv_capacity)out = engine.step(batch) # compute and communication overlapfor seq in batch.finished_or_preempted():scheduler.requeue_or_release(seq)metrics.emit(batch) # latency, throughput, cache hit rate
Key mechanisms include continuous batching (iteration-level rather than request-level scheduling), preemption with a choice between recomputation and swap-out, resource pools divided by business priority, and adaptive admission control and rate limiting based on queue watermarks. Production environments must also prepare fallback paths: input truncation for extremely long inputs, output length caps, and model-tier routing.
3. Evaluate Latency and Economics in the Same Table
Looking only at latency or only at throughput misleads decisions. Establish a four-dimensional metric baseline:
- TTFT (time to first token): Determined by the prefill phase; grows roughly linearly with input length, and constrains chunking sizes and parallelism strategy.
- TPOT / per-stream output speed: Determined by the decode phase; affected by memory bandwidth and intra-batch concurrency.
- Effective throughput: Completed tokens per unit time, distinguishing input from output, and excluding failures and retries.
- Unit economics: Per-card hourly effective output converted into revenue or cost, accounting for peak/off-peak pricing, utilization, and cache hit rate.
A reusable estimate is:
Per-card hourly revenue ≈ per-card output tokens per second × 3600 × unit token price
Note that “output tokens per second” here must be a measured value after deducting bubbles and queuing, not a stress-test peak. All performance and economics figures disclosed externally should come from real online traffic statistics and state the input length distribution, concurrency, precision configuration, and statistical methodology; otherwise they are not comparable.
4. Engineering Foundation: Observability Determines the Optimization Ceiling
Without measurement there is no optimization. Production-grade inference requires at least three kinds of general cloud capabilities: a container platform for elastic scaling and rolling upgrades; log services collecting per-request traces (queuing time, prefill time, decode steps); and monitoring/alerting for TTFT percentiles, cache hit rates, memory watermarks, device temperature, and throttling events. Display P50/P90/P99 simultaneously—averages systematically mask the tail, and the tail is what generates user complaints.
5. Implementation Roadmap and Common Pitfalls
- Build the baseline first: Fix the dataset and stress-test scripts; record both operator-level and end-to-end results.
- Attack memory bandwidth next: Prioritize operator fusion and KV-cache paging—usually the largest gains with the lowest risk.
- Tune parallelism after that: Choose parallel dimensions based on measured bandwidth; avoid blindly stacking pipeline parallelism.
- Do scheduling last: Introduce priorities, preemption, and elasticity on top of stable single-instance performance.
- Continuously regression-test: Run the full benchmark suite after every driver or framework upgrade to prevent silent performance degradation.
Three common pitfalls:
- Using peak stress-test data for capacity planning;
- Ignoring the input-length long tail, which distorts cache and memory estimates;
- Optimizing only average latency without setting tail-latency SLOs.
6. Conclusion
The new generation of infrastructure represented by domestic AI accelerators is already capable of delivering AI inference services at the highest standard. This conclusion holds only if operators, memory, communication, and scheduling are all addressed simultaneously, with real business traffic—not offline stress tests—as the acceptance criterion. Open-sourcing production-grade inference code and optimization methods matters not because of the code itself, but because it lets others skip the cycle of repeated mistakes and focus their energy on business and model innovation. This is the concrete engineering form of democratizing technology.
