LLM Inference Operator Fusion and Deep Adaptation to Domestic Chips: A Practical Guide
This article explains why LLM inference optimization must start at the operator level, how Prefill and Decode stages differ in their performance bottlenecks, and how to apply operator fusion, specialized kernels, and hardware-software co-design to improve utilization. It covers attention fusion design, model-type specialization, memory bandwidth considerations, and a practical checklist for reproducible performance engineering.
1. Why Inference Optimization Starts at the Operator Level
In large model inference, end-to-end latency is not determined by parameter count alone. It is shaped by three factors working together: operator implementation quality, memory bandwidth, and parallelism strategy. A common misconception is that switching to faster hardware will deliver a linear performance gain. Engineering experience shows the opposite: on the same hardware, different implementations of the same operator can differ in throughput by several times. The gap usually comes from three sources:
- Too many memory accesses, with intermediate results repeatedly written back to VRAM.
- Operators that are too fine-grained, so kernel launch and scheduling overhead dominates.
- Frequent numerical format conversions, wasting both bandwidth and compute.
So the first step in inference optimization is not tuning parameters. It is breaking the computation graph down to the operator level and identifying which operators are memory-bound and which are compute-bound. Only after this classification do fusion, quantization, and parallelism have a clear target.
2. Two-Stage Performance Profile: How Prefill and Decode Differ
LLM inference typically has two stages with very different performance characteristics:
- Prefill stage: The entire input sequence is processed at once. Matrix multiplications are large and arithmetic intensity is high, making this a compute-bound scenario. The core metric is the hardware’s peak floating-point utilization (MFU); approaching the peak means the tensor compute units are fully fed.
- Decode stage: Tokens are generated autoregressively, one position per step. The matrices go from “fat” to “thin,” arithmetic intensity drops sharply, and the bottleneck shifts to memory bandwidth and KV Cache reads/writes. This is a memory-bound scenario.
This explains a frequently misread phenomenon: the same set of operators can reach more than 90% of hardware peak in Prefill but only around 80% in Decode. This is not an implementation regression; it is the physical ceiling defined by the roofline model. When evaluating optimization results, utilization must be reported per stage; otherwise the conclusions are not comparable.
A schematic evaluation logic can be written as:
# Pseudocode: measure effective compute and bandwidth utilization per stagedef profile_stage(stage_logits, elapsed, peak_flops, peak_bw, bytes_moved):flops = count_flops(stage_logits) # FLOPs derived from the model structureachieved = flops / elapsedreturn {"stage": stage_name, # prefill or decode"mfu": achieved / peak_flops, # compute utilization"mbu": bytes_moved / elapsed / peak_bw # bandwidth utilization}
The decision rule is straightforward: if mbu is significantly higher than mfu, the stage is memory-bound and you should prioritize data reuse and cache optimization. Otherwise, start from compute density and parallelism.
3. Attention Operator Fusion: A head_dim=128 Example
Attention is the most memory-intensive module in inference. A naive implementation splits Q/K/V projection, normalization, positional encoding, attention computation, and type conversion into separate kernels, with intermediate tensors moving in and out of VRAM repeatedly. The core idea of fusion is to merge the tightly data-dependent steps in this chain into a single kernel, keeping intermediate results in on-chip cache (SRAM/shared memory) and writing back only the final result.
For a common 128-dimension head width configuration, a fused kernel typically has these responsibilities:
- Read Q/K/V tiles.
- Perform normalization and positional encoding (RoPE) on-chip.
- Compute attention scores in tiles with online softmax, avoiding materializing the full score matrix.
- Multiply by V and apply output type conversion, writing back once.
The benefits of fusion are compound: fewer VRAM reads and writes, fewer kernel launches, and higher on-chip data reuse. In practice, tile size must be matched to shared memory capacity. Tiles that are too large cause overflow; tiles that are too small provide insufficient reuse. This requires empirical scanning on the target hardware.
4. Specialized Operator Instances and Model-Type Tagging
When an operator library contains many specialized instance files targeting specific model configurations, tagged with explicit model-type enums, optimization moves from “general approximation” to “precise specialization.” The value is:
- Eliminating runtime branches: No conditional handling of different head widths or precisions inside a general kernel, resulting in a cleaner instruction stream.
- Enabling compile-time constant folding: Once dimensions and strides become compile-time constants, address calculation and loop unrolling can be fully optimized.
- Better maintainability: New model shapes are added as new instances without affecting existing paths.
In code organization, a three-layer structure is common: a general fallback implementation, specialized implementations, and runtime selection. The selection logic uses model configuration and hardware capability detection, as shown below:
// Schematic: select a specialized kernel by model shape and device capabilitiesKernel select_kernel(const ModelConfig& cfg, const DeviceCaps& caps) {if (cfg.model_type == ModelType::V41 && cfg.head_dim == 128) {if (caps.supports_fused_norm_rope_attn)return Kernel::FusedHead128; // fused specialized pathreturn Kernel::UnfusedHead128; // general fallback path}return Kernel::Generic;}
Specialized paths must be paired with precision alignment tests that compare numerical deviations against a reference implementation layer by layer, avoiding the situation where performance improves but results drift.
5. From Code to Ecosystem: Conditions for a Hardware-Software Co-Design Loop
Single-point operator optimization is only the starting point. Real performance gains depend on a hardware-software co-design loop, which requires four conditions to be met simultaneously:
- Pluggable framework layer: The operator library exposes a unified abstraction so the upper framework can switch backends automatically based on hardware capabilities.
- Graph compilation and scheduling coordination: Operator fusion needs pattern-matching support at the computation graph level to dispatch fusible subgraphs to the backend as a whole.
- Unified precision and numerical conventions: Low-precision accumulation, scaling factors, and rounding strategies must be consistent end to end.
- Complete observability: Monitoring, alerting, and logging services collect per-stage utilization, VRAM usage, and kernel timing to form a continuously regressed baseline.
For cloud deployment, a common approach is to run inference services on a container platform, store model and operator artifacts in object storage, use a message queue for peak shaving, and set alert thresholds on latency and utilization. Baidu AI Cloud provides standardized support for these general capabilities; specific choices should still be based on measured baselines.
6. Memory Bandwidth Roadmap: Interface Width and Stacked Bonding
The Decode stage bottleneck is bandwidth, so HBM interface width, channel count, and stacked bonding process directly determine the ceiling. Public industry roadmaps show that wafer-on-wafer hybrid bonding across multiple layers, combined with more channels and wider data interfaces, can multiply bandwidth at the same data rate. Practical implications for developers:
- After a bandwidth increase, the Decode roofline ceiling rises, and operators that were memory-bound may become compute-bound again, requiring fresh bottleneck identification.
- Capacity and bandwidth must match the KV Cache growth curve; in long-context scenarios, insufficient capacity triggers swapping and increases latency.
- When evaluating new hardware, always rerun the per-stage utilization baseline instead of reusing old conclusions.
7. Deployment Checklist
- Have operators been classified as memory-bound or compute-bound at operator granularity, with MFU and MBU reported per stage?
- Has the attention chain been fused across normalization, positional encoding, attention, and type conversion, with intermediate tensors resident on-chip?
- Are specialized operators paired with layer-by-layer precision alignment and regression tests?
- Has tile size been scanned on the target hardware, and does shared memory overflow?
- Are monitoring, alerting, and logging baselines in place to support performance comparison across versions?
- After introducing new hardware or a new bandwidth scheme, have the roofline and bottleneck attribution been retested?
8. Conclusion
The gap in inference performance usually lies not in “which chip is used” but in “whether operators are designed for the hardware.” The sustainable performance engineering method is to separate the two-stage bottlenecks, fuse memory-intensive chains, bind specialized paths to precision alignment, and make observability routine. Once the hardware-software co-design loop is running, hardware peak utilization rises naturally. Behind this are many reproducible, regression-friendly engineering details, not a single-point conclusion.
