LLM Inference Optimization: Fused Kernels and Adaptation to Chinese AI Accelerators
Optimizing LLM inference requires more than high peak compute utilization. This article explains how fused kernels, shape specialization, memory management, distributed parallelism, and reproducible benchmarks support adaptation to Chinese-developed AI accelerators. It also outlines the end-to-end metrics and deployment quality gates needed to turn kernel-level improvements into reliable serving performance.
Claims that the Prefill stage approaches peak hardware performance are easy to share—and easy to misinterpret. When public materials report that “Prefill reaches 98.5% of hardware peak,” engineering teams should examine the measurement conditions before focusing on the number: model dimensions, batch size, input length, numerical precision, whether end-to-end data transfers are included, whether only core operators are measured, whether accelerator clocks are fixed, and whether the result represents steady-state performance or a momentary peak.
Without these constraints, 98.5% and 80% are not directly comparable. For the ecosystem of Chinese-developed AI accelerators, the value of such a result is that it can demonstrate an integrated software optimization workflow spanning fused kernels, data layouts, specialized execution paths, and benchmarking—not simply an isolated benchmark score.
1. Distinguish Prefill from Decode
LLM inference typically has two stages. Prefill processes the input context in one pass. It involves substantial computation and dense matrix multiplication, so optimization focuses on compute utilization and time to first token. Decode generates tokens one at a time, with frequent memory access and relatively little computation per step. Its priorities are typically KV cache bandwidth, batching efficiency, and tail latency.
These stages have different bottlenecks. A single peak-utilization figure cannot adequately describe both.
Looking only at operator-level peak performance during Prefill can obscure three issues:
- End-to-end latency also includes request queuing, scheduling, sampling, networking, and output delivery.
- Decode can become a major cost driver in long-context workloads.
- Real traffic has long-tailed input and output length distributions that static benchmarks cannot fully cover.
To assess whether hardware adaptation is genuinely comprehensive, track time to first token (TTFT), time per output token (TPOT), throughput, P99 latency, device memory usage, communication wait time, and error rates—not just the peak result of one microbenchmark.
2. Fused Kernels: Consolidating Memory Access into a Single Data Path
Public code and technical materials often describe fusion that combines normalization, positional encoding, attention computation, and data-format conversion into fewer kernel launches.
Consider “norm + RoPE + attention + cast.” An unfused implementation may repeatedly read and write intermediate tensors: normalization results are written to global memory, positional encoding reads them again, attention scores and Softmax results pass through additional intermediate storage, and precision conversion follows.
With fusion, intermediate results remain in on-chip memory or registers wherever possible. This reduces both global memory bandwidth pressure and kernel launch and scheduling overhead.
The following code illustrates the logical attention path:
def prefill_forward(x, w_qkv, cos, sin, mask, scale):qkv = matmul(x, w_qkv)q, k, v = split_heads(qkv)q = apply_rope(q, cos, sin)k = apply_rope(k, cos, sin)score = scaled_dot_product(q, k) * scale + maskprob = stable_softmax(score)out = matmul(prob, v)return cast(out, target_dtype)
This is a logical sketch, not a high-performance implementation. Production kernels require tiling, pipelined double buffering, mask-boundary handling, and numerical stability safeguards. They also need specialized implementations for fixed head dimensions, sequence-length ranges, and batch sizes.
Fewer operators are not always better. Fusion must balance register pressure, on-chip memory capacity, code size, and compilation time. Excessive fusion can reduce occupancy or cause register spills, offsetting its benefits.
3. Shape Specialization and Graph Compilation
When model architecture and accelerator characteristics are stable, an inference framework can generate specialized execution paths for frequently encountered shapes.
For example, Prefill may use specialized large matrix multiplications and fused attention, while Decode uses separate implementations optimized for small batches and KV cache reads. The scheduler must select kernels according to the inference stage, precision, head dimension, batch size, and sequence length:
if phase == "prefill" and dtype == "bf16" and shape_is_supported(shape):kernel = fused_prefill_kernelelif phase == "decode" and kv_cache_is_paged:kernel = paged_decode_kernelelse:kernel = generic_fallback_kernel
The central challenge is controlling the combinatorial growth of specialized implementations. Teams should use shape buckets to group varying input lengths into a finite set of ranges, prioritize compilation for common production workloads, and retain fallback paths for long-tail inputs.
Every additional specialized implementation needs numerical consistency tests, performance regression tests, and a compilation-cache strategy. Otherwise, a faster path may prove unusable, or an untested fallback may fail when it is needed.
4. Memory Systems: High Bandwidth Does Not Guarantee High Serving Throughput
Decode is often constrained by KV cache read bandwidth. Paged KV caching, continuous batching, prefix reuse, and appropriate quantization strategies can reduce unnecessary memory access.
Quantization reduces bandwidth and capacity requirements, but its effects on accuracy, calibration-set coverage, and long-context stability must be evaluated. Average metrics are insufficient: testing should also cover boundary cases, long-tail problems, and severe errors.
At the hardware level, high-bandwidth memory systems increase achievable bandwidth through wider interfaces, more channels, shorter interconnect distances, and advanced packaging. Technologies such as hybrid bonding can increase the number of bonding sites and shorten interconnects, but remain constrained by yield, stack height, capacity, cooling, and cost.
Peak bandwidth should therefore not be treated as equivalent to application throughput. Effective performance depends on access patterns, concurrency, data layout, and cache hit rates.
5. Distributed Parallelism: Overlap Communication with Computation
When a single accelerator lacks sufficient memory capacity or compute performance, inference may require tensor parallelism, pipeline parallelism, or expert parallelism.
Prefill has high compute density, allowing larger batches to amortize communication overhead. Decode performs less computation per step, making communication stalls more visible. Optimization must account for the size, topology, and frequency of collective operations such as AllReduce and AllToAll, while overlapping communication with computation wherever possible.
For mixture-of-experts models, expert parallelism adds routing overhead and AllToAll communication. Load balance, heavily used experts, and tail-request latency require particular attention.
Separating Prefill and Decode into different deployments is another common approach. Prefill resources can prioritize compute throughput, while Decode resources prioritize low latency and high concurrency. The two stages can use different parallelism strategies and resource allocations.
However, separation introduces KV cache transfer overhead and more complex scheduling. Its benefits must be validated through end-to-end load testing.
6. Benchmarking: Define Measurement Conditions Before Comparing Peaks
A reproducible benchmark should record at least:
- Inference stage
- Batch size
- Input and output lengths
- Numerical precision
- Mask configuration
- Whether sampling is included
- Whether preprocessing and postprocessing are included
- Accelerator clock frequency
- Warm-up and repetition counts
Store these settings in a version-controlled configuration file:
workload:phase: prefillbatch_size: [1, 8, 32]input_len: [128, 1024, 4096]output_len: 1dtype: bf16warmup: 3repeat: 10metrics:- effective_tflops- memory_bandwidth- ttft_p50_p99- tpot_p50_p99- request_throughput- error_max_relative
Reports should include compute utilization, memory bandwidth, communication wait time, peak device memory usage, and error rates. They should also clearly distinguish microbenchmark results from serving-level results.
A microbenchmark can demonstrate that a fused kernel approaches peak hardware performance. It cannot directly establish production requests per second. Serving-level evaluation must cover realistic traffic distributions, concurrency patterns, timeouts and retries, and multi-tenant isolation.
7. Deployment Governance: Put Quality Gates Around Performance Changes
As fused kernels and specialized implementations multiply, regression testing becomes increasingly important. At a minimum, deployment gates should:
- Compare numerical results against a reference implementation and enforce maximum absolute and relative error limits.
- Cover empty inputs, extremely long contexts, fully masked inputs, boundary positions, and unusual precision conditions.
- Verify that fallback paths work.
- Monitor device memory fragmentation, thermal throttling, and error rates during extended runs.
Roll out changes through a small-traffic canary, gradually increasing exposure by tenant or request percentage. Monitor TTFT, TPOT, P99 latency, throughput, failure rate, device memory usage, and communication wait time.
If performance regresses or numerical anomalies appear, the system should be able to roll back automatically to stable kernels. Observability must span operators, graph compilation, scheduling, and runtime execution rather than relying on a single accelerator-utilization metric.
8. Common Pitfalls and Conclusion
Common mistakes include:
- Treating microbenchmark peaks as production throughput.
- Optimizing Prefill while overlooking Decode’s long-tail costs.
- Fusing operators for its own sake, increasing register pressure and reducing occupancy.
- Evaluating quantization only through average results, without testing long contexts and boundary cases.
- Relying on static batching that does not match real traffic.
- Ignoring clock frequency, thermal conditions, and multi-tenant interference when interpreting results.
“98.5% of hardware peak” can be a useful engineering signal, but it is best understood as an intermediate result of hardware–software co-design. Fused kernels reduce memory traffic; shape specialization improves execution efficiency; data layouts and memory hierarchies align with accelerator characteristics; benchmarks document measurement conditions; and deployment governance keeps changes testable and reversible.
For teams adapting LLM inference to Chinese-developed AI accelerators, the reusable capability is not a single headline number. It is a complete performance engineering workflow—from kernels and graph compilation to runtime scheduling and quality gates.
